source
stringlengths
3
92
c
stringlengths
26
2.25M
eltwise.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_ELTWISE_H_ #define MACE_KERNELS_ELTWISE_H_ #include <algorithm> #include <functional> #include <memory> #include <utility> #include <vector> #include "mace/core/future.h" #include "mace/core/tensor.h" #ifdef MACE_ENABLE_OPENCL #include "mace/core/runtime/opencl/cl2_header.h" #endif // MACE_ENABLE_OPENCL namespace mace { namespace kernels { enum EltwiseType { SUM = 0, SUB = 1, PROD = 2, DIV = 3, MIN = 4, MAX = 5, NEG = 6, ABS = 7, SQR_DIFF = 8, POW = 9, EQUAL = 10, NONE = 11, }; static bool IsLogicalType(EltwiseType type) { return type == EQUAL; } inline index_t GetIndex(const std::vector<index_t> &shape, const std::vector<index_t> &index) { index_t idx = 0; for (size_t i = 0; i < shape.size(); ++i) { if (shape[i] > 1) { idx = idx * shape[i] + index[i]; } } return idx; } inline void IncreaseIndex(const std::vector<index_t> &shape, std::vector<index_t> *index) { for (index_t i = static_cast<index_t>(shape.size()) - 1; i >= 0; --i) { ++(*index)[i]; if ((*index)[i] >= shape[i]) { (*index)[i] -= shape[i]; } else { break; } } } template <typename T, typename DstType> inline void TensorGeneralBroadcastEltwise( const EltwiseType type, const T *input0, const T *input1, const std::vector<float> &coeff, const bool swapped, const std::vector<index_t> &input0_shape, const std::vector<index_t> &input1_shape, const std::vector<index_t> &output_shape, DstType *output) { const index_t output_size = std::accumulate( output_shape.begin(), output_shape.end(), 1, std::multiplies<index_t>()); std::vector<index_t> out_index(output_shape.size(), 0); switch (type) { case SUM: if (coeff.empty()) { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input0[idx0] + input1[idx1]; IncreaseIndex(output_shape, &out_index); } } else { std::vector<float> coeff_copy = coeff; if (swapped) { std::swap(coeff_copy[0], coeff_copy[1]); } for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input0[idx0] * coeff_copy[0] + input1[idx1] * coeff_copy[1]; IncreaseIndex(output_shape, &out_index); } } break; case SUB: if (!swapped) { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input0[idx0] - input1[idx1]; IncreaseIndex(output_shape, &out_index); } } else { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input1[idx1] - input0[idx0]; IncreaseIndex(output_shape, &out_index); } } break; case PROD: for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input0[idx0] * input1[idx1]; IncreaseIndex(output_shape, &out_index); } break; case DIV: if (!swapped) { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input0[idx0] / input1[idx1]; IncreaseIndex(output_shape, &out_index); } } else { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input1[idx1] / input0[idx0]; IncreaseIndex(output_shape, &out_index); } } break; case MIN: for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = std::min(input1[idx1], input0[idx0]); IncreaseIndex(output_shape, &out_index); } break; case MAX: for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = std::max(input1[idx1], input0[idx0]); IncreaseIndex(output_shape, &out_index); } break; case SQR_DIFF: for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = std::pow(input1[idx1] - input0[idx0], 2.f); IncreaseIndex(output_shape, &out_index); } break; case POW: if (!swapped) { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = std::pow(input0[idx0], input1[idx1]); IncreaseIndex(output_shape, &out_index); } } else { for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = std::pow(input1[idx1], input0[idx0]); IncreaseIndex(output_shape, &out_index); } } break; case EQUAL: for (index_t i = 0; i < output_size; ++i) { const index_t idx0 = GetIndex(input0_shape, out_index); const index_t idx1 = GetIndex(input1_shape, out_index); output[i] = input1[idx1] == input0[idx0]; IncreaseIndex(output_shape, &out_index); } break; default: LOG(FATAL) << "Eltwise op not support type " << type; } } template <typename T, typename DstType> inline void TensorBroadcastEltwise(const EltwiseType type, const T *input0, const T *input1, const std::vector<float> &coeff, const index_t diff_size, const index_t common_size, const bool swapped, DstType *output) { switch (type) { case SUM: if (coeff.empty()) { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] + input1[i]; } } } else { std::vector<float> coeff_copy = coeff; if (swapped) { std::swap(coeff_copy[0], coeff_copy[1]); } #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] * coeff_copy[0] + input1[i] * coeff_copy[1]; } } } break; case SUB: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] - input1[i]; } } } else { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input1[i] - input0[i + d * common_size]; } } } break; case PROD: #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] * input1[i]; } } break; case DIV: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] / input1[i]; } } } else { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input1[i] / input0[i + d * common_size]; } } } break; case MIN: #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = std::min(input0[i + d * common_size], input1[i]); } } break; case MAX: #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = std::max(input0[i + d * common_size], input1[i]); } } break; case SQR_DIFF: #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = std::pow(input0[i + d * common_size] - input1[i], 2.f); } } break; case POW: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = std::pow(input0[i + d * common_size], input1[i]); } } } else { #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = std::pow(input1[i], input0[i + d * common_size]); } } } break; case NEG: #pragma omp parallel for for (index_t i = 0; i < diff_size * common_size; ++i) { output[i] = -input0[i]; } break; case ABS: #pragma omp parallel for for (index_t i = 0; i < diff_size * common_size; ++i) { output[i] = std::fabs(input0[i]); } break; case EQUAL: #pragma omp parallel for collapse(2) for (index_t d = 0; d < diff_size; ++d) { for (index_t i = 0; i < common_size; ++i) { output[i + d * common_size] = input0[i + d * common_size] == input1[i]; } } break; default: LOG(FATAL) << "Eltwise op not support type " << type; } } // Multiplication is costly, so we specialize the following case. template <typename T, typename DstType> inline void TensorEltwise(const EltwiseType type, const T *input0, const T *input1, const std::vector<float> &coeff, const index_t size, const bool swapped, DstType *output) { switch (type) { case SUM: if (coeff.empty()) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] + input1[i]; } } else { std::vector<float> coeff_copy = coeff; if (swapped) { std::swap(coeff_copy[0], coeff_copy[1]); } #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] * coeff_copy[0] + input1[i] * coeff_copy[1]; } } break; case SUB: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] - input1[i]; } } else { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input1[i] - input0[i]; } } break; case PROD: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] * input1[i]; } break; case DIV: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] / input1[i]; } } else { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input1[i] / input0[i]; } } break; case MIN: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::min(input0[i], input1[i]); } break; case MAX: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::max(input0[i], input1[i]); } break; case SQR_DIFF: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input0[i] - input1[i], 2.f); } break; case POW: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input0[i], input1[i]); } } else { for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input1[i], input0[i]); } } break; case NEG: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = -input0[i]; } break; case ABS: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::fabs(input0[i]); } break; case EQUAL: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] == input1[i]; } break; default: LOG(FATAL) << "Eltwise op not support type " << type; } } // Multiplication is costly, so we specialize the following case. template <typename T, typename DstType> inline void TensorScalarEltwise(const EltwiseType type, const T *input0, const T input1, const std::vector<float> &coeff, const index_t size, const bool swapped, DstType *output) { switch (type) { case SUM: if (coeff.empty()) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] + input1; } } else { std::vector<float> coeff_copy = coeff; if (swapped) { std::swap(coeff_copy[0], coeff_copy[1]); } #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] * coeff_copy[0] + input1 * coeff_copy[1]; } } break; case SUB: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] - input1; } } else { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input1 - input0[i]; } } break; case PROD: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] * input1; } break; case DIV: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] / input1; } } else { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input1 / input0[i]; } } break; case MIN: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::min(input0[i], input1); } break; case MAX: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::max(input0[i], input1); } break; case SQR_DIFF: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input0[i] - input1, 2.f); } break; case POW: if (!swapped) { #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input0[i], input1); } } else { for (index_t i = 0; i < size; ++i) { output[i] = std::pow(input1, input0[i]); } } break; case NEG: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = -input0[i]; } break; case ABS: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = std::fabs(input0[i]); } break; case EQUAL: #pragma omp parallel for for (index_t i = 0; i < size; ++i) { output[i] = input0[i] == input1; } break; default: LOG(FATAL) << "Eltwise op not support type " << type; } } template <typename T, typename DstType> inline void TensorEltwisePerChannel(const EltwiseType type, const T *input0, const T *input1, const std::vector<float> &coeff, const index_t batch0, const index_t batch1, const index_t channel, const index_t image_size, const bool swapped, DstType *output) { switch (type) { case SUM: if (coeff.empty()) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] + in1_ptr[c]; } } } } else { std::vector<float> coeff_copy = coeff; if (swapped) { std::swap(coeff_copy[0], coeff_copy[1]); } #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] * coeff_copy[0] + in1_ptr[c] * coeff_copy[1]; } } } } break; case SUB: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] - in1_ptr[c]; } } } } else { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in1_ptr[c] - in0_ptr[i]; } } } } break; case PROD: #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] * in1_ptr[c]; } } } break; case DIV: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] / in1_ptr[c]; } } } } else { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in1_ptr[c] / in0_ptr[i]; } } } } break; case MIN: #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = std::min(in0_ptr[i], in1_ptr[c]); } } } break; case MAX: #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = std::max(in0_ptr[i], in1_ptr[c]); } } } break; case SQR_DIFF: #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = std::pow(in0_ptr[i] - in1_ptr[c], 2.f); } } } break; case POW: if (!swapped) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = std::pow(in0_ptr[i], in1_ptr[c]); } } } } else { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = std::pow(in1_ptr[c], in0_ptr[i]); } } } } break; case NEG: #pragma omp parallel for for (index_t i = 0; i < batch0 * channel * image_size; ++i) { output[i] = -input0[i]; } break; case ABS: #pragma omp parallel for for (index_t i = 0; i < batch0 * channel * image_size; ++i) { output[i] = std::fabs(input0[i]); } break; case EQUAL: #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch0; ++b) { for (index_t c = 0; c < channel; ++c) { const T *in0_ptr = input0 + ((b * channel) + c) * image_size; const T *in1_ptr = input1 + (batch1 > 1 ? b * channel : 0); DstType *out_ptr = output + ((b * channel) + c) * image_size; for (index_t i = 0; i < image_size; ++i) { out_ptr[i] = in0_ptr[i] == in1_ptr[c]; } } } break; default: LOG(FATAL) << "Eltwise op not support type " << type; } } struct EltwiseFunctorBase { EltwiseFunctorBase(const EltwiseType type, const std::vector<float> &coeff, const float value, const DataFormat data_format) : type_(type), coeff_(coeff), value_(value), data_format_(data_format) {} EltwiseType type_; std::vector<float> coeff_; float value_; DataFormat data_format_; }; template <DeviceType D, typename T> struct EltwiseFunctor : EltwiseFunctorBase { EltwiseFunctor(const EltwiseType type, const std::vector<float> &coeff, const float value, // keep it float as it comes from arg const DataFormat data_format) : EltwiseFunctorBase(type, coeff, value, data_format) {} template <typename DstType> MaceStatus DoEltwise(const Tensor *input0, const Tensor *input1, Tensor *output) { bool swapped = false; if (input0->size() < input1->size()) { std::swap(input0, input1); swapped = true; } // check if we can broadcast tensor uint32_t rank_diff = static_cast<uint32_t>(input0->dim_size() - input1->dim_size()); if (data_format_ == NCHW) { MACE_CHECK( (input0->dim_size() == 4) && ((input1->dim_size() == 0) || (input1->dim_size() == 4 && input1->dim(1) == input0->dim(1) && (input1->dim(0) == input0->dim(0) || input1->dim(0) == 1)) || (input1->dim_size() == 1 && input1->dim(0) == input0->dim(1))), "only support broadcast channel dimension"); } else { for (uint32_t i = 0; i < input1->dim_size(); ++i) { MACE_CHECK(input0->dim(rank_diff + i) == 1 || input1->dim(i) == 1 || input0->dim(rank_diff + i) == input1->dim(i), "Element-Wise op only support tail dimensions broadcast"); } } Tensor::MappingGuard input0_guard(input0); Tensor::MappingGuard input1_guard(input1); const T *input0_ptr = input0->data<T>(); const T *input1_ptr = input1->data<T>(); if (data_format_ == NCHW && input1->dim_size() > 0 && input1->size() < input0->size()) { MACE_RETURN_IF_ERROR(output->ResizeLike(input0)); Tensor::MappingGuard output_guard(output); DstType *output_ptr = output->mutable_data<DstType>(); TensorEltwisePerChannel( type_, input0_ptr, input1_ptr, coeff_, input0->dim(0), input1->dim_size() == 1 ? 1 : input1->dim(0), input0->dim(1), input0->dim(2) * input0->dim(3), swapped, output_ptr); } else { const std::vector<index_t> &input0_shape = input0->shape(); std::vector<index_t> input1_shape(rank_diff, 1); input1_shape.insert(input1_shape.end(), input1->shape().begin(), input1->shape().end()); std::vector<index_t> output_shape(input0->dim_size(), 0); for (unsigned int i = 0; i < input0_shape.size(); ++i) { output_shape[i] = std::max(input0_shape[i], input1_shape[i]); } MACE_RETURN_IF_ERROR(output->Resize(output_shape)); Tensor::MappingGuard output_guard(output); DstType *output_ptr = output->mutable_data<DstType>(); bool need_general_broadcast = false; for (uint32_t i = 0; i < input1->dim_size(); ++i) { if ((input0->dim(rank_diff + i) == 1 && input1->dim(i) > 1) || (input0->dim(rank_diff + i) > 1 && input1->dim(i) == 1)) { need_general_broadcast = true; break; } } if (need_general_broadcast) { TensorGeneralBroadcastEltwise(type_, input0_ptr, input1_ptr, coeff_, swapped, input0_shape, input1_shape, output_shape, output_ptr); } else if (input1->size() == input0->size()) { TensorEltwise(type_, input0_ptr, input1_ptr, coeff_, input0->size(), swapped, output_ptr); } else if (input1->size() < input0->size()) { if (input1->size() > 1) { index_t common_size = input1->size(); index_t diff_size = input0->size() / common_size; TensorBroadcastEltwise(type_, input0_ptr, input1_ptr, coeff_, diff_size, common_size, swapped, output_ptr); } else { TensorScalarEltwise(type_, input0_ptr, input1_ptr[0], coeff_, input0->size(), swapped, output_ptr); } } } return MACE_SUCCESS; } MaceStatus operator()(const Tensor *input0, const Tensor *input1, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); if (input1 == nullptr) { scalar_tensor_.Resize({}); Tensor::MappingGuard guard(&scalar_tensor_); auto scalar_data = scalar_tensor_.mutable_data<T>(); scalar_data[0] = static_cast<T>(value_); input1 = &scalar_tensor_; } if (IsLogicalType(type_)) { // as we do not have bool-type tensor, we use int type return DoEltwise<int32_t>(input0, input1, output); } else { return DoEltwise<T>(input0, input1, output); } } Tensor scalar_tensor_; }; #ifdef MACE_ENABLE_OPENCL template <typename T> struct EltwiseFunctor<DeviceType::GPU, T> : EltwiseFunctorBase { EltwiseFunctor(const EltwiseType type, const std::vector<float> &coeff, const float value, const DataFormat data_format) : EltwiseFunctorBase(type, coeff, value, data_format) {} MaceStatus operator()(const Tensor *input0, const Tensor *input1, Tensor *output, StatsFuture *future); cl::Kernel kernel_; uint32_t kwg_size_; std::unique_ptr<BufferBase> kernel_error_; std::vector<index_t> input_shape_; }; #endif // MACE_ENABLE_OPENCL } // namespace kernels } // namespace mace #endif // MACE_KERNELS_ELTWISE_H_
GB_unop__identity_int32_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__identity_int32_fp32) // op(A') function: GB (_unop_tran__identity_int32_fp32) // C type: int32_t // A type: float // cast: int32_t cij = GB_cast_to_int32_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int32_t // 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 = x ; // casting #define GB_CAST(z, aij) \ int32_t z = GB_cast_to_int32_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = GB_cast_to_int32_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int32_fp32) ( int32_t *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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; int32_t z = GB_cast_to_int32_t ((double) (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; int32_t z = GB_cast_to_int32_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int32_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
syr2k.dstblock3.c
/** * This version is stamped on May 10, 2016 * * Contact: * Louis-Noel Pouchet <pouchet.ohio-state.edu> * Tomofumi Yuki <tomofumi.yuki.fr> * * Web address: http://polybench.sourceforge.net */ /* syr2k.c: this file is part of PolyBench/C */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ #include "syr2k.h" /* Array initialization. */ static void init_array(int n, int m, DATA_TYPE *alpha, DATA_TYPE *beta, DATA_TYPE POLYBENCH_2D(C,N,N,n,n), DATA_TYPE POLYBENCH_2D(A,N,M,n,m), DATA_TYPE POLYBENCH_2D(B,N,M,n,m)) { int i, j; *alpha = 1.5; *beta = 1.2; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { A[i][j] = (DATA_TYPE) ((i*j+1)%n) / n; B[i][j] = (DATA_TYPE) ((i*j+2)%m) / m; } for (i = 0; i < n; i++) for (j = 0; j < n; j++) { C[i][j] = (DATA_TYPE) ((i*j+3)%n) / m; } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int n, DATA_TYPE POLYBENCH_2D(C,N,N,n,n)) { int i, j; POLYBENCH_DUMP_START; POLYBENCH_DUMP_BEGIN("C"); for (i = 0; i < n; i++) for (j = 0; j < n; j++) { if ((i * n + j) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n"); fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, C[i][j]); } POLYBENCH_DUMP_END("C"); POLYBENCH_DUMP_FINISH; } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_syr2k(int n, int m, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(C,N,N,n,n), DATA_TYPE POLYBENCH_2D(A,N,M,n,m), DATA_TYPE POLYBENCH_2D(B,N,M,n,m), DATA_TYPE POLYBENCH_2D(At,M,N,m,n), DATA_TYPE POLYBENCH_2D(Bt,M,N,m,n)) { /* Sizes * the linesize is 64 bytes on keller and blum * on keller, L1,L2,L3 is 32 KB, 256 KB, 20480 KB * on blum, 32KB , 256 KB, 6 MB * 64 bits per word; each word is 8 bytes */ // Indices int i, j, k; int ii, jj; // PARAMETER 1 // make sure you change the data size when you change this too!!! int cacheSize = 256; // IN kilobytes !!! // PARAMETER 2 int jumpA = floor((cacheSize * 1024) / (4*8*8)); int jumpB = floor((cacheSize * 1024 ) / (18*8) ); int jump = jumpA; // Misc. Calculations int linesize = 8; // how many bytes per cache line? int blockcount = cacheSize * 1024 / linesize; // kb * (bytes / per kb) / (bytes / per cache line) //BLAS PARAMS //UPLO = 'L' //TRANS = 'N' //A is NxM //At is MxN //B is NxM //Bt is MxN //C is NxN #pragma scop // Note: I can't figure out how to // stack allocate the array; I do this beforehand // and it's untimed. for (ii=0; ii < _PB_N; ii += jump){ for(jj=0; jj < _PB_M; jj += jump){ for (i=ii; i < fmin(jump + ii, _PB_N); i++){ for (j=jj; j < fmin(jump + jj, _PB_M); j++){ // Transpose At[j][i] = A[i][j]; Bt[j][i] = B[i][j]; } } } } // At is M by N // Bt is M by N #pragma omp parallel for for (i = 0; i < _PB_N; i++) { for (j = 0; j <= i; j++) C[i][j] *= beta; for (k = 0; k < _PB_M; k++) for (j = 0; j <= i; j++) { C[i][j] += At[k][j]*alpha*B[i][k] + Bt[k][j]*alpha*A[i][k]; } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int n = N; int m = M; double footprint = 8*(n*n + 2*n*m); // HAVERFORD added code double FP_ops = 3.0 * m * (n + 1) * n; // HAVERFORD added code #ifdef POLYBENCH_GFLOPS polybench_set_program_flops(FP_ops); // HAVERFORD addition #endif #if defined POLYFORD_VERBOSE printf("Starting %s, n=%8d, m=%8d, Footprint %8.4g M, Source FP ops=%8.4g G\n", __FILE__, n, m, footprint / (1024 * 1024), FP_ops/1000000000.0); #endif /* Variable declaration/allocation. */ DATA_TYPE alpha; DATA_TYPE beta; POLYBENCH_2D_ARRAY_DECL(C,DATA_TYPE,N,N,n,n); POLYBENCH_2D_ARRAY_DECL(A,DATA_TYPE,N,M,n,m); POLYBENCH_2D_ARRAY_DECL(B,DATA_TYPE,N,M,n,m); POLYBENCH_2D_ARRAY_DECL(At,DATA_TYPE,M,N,m,n); POLYBENCH_2D_ARRAY_DECL(Bt,DATA_TYPE,M,N,m,n); /* Initialize array(s). */ init_array (n, m, &alpha, &beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_syr2k (n, m, alpha, beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(At), POLYBENCH_ARRAY(Bt)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(n, POLYBENCH_ARRAY(C))); /* Be clean. */ POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
time_dpotrf.c
/** * * @generated d Tue Jan 7 11:45:24 2014 * **/ #define _TYPE double #define _PREC double #define _LAMCH LAPACKE_dlamch_work #define _NAME "PLASMA_dpotrf" /* See Lawn 41 page 120 */ #define _FMULS FMULS_POTRF( N ) #define _FADDS FADDS_POTRF( N ) #include "./timing.c" static int RunTest(int *iparam, double *dparam, real_Double_t *t_) { PASTE_CODE_IPARAM_LOCALS( iparam ); int uplo = PlasmaLower; LDA = max(LDA, N); /* Allocate Data */ PASTE_CODE_ALLOCATE_MATRIX( A, 1, double, LDA, N ); #pragma omp register([LDA*N]A) int runtime = RT_get_runtime(); int ws = RT_get_ws(); if ( runtime == PLASMA_OMPSS ) { PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_QUARK); RT_set_ws(1); } /* Initialiaze Data */ PLASMA_dplgsy( (double)N, N, A, LDA, 51 ); /* Save A and b */ PASTE_CODE_ALLOCATE_COPY( A2, check, double, A, LDA, N ); if ( runtime == PLASMA_OMPSS ) { PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_OMPSS); RT_set_ws(ws); } /* PLASMA DPOSV */ START_TIMING(); PLASMA_dpotrf(uplo, N, A, LDA); STOP_TIMING(); if ( runtime == PLASMA_OMPSS ) { PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_QUARK); RT_set_ws(1); } /* Check the solution */ if (check) { PASTE_CODE_ALLOCATE_MATRIX( B, check, double, LDB, NRHS ); PLASMA_dplrnt( N, NRHS, B, LDB, 5673 ); PASTE_CODE_ALLOCATE_COPY( X, check, double, B, LDB, NRHS ); PLASMA_dpotrs(uplo, N, NRHS, A, LDA, X, LDB); dparam[IPARAM_RES] = d_check_solution(N, N, NRHS, A2, LDA, B, X, LDB, &(dparam[IPARAM_ANORM]), &(dparam[IPARAM_BNORM]), &(dparam[IPARAM_XNORM])); // free(A2); free(B); free(X); } // free(A); if ( runtime == PLASMA_OMPSS ) { PLASMA_Set(PLASMA_RUNTIME_MODE, PLASMA_OMPSS); RT_set_ws(ws); } return 0; }
dcrtpoly.h
/** * @file dcrtpoly.h Represents integer lattice elements with double-CRT * @author TPOC: contact@palisade-crypto.org * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. THIS SOFTWARE IS * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LBCRYPTO_LATTICE_DCRTPOLY_H #define LBCRYPTO_LATTICE_DCRTPOLY_H #include <vector> #include <string> #include "../math/backend.h" #include "../utils/inttypes.h" #include "../utils/exception.h" #include "../lattice/elemparams.h" #include "../lattice/ilparams.h" #include "../lattice/ildcrtparams.h" #include "../lattice/ilelement.h" #include "../lattice/poly.h" #include "../math/nbtheory.h" #include "../math/transfrm.h" #include "../math/distrgen.h" #include "../math/quadfloat.h" namespace lbcrypto { /** * @brief Ideal lattice for the double-CRT representation. * The implementation contains a vector of underlying native-integer lattices * The double-CRT representation of polynomials is a common optimization for * lattice encryption operations. Basically, it allows large-modulus polynamials * to be represented as multiple smaller-modulus polynomials. The double-CRT * representations are discussed theoretically here: * - Gentry C., Halevi S., Smart N.P. (2012) Homomorphic Evaluation of the AES * Circuit. In: Safavi-Naini R., Canetti R. (eds) Advances in Cryptology – * CRYPTO 2012. Lecture Notes in Computer Science, vol 7417. Springer, Berlin, * Heidelberg */ template <typename VecType> class DCRTPolyImpl : public ILElement<DCRTPolyImpl<VecType>, VecType> { public: using Integer = typename VecType::Integer; using Params = ILDCRTParams<Integer>; typedef VecType Vector; typedef DCRTPolyImpl<VecType> DCRTPolyType; typedef DiscreteGaussianGeneratorImpl<NativeVector> DggType; typedef DiscreteUniformGeneratorImpl<NativeVector> DugType; typedef TernaryUniformGeneratorImpl<NativeVector> TugType; typedef BinaryUniformGeneratorImpl<NativeVector> BugType; // this class contains an array of these: using PolyType = PolyImpl<NativeVector>; // the composed polynomial type typedef PolyImpl<VecType> PolyLargeType; static const std::string GetElementName() { return "DCRTPolyImpl"; } // CONSTRUCTORS /** * @brief Constructor that initialized m_format to EVALUATION and calls * m_params to nothing */ DCRTPolyImpl(); /** * Constructor that initializes parameters. * *@param params parameter set required for DCRTPoly. *@param format the input format fixed to EVALUATION. Format is a enum type *that indicates if the polynomial is in Evaluation representation or *Coefficient representation. It is defined in inttypes.h. *@param initializeElementToZero */ DCRTPolyImpl(const shared_ptr<Params> params, Format format = EVALUATION, bool initializeElementToZero = false); const DCRTPolyType &operator=(const PolyLargeType &element); const DCRTPolyType &operator=(const NativePoly &element); /** * @brief Constructor based on discrete Gaussian generator. * * @param &dgg the input discrete Gaussian generator. The dgg will be the seed * to populate the towers of the DCRTPoly with random numbers. * @param params parameter set required for DCRTPoly. * @param format the input format fixed to EVALUATION. Format is a enum type * that indicates if the polynomial is in Evaluation representation or * Coefficient representation. It is defined in inttypes.h. */ DCRTPolyImpl(const DggType &dgg, const shared_ptr<Params> params, Format format = EVALUATION); /** * @brief Constructor based on binary distribution generator. This is not * implemented. Will throw an error. * * @param &bug the input binary uniform generator. The bug will be the seed to * populate the towers of the DCRTPoly with random numbers. * @param params parameter set required for DCRTPoly. * @param format the input format fixed to EVALUATION. Format is a enum type * that indicates if the polynomial is in Evaluation representation or * Coefficient representation. It is defined in inttypes.h. */ DCRTPolyImpl(const BugType &bug, const shared_ptr<Params> params, Format format = EVALUATION); /** * @brief Constructor based on ternary distribution generator. * * @param &tug the input ternary uniform generator. The bug will be the seed * to populate the towers of the DCRTPoly with random numbers. * @param params parameter set required for DCRTPoly. * @param format the input format fixed to EVALUATION. Format is a enum type * that indicates if the polynomial is in Evaluation representation or * Coefficient representation. It is defined in inttypes.h. * @param h - Hamming weight for sparse ternary distribution (by default, when * h = 0, the distribution is NOT sparse) */ DCRTPolyImpl(const TugType &tug, const shared_ptr<Params> params, Format format = EVALUATION, uint32_t h = 0); /** * @brief Constructor based on discrete uniform generator. * * @param &dug the input discrete Uniform Generator. * @param params the input params. * @param &format the input format fixed to EVALUATION. Format is a enum type * that indicates if the polynomial is in Evaluation representation or * Coefficient representation. It is defined in inttypes.h. */ DCRTPolyImpl(DugType &dug, const shared_ptr<Params> params, Format format = EVALUATION); /** * @brief Construct using a single Poly. The Poly is copied into every tower. * Each tower will be reduced to it's corresponding modulus via GetModuli(at * tower index). The format is derived from the passed in Poly. * * @param &element Poly to build other towers from. * @param params parameter set required for DCRTPoly. */ DCRTPolyImpl(const PolyLargeType &element, const shared_ptr<Params> params); /** * @brief Construct using a single NativePoly. The NativePoly is copied into * every tower. Each tower will be reduced to it's corresponding modulus via * GetModuli(at tower index). The format is derived from the passed in * NativePoly. * * @param &element Poly to build other towers from. * @param params parameter set required for DCRTPoly. */ DCRTPolyImpl(const NativePoly &element, const shared_ptr<Params> params); /** * @brief Construct using an tower of ILVectro2ns. The params and format for * the DCRTPoly will be derived from the towers. * * @param &towers vector of Polys which correspond to each tower of DCRTPoly. */ DCRTPolyImpl(const std::vector<PolyType> &elements); /** * @brief Create lambda that allocates a zeroed element for the case when it * is called from a templated class * @param params the params to use. * @param format - EVALUATION or COEFFICIENT */ inline static function<DCRTPolyType()> Allocator( const shared_ptr<Params> params, Format format) { return [=]() { return DCRTPolyType(params, format, true); }; } /** * @brief Allocator for discrete uniform distribution. * * @param params Params instance that is is passed. * @param resultFormat resultFormat for the polynomials generated. * @param stddev standard deviation for the discrete gaussian generator. * @return the resulting vector. */ inline static function<DCRTPolyType()> MakeDiscreteGaussianCoefficientAllocator(shared_ptr<Params> params, Format resultFormat, double stddev) { return [=]() { DggType dgg(stddev); DCRTPolyType ilvec(dgg, params, COEFFICIENT); ilvec.SetFormat(resultFormat); return ilvec; }; } /** * @brief Allocator for discrete uniform distribution. * * @param params Params instance that is is passed. * @param format format for the polynomials generated. * @return the resulting vector. */ inline static function<DCRTPolyType()> MakeDiscreteUniformAllocator( shared_ptr<Params> params, Format format) { return [=]() { DugType dug; return DCRTPolyType(dug, params, format); }; } /** * @brief Copy constructor. * * @param &element DCRTPoly to copy from */ DCRTPolyImpl(const DCRTPolyType &element); /** * @brief Move constructor. * * @param &&element DCRTPoly to move from */ DCRTPolyImpl(const DCRTPolyType &&element); // CLONE OPERATIONS /** * @brief Clone the object by making a copy of it and returning the copy * @return new Element */ DCRTPolyType Clone() const { return std::move(DCRTPolyImpl(*this)); } /** * @brief Makes a copy of the DCRTPoly, but it includes only a sequential * subset of the towers that the original holds. * * @param startTower The index number of the first tower to clone * @param endTower The index number of the last tower to clone * @return new Element */ DCRTPolyType CloneTowers(uint32_t startTower, uint32_t endTower) const { vector<NativeInteger> moduli(endTower - startTower + 1); vector<NativeInteger> roots(endTower - startTower + 1); for (uint32_t i = startTower; i <= endTower; i++) { moduli[i - startTower] = this->GetParams()->GetParams()[i]->GetModulus(); roots[i - startTower] = this->GetParams()->GetParams()[i]->GetRootOfUnity(); } auto params = DCRTPolyImpl::Params(this->GetCyclotomicOrder(), moduli, roots, {}, {}, 0); auto res = DCRTPolyImpl(std::make_shared<typename DCRTPolyImpl::Params>(params), EVALUATION, false); for (uint32_t i = startTower; i <= endTower; i++) { res.SetElementAtIndex(i - startTower, this->GetElementAtIndex(i)); } return std::move(res); } /** * @brief Clone the object, but have it contain nothing * @return new Element */ DCRTPolyType CloneEmpty() const { return std::move(DCRTPolyImpl()); } /** * @brief Clone method creates a new DCRTPoly and clones only the params. The * tower values are empty. The tower values can be filled by another * process/function or initializer list. */ DCRTPolyType CloneParametersOnly() const; /** * @brief Clone with noise. This method creates a new DCRTPoly and clones the * params. The tower values will be filled up with noise based on the discrete * gaussian. * * @param &dgg the input discrete Gaussian generator. The dgg will be the seed * to populate the towers of the DCRTPoly with random numbers. * @param format the input format fixed to EVALUATION. Format is a enum type * that indicates if the polynomial is in Evaluation representation or * Coefficient representation. It is defined in inttypes.h. */ DCRTPolyType CloneWithNoise(const DiscreteGaussianGeneratorImpl<VecType> &dgg, Format format = EVALUATION) const; /** * @brief Destructor. */ ~DCRTPolyImpl(); // GETTERS /** * @brief returns the parameters of the element. * @return the element parameter set. */ const shared_ptr<Params> GetParams() const { return m_params; } /** * @brief returns the element's cyclotomic order * @return returns the cyclotomic order of the element. */ const usint GetCyclotomicOrder() const { return m_params->GetCyclotomicOrder(); } /** * @brief returns the element's ring dimension * @return returns the ring dimension of the element. */ const usint GetRingDimension() const { return m_params->GetRingDimension(); } /** * @brief returns the element's modulus * @return returns the modulus of the element. */ const Integer &GetModulus() const { return m_params->GetModulus(); } /** * @brief returns the element's original modulus, derived from Poly * @return returns the modulus of the element. */ const Integer &GetOriginalModulus() const { return m_params->GetOriginalModulus(); } /** * @brief returns the element's root of unity. * @return the element's root of unity. */ const Integer &GetRootOfUnity() const { static Integer t(0); return t; } /** * @brief Get method for length of each component element. * NOTE assumes all components are the same size. * * @return length of the component element */ usint GetLength() const { if (m_vectors.size() == 0) return 0; return m_vectors[0].GetValues().GetLength(); } /** * @brief Get interpolated value of elements at all tower index i. * Note this operation is computationally intense. * @return interpolated value at index i. */ Integer &at(usint i); const Integer &at(usint i) const; /** * @brief Get interpolated value of element at index i. * Note this operation is computationally intense. * @return interpolated value at index i. */ Integer &operator[](usint i); const Integer &operator[](usint i) const; /** * @brief Get method of individual tower of elements. * Note this behavior is different than poly * @param i index of tower to be returned. * @returns a reference to the returned tower */ const PolyType &GetElementAtIndex(usint i) const; /** * @brief Get method of the number of component elements, also known as the * number of towers. * * @return the number of component elements. */ usint GetNumOfElements() const; /** * @brief Get method that returns a vector of all component elements. * * @returns a vector of the component elements. */ const std::vector<PolyType> &GetAllElements() const; /** * @brief Get method of the format. * * @return the format, either COEFFICIENT or EVALUATION */ Format GetFormat() const; /** * @brief Write the element as \f$ \sum\limits{i=0}^{\lfloor {\log q/base} * \rfloor} {(base^i u_i)} \f$ and return the vector of \f$ \left\{u_0, * u_1,...,u_{\lfloor {\log q/base} \rfloor} \right\} \in R_{{base}^{\lceil * {\log q/base} \rceil}} \f$; This is used as a subroutine in the * relinearization procedure. * * @param baseBits is the number of bits in the base, i.e., \f$ base = * 2^{baseBits} \f$. * @return is the pointer where the base decomposition vector is stored */ std::vector<DCRTPolyType> BaseDecompose(usint baseBits, bool evalModeAnswer = true) const; /** * @brief Generate a vector of PolyImpl's as \f$ \left\{x, {base}*x, * {base}^2*x, ..., {base}^{\lfloor {\log q/{base}} \rfloor} \right\}*x \f$, * where \f$ x \f$ is the current PolyImpl object; * used as a subroutine in the relinearization procedure to get powers of a * certain "base" for the secret key element. * * @param baseBits is the number of bits in the base, i.e., \f$ base = * 2^{baseBits} \f$. * @return is the pointer where the base decomposition vector is stored */ std::vector<DCRTPolyType> PowersOfBase(usint baseBits) const; /** * CRT basis decomposition of c as [c qi/q]_qi * * @param &baseBits bits in the base for additional digit decomposition if * base > 0 * @return is the pointer where the resulting vector is stored */ std::vector<DCRTPolyType> CRTDecompose(uint32_t baseBits = 0) const; // VECTOR OPERATIONS /** * @brief Assignment Operator. * * @param &rhs the copied element. * @return the resulting element. */ const DCRTPolyType &operator=(const DCRTPolyType &rhs); /** * @brief Move Assignment Operator. * * @param &rhs the copied element. * @return the resulting element. */ const DCRTPolyType &operator=(DCRTPolyType &&rhs); /** * @brief Initalizer list * * @param &rhs the list to initalized the element. * @return the resulting element. */ DCRTPolyType &operator=(std::initializer_list<uint64_t> rhs); /** * @brief Assignment Operator. The usint val will be set at index zero and all * other indices will be set to zero. * * @param val is the usint to assign to index zero. * @return the resulting vector. */ DCRTPolyType &operator=(uint64_t val); /** * @brief Creates a Poly from a vector of signed integers (used for trapdoor * sampling) * * @param &rhs the vector to set the PolyImpl to. * @return the resulting PolyImpl. */ DCRTPolyType &operator=(std::vector<int64_t> rhs); /** * @brief Creates a Poly from a vector of signed integers (used for trapdoor * sampling) * * @param &rhs the vector to set the PolyImpl to. * @return the resulting PolyImpl. */ DCRTPolyType &operator=(std::vector<int32_t> rhs); /** * @brief Initalizer list * * @param &rhs the list to set the PolyImpl to. * @return the resulting PolyImpl. */ DCRTPolyType &operator=(std::initializer_list<std::string> rhs); /** * @brief Unary minus on a element. * @return additive inverse of the an element. */ DCRTPolyType operator-() const { DCRTPolyType all0(this->GetParams(), this->GetFormat(), true); return all0 - *this; } /** * @brief Equality operator. * * @param &rhs is the specified element to be compared with this element. * @return true if this element represents the same values as the specified * element, false otherwise */ bool operator==(const DCRTPolyType &rhs) const; /** * @brief Performs an entry-wise addition over all elements of each tower with * the towers of the element on the right hand side. * * @param &rhs is the element to add with. * @return is the result of the addition. */ const DCRTPolyType &operator+=(const DCRTPolyType &rhs); /** * @brief Performs an entry-wise subtraction over all elements of each tower * with the towers of the element on the right hand side. * * @param &rhs is the element to subtract from. * @return is the result of the addition. */ const DCRTPolyType &operator-=(const DCRTPolyType &rhs); /** * @brief Permutes coefficients in a polynomial. Moves the ith index to the * first one, it only supports odd indices. * * @param &i is the element to perform the automorphism transform with. * @return is the result of the automorphism transform. */ #if 1 DCRTPolyType AutomorphismTransform(const usint &i) const { DCRTPolyType result(*this); for (usint k = 0; k < m_vectors.size(); k++) { result.m_vectors[k] = m_vectors[k].AutomorphismTransform(i); } return result; } void GenAutormophTable(const usint &k, std::vector<usint> &perm) const { usint n = GetRingDimension(); usint m = n << 1; usint logn = log2(n); usint logm = logn + 1; perm.resize(n); for (usint j = 1; j < m; j += 2) { usint idx = (j * k) - (((j * k) >> logm) << logm); usint jrev = ReverseBits(j >> 1, logn); usint idxrev = ReverseBits(idx >> 1, logn); // result.m_values->operator[](jrev) = GetValues().operator[](idxrev); perm[idxrev] = jrev; } } DCRTPolyType Permute(const std::vector<usint> &perm) const { DCRTPolyType result(*this); #pragma omp parallel for for (usint k = 0; k < m_vectors.size(); k++) { result.m_vectors[k] = m_vectors[k].Permute(perm); } return result; } #else DCRTPolyType AutomorphismTransform(const usint &i) const { DCRTPolyType result(*this); // TODO add table usint m = this->m_params->GetCyclotomicOrder(); usint n = this->m_params->GetRingDimension(); usint logm = log2(m); usint logn = log2(n); for (usint j = 1; j < m; j += 2) { usint idx = (j * k) - (((j * k) >> logm) << logm); usint jrev = ReverseBits(j >> 1, logn); usint idxrev = ReverseBits(idx >> 1, logn); result.m_values->operator[](jrev) = GetValues().operator[](idxrev); } // Simple permutation for (usint k = 0; k < m_vectors.size(); k++) { result.m_vectors[k] = m_vectors[k].AutomorphismTransform(i); } return result; } #endif /** * @brief Transpose the ring element using the automorphism operation * * @return is the result of the transposition. */ DCRTPolyType Transpose() const { if (m_format == COEFFICIENT) { PALISADE_THROW(not_implemented_error, "DCRTPolyImpl element transposition is currently " "implemented only in the Evaluation representation."); } else { usint m = m_params->GetCyclotomicOrder(); return AutomorphismTransform(m - 1); } } /** * @brief Performs an addition operation and returns the result. * * @param &element is the element to add with. * @return is the result of the addition. */ DCRTPolyType Plus(const DCRTPolyType &element) const; /** * @brief Performs a multiplication operation and returns the result. * * @param &element is the element to multiply with. * @return is the result of the multiplication. */ DCRTPolyType Times(const DCRTPolyType &element) const; /** * @brief Performs a subtraction operation and returns the result. * * @param &element is the element to subtract from. * @return is the result of the subtraction. */ DCRTPolyType Minus(const DCRTPolyType &element) const; // SCALAR OPERATIONS /** * @brief Scalar addition - add an element to the first index of each tower. * * @param &element is the element to add entry-wise. * @return is the result of the addition operation. */ DCRTPolyType Plus(const Integer &element) const; /** * @brief Scalar addition for elements in CRT format. * CRT elements are represented as vector of integer elements which * correspond to the represented number modulo the primes in the * tower chain (in same order). * * @param &element is the element to add entry-wise. * @return is the result of the addition operation. */ DCRTPolyType Plus(const vector<Integer> &element) const; /** * @brief Scalar subtraction - subtract an element to all entries. * * @param &element is the element to subtract entry-wise. * @return is the return value of the minus operation. */ DCRTPolyType Minus(const Integer &element) const; /** * @brief Scalar subtraction for elements in CRT format. * CRT elements are represented as vector of integer elements which * correspond to the represented number modulo the primes in the * tower chain (in same order). * * @param &element is the element to subtract entry-wise. * @return is the result of the subtraction operation. */ DCRTPolyType Minus(const vector<Integer> &element) const; /** * @brief Scalar multiplication - multiply all entries. * * @param &element is the element to multiply entry-wise. * @return is the return value of the times operation. */ DCRTPolyType Times(const Integer &element) const; /** * @brief Scalar multiplication - mulltiply by a signed integer * * @param &element is the element to multiply entry-wise. * @return is the return value of the times operation. */ DCRTPolyType Times(int64_t element) const; /** * @brief Scalar multiplication by an integer represented in CRT Basis. * * @param &element is the element to multiply entry-wise. * @return is the return value of the times operation. */ DCRTPolyType Times(const std::vector<NativeInteger> &element) const; /** * @brief Scalar modular multiplication by an integer represented in CRT * Basis. * * @param &element is the element to multiply entry-wise. * @return is the return value of the times operation. */ DCRTPolyType Times(const std::vector<Integer> &element) const; /** * @brief Scalar multiplication followed by division and rounding operation - * operation on all entries. * * @param &p is the element to multiply entry-wise. * @param &q is the element to divide entry-wise. * @return is the return value of the multiply, divide and followed by * rounding operation. */ DCRTPolyType MultiplyAndRound(const Integer &p, const Integer &q) const; /** * @brief Scalar division followed by rounding operation - operation on all * entries. * * @param &q is the element to divide entry-wise. * @return is the return value of the divide, followed by rounding operation. */ DCRTPolyType DivideAndRound(const Integer &q) const; /** * @brief Performs a negation operation and returns the result. * * @return is the result of the negation. */ DCRTPolyType Negate() const; const DCRTPolyType &operator+=(const Integer &element) { for (usint i = 0; i < this->GetNumOfElements(); i++) { this->m_vectors[i] += (element.Mod(this->m_vectors[i].GetModulus())).ConvertToInt(); } return *this; } /** * @brief Performs a subtraction operation and returns the result. * * @param &element is the element to subtract from. * @return is the result of the subtraction. */ const DCRTPolyType &operator-=(const Integer &element) { for (usint i = 0; i < this->GetNumOfElements(); i++) { this->m_vectors[i] -= (element.Mod(this->m_vectors[i].GetModulus())).ConvertToInt(); } return *this; } /** * @brief Performs a multiplication operation and returns the result. * * @param &element is the element to multiply by. * @return is the result of the subtraction. */ const DCRTPolyType &operator*=(const Integer &element); /** * @brief Performs an multiplication operation and returns the result. * * @param &element is the element to multiply with. * @return is the result of the multiplication. */ const DCRTPolyType &operator*=(const DCRTPolyType &element); /** * @brief Get value of element at index i. * * @return value at index i. */ PolyType &ElementAtIndex(usint i); // multiplicative inverse operation /** * @brief Performs a multiplicative inverse operation and returns the result. * * @return is the result of the multiplicative inverse. */ DCRTPolyType MultiplicativeInverse() const; /** * @brief Perform a modulus by 2 operation. Returns the least significant * bit. * * @return is the resulting value. */ DCRTPolyType ModByTwo() const; /** * @brief Modulus - perform a modulus operation. Does proper mapping of * [-modulus/2, modulus/2) to [0, modulus) * * @param modulus is the modulus to use. * @return is the return value of the modulus. */ DCRTPolyType Mod(const Integer &modulus) const { PALISADE_THROW(not_implemented_error, "Mod of an Integer not implemented on DCRTPoly"); } // OTHER FUNCTIONS AND UTILITIES /** * @brief Get method that should not be used * * @return will throw an error. */ const VecType &GetValues() const { PALISADE_THROW(not_implemented_error, "GetValues not implemented on DCRTPoly"); } /** * @brief Set method that should not be used, will throw an error. * * @param &values * @param format */ void SetValues(const VecType &values, Format format) { PALISADE_THROW(not_implemented_error, "SetValues not implemented on DCRTPoly"); } /** * @brief Sets element at index * * @param index where the element should be set */ void SetElementAtIndex(usint index, const PolyType &element) { m_vectors[index] = element; } /** * @brief Sets all values of element to zero. */ void SetValuesToZero(); /** * @brief Adds "1" to every entry in every tower. */ void AddILElementOne(); /** * @brief Add uniformly random values to all components except for the first * one */ DCRTPolyType AddRandomNoise(const Integer &modulus) const { PALISADE_THROW(not_implemented_error, "AddRandomNoise is not currently implemented for DCRTPoly"); } /** * @brief Make DCRTPoly Sparse. Sets every index of each tower not equal to * zero mod the wFactor to zero. * * @param &wFactor ratio between the sparse and none-sparse values. */ void MakeSparse(const uint32_t &wFactor); /** * @brief Returns true if ALL the tower(s) are empty. * @return true if all towers are empty */ bool IsEmpty() const; /** * @brief Drops the last element in the double-CRT representation. The * resulting DCRTPoly element will have one less tower. */ void DropLastElement(); /** * @brief Drops the last i elements in the double-CRT representation. */ void DropLastElements(size_t i); /** * @brief Drops the last element in the double-CRT representation and scales * down by the last CRT modulus. The resulting DCRTPoly element will have one * less tower. */ void DropLastElementAndScale( const std::vector<typename PolyType::Integer> &omega); /** * @brief ModReduces reduces the DCRTPoly element's composite modulus by * dropping the last modulus from the chain of moduli as well as dropping the * last tower. * * @param plaintextModulus is the plaintextModulus used for the DCRTPoly */ void ModReduce(const Integer &plaintextModulus); /** * @brief Interpolates the DCRTPoly to an Poly based on the Chinese Remainder * Transform Interpolation. and then returns a Poly with that single element * * @return the interpolated ring element as a Poly object. */ PolyLargeType CRTInterpolate() const; PolyType DecryptionCRTInterpolate(PlaintextModulus ptm) const; NativePoly ToNativePoly() const; /** * @brief Interpolates the DCRTPoly to an Poly based on the Chinese Remainder * Transform Interpolation, only at element index i, all other elements are * zero. and then returns a Poly with that single element * * @return the interpolated ring element as a Poly object. */ PolyLargeType CRTInterpolateIndex(usint i) const; /** * @brief Computes Round(p/q*x) mod p as [\sum_i x_i*alpha_i + Round(\sum_i * x_i*beta_i)] mod p for fast rounding in RNS; used in the decryption of * BFVrns * * @param &p 64-bit integer (often corresponds to the plaintext modulus) * @param &alpha a vector of precomputed integer factors mod p - for each q_i * @param &beta a vector of precomputed floating-point factors between 0 and 1 * - for each q_i - used when CRT moduli are <= 44 bits * @param &alphaPrecon an NTL-specific vector of precomputed integer factors * mod p - for each q_i * @param &quadBeta a vector of precomputed quad-precision floating-point * factors between 0 and 1 - for each q_i - used when CRT moduli are 58..60 * bits long * @param &extBeta a vector of precomputed extended-double-precision * floating-point factors between 0 and 1 - for each q_i - used when CRT * moduli are 45..57 bits long * @return the result of computation as a polynomial with native 64-bit * coefficients */ PolyType ScaleAndRound(const NativeInteger &p, const std::vector<NativeInteger> &alpha, const std::vector<double> &beta, const std::vector<NativeInteger> &alphaPrecon, #ifndef NO_QUADMATH const std::vector<QuadFloat> &quadBeta, #endif const std::vector<long double> &extBeta) const; /** * @brief Computes and returns the product of primes in the current moduli * chain. Compared to GetModulus, which always returns the product of all * primes in the crypto parameters, this method will return a different * modulus, based on the towers/moduli that are currently in the chain (some * towers are dropped along the way). * * @return the product of moduli in the current towers. */ BigInteger GetWorkingModulus() const; /** * @brief Returns the element parameters for DCRTPoly elements in an extended * CRT basis, which is the concatenation of the towers currently in "this" * DCRTPoly, and the moduli in ParamsP. * * @return element parameters of the extended basis. */ shared_ptr<Params> GetExtendedCRTBasis(shared_ptr<Params> paramsP) const; /** * @brief Performs approximate CRT basis switching. Based on the Fast Basis * Conversion algorithm presented in Section 2.3 of "A full RNS variant of * approximate homomorphic encryption" by Cheon, et. al. * * Suppose we have two CRT bases: C={q_0, ..., q_{L-1}} with Q=q_0*...*q_{L-1} * and B={p_0, ..., p_{K-1}} with P=p_0*...*p_{K-1}. Also, suppose that the * input of the algorithm (the DCRTPoly in "this" in our case), is in basis C. * * The conversion algorithm Conv_{C->B}(this) does not return the * representation of this in basis B, but instead, it returns the * representation of (this + Q*t) in basis B, for some small t (hence we call * it *approximate* CRT basis switch). * * The method computes the conversion as follows: * * Conv_{C->B}(this in C basis) = * Sum_{j=0}^{L-1}(this_j * invhatq_j * hatq_j) mod p_i * * Where: * this_j = this mod q_j * invhatq_j = \hat{q_j} = Q / q_j * hatq_j = \hat{q_j}^{-1} = \hat{q_j}^{-1} mod q_j * * Values for (invhatq_j mod q_j) and (hatq_j mod p_i) must be pre-computed * and supplied as arguments, to ensure the entirety of the conversion happens * in RNS. * * @param &paramsFrom parameters for the CRT basis C * @param &paramsTo parameters for the CRT basis B * @param &hatInvModFrom precomputed values for (invhatq_j mod q_j) * @param &hatInvModFromPrecon ModMul precomputed values for hatInvModFrom * @param &hatModTo precomputed values for (hatq_j mod p_i) * @param &modBarretPrecon 128-bit Barrett reduction precomputed values * @return the representation of (this + Q*t) in basis B. */ DCRTPolyType ApproxSwitchCRTBasis( const shared_ptr<Params> paramsFrom, const shared_ptr<Params> paramsTo, const vector<NativeInteger> &hatInvModFrom, const vector<NativeInteger> &hatInvModFromPrecon, const vector<vector<NativeInteger>> &hatModTo, const vector<DoubleNativeInt> &modBarretPrecon) const; /** * @brief Performs approximate modulus raising in RNS. Based on the algorithm * presented in Section 3.2 of "A full RNS variant of approximate homomorphic * encryption" by Cheon, et. al. Given a DCRTPoly "this" in basis C={q_0, ..., * q_{L-1}} with Q=q_0*...*q_{L-1}, it uses ApproxSwitchCRTBasis internally, * and computes the representation of (this + Q*t) in basis D={q_0, ..., * q_{L-1}, p_L, ..., p_{L+K-1}}, where B={p_0, ..., p_{K-1}} with * P=p_0*...*p_{K-1} is the basis we supply as argument in ParamsP. * * Values for (invhatq_j mod q_j) and (hatq_j mod p_i) must be supplied as * arguments here too, because ApproxSwitchCRTBasis is used internally. * * @param &paramsQ parameters for the CRT basis C * @param &paramsP parameters for the CRT basis B * @param &qHatInvModQj precomputed values for (invhatq_j mod q_j) * @param &qHatInvModQjPrecon ModMul precomputed values for qHatInvModQj * @param &qHatModPi precomputed values for (hatq_j mod p_i) * @param &modBarretPreconP 128-bit Barrett reduction precomputed values for * p_i * @return the representation of (this + Q*t) in the extended basis. */ DCRTPolyType ApproxModUp( const shared_ptr<Params> paramsQ, const shared_ptr<Params> paramsP, const vector<vector<NativeInteger>> &qHatInvModQj, const vector<vector<NativeInteger>> &qHatInvModQjPrecon, const vector<vector<vector<NativeInteger>>> &qHatModPi, const vector<DoubleNativeInt> &modBarretPreconP) const; /** * @brief Performs approximate modulus reduction in RNS. Based on the * algorithm presented in Section 3.2 of "A full RNS variant of approximate * homomorphic encryption" by Cheon, et. al. Given a DCRTPoly "this" in basis * D={q_0, ..., q_{L-1}, p_L, ..., p_{L+K-1}}, it computes the representation * of (P^-1 * this) is basis C={q_0, ..., q_{L-1}}. The reduction is * approximate, so the result is not exactly (P^-1 * this), but a reasonable * approximation to it. * * Values for (invhatq_j mod q_j) and (hatq_j mod p_i) must be supplied as * arguments here too, because ApproxSwitchCRTBasis is used internally. * Moreover, precomputed values for (P^{-1} mod q_j) must also be supplied. * * @param &paramsQ parameters for the CRT basis C. * @param &paramsP parameters for the CRT basis B. * @param &pInvModQj precomputed values for (P^{-1} mod q_j). * @param &pInvModQjPrecon ModMul precomputed values for pInvModQj * @param &pHatInvModPi precomputed values for (invhatq_j mod q_j). * @param &pHatInvModPiPrecon ModMul precomputed values for pHatInvModPi * @param &pHatModQj precomputed values for (hatq_j mod p_i). * @param &modBarretPreconQ 128-bit Barrett reduction precomputed values for * q_j * @return the representation of (P^-1 * this) in basis C. */ DCRTPolyType ApproxModDown( const shared_ptr<Params> paramsQ, const shared_ptr<Params> paramsP, const vector<NativeInteger> &pInvModQj, const vector<NativeInteger> &pInvModQjPrecon, const vector<NativeInteger> &pHatInvModPi, const vector<NativeInteger> &pHatInvModPiPrecon, const vector<vector<NativeInteger>> &pHatModQj, const vector<DoubleNativeInt> &modBarretPreconQ) const; /** * @brief Switches polynomial from one CRT basis Q = q1*q2*...*qn to another * CRT basis S = s1*s2*...*sn * * @param &params parameters for the CRT basis S * @param &qInvModqi a vector of precomputed integer factors (q/qi)^{-1} mod * qi for all qi * @param &qDivqiModsi a matrix of precomputed integer factors (q/qi)^{-1} mod * si for all si, qi combinations * @param &qModsi a vector of precomputed integer factors q mod si for all si * @param &siModulimu Barrett modulo reduction precomputations for si's * @param &qInvModqiPrecon NTL precomputations for (q/qi)^{-1} mod q * @return the polynomial in the CRT basis S */ DCRTPolyType SwitchCRTBasis( const shared_ptr<Params> params, const std::vector<NativeInteger> &qInvModqi, const std::vector<std::vector<NativeInteger>> &qDivqiModsi, const std::vector<NativeInteger> &qModsi, const std::vector<DoubleNativeInt> &siModulimu, const std::vector<NativeInteger> &qInvModqiPrecon) const; /** * @brief Expands polynomial in CRT basis Q = q1*q2*...*qn to a larger CRT * basis Q*S, where S = s1*s2*...*sn; uses SwtichCRTBasis as a subroutine; the * result is in evaluation representation * * @param &paramsQS parameters for the expanded CRT basis Q*S * @param &params parameters for the CRT basis S * @param &qInvModqi a vector of precomputed integer factors (q/qi)^{-1} mod * qi for all qi * @param &qDivqiModsi a matrix of precomputed integer factors (q/qi)^{-1} mod * si for all si, qi combinations * @param &qModsi a vector of precomputed integer factors q mod si for all si * @param &siModulimu Barrett modulo reduction precomputations for si's * @param &qInvModqiPrecon NTL precomputations for (q/qi)^{-1} mod q */ void ExpandCRTBasis( const shared_ptr<Params> paramsQS, const shared_ptr<Params> params, const std::vector<NativeInteger> &qInvModqi, const std::vector<std::vector<NativeInteger>> &qDivqiModsi, const std::vector<NativeInteger> &qModsi, const std::vector<DoubleNativeInt> &siModulimu, const std::vector<NativeInteger> &qInvModqiPrecon); /** * @brief Computes Round(t/q*x) mod t for fast rounding in RNS * @param qModuliTable: basis q = q1 * q2 * ... * @param gamma: redundant modulus * @param t: plaintext modulus * @param gammaInvModt * @param gammaInvModtPrecon - table for gammaInvModt used in preconditioned * modular reduction * @param negqInvModtgammaTable: -1/q mod {t U gamma} * @param negqInvModtgammaPreconTable - used in preconditioned modular * reduction * @param tgammaqDivqiModqiTable * @param tgammaqDivqiModqiPreconTable * @param qDivqiModtgammaTable * @param qDivqiModtgammaPreconTable * @return */ PolyType ScaleAndRound( const std::vector<NativeInteger> &qModuliTable, const NativeInteger &gamma, const NativeInteger &t, const NativeInteger &gammaInvModt, const NativeInteger &gammaInvModtPrecon, const std::vector<NativeInteger> &negqInvModtgammaTable, const std::vector<NativeInteger> &negqInvModtgammaPreconTable, const std::vector<NativeInteger> &tgammaqDivqiModqiTable, const std::vector<NativeInteger> &tgammaqDivqiModqiPreconTable, const std::vector<std::vector<NativeInteger>> &qDivqiModtgammaTable, const std::vector<std::vector<NativeInteger>> &qDivqiModtgammaPreconTable) const; /** *@ brief Expands polynomial in CRT basis q to a larger CRT basis {Bsk U *mtilde}, mtilde is a redundant modulus used to remove q overflows generated *from fast conversion. * @param paramsBsk: container of Bsk moduli and roots on unity * @param qModuli: basis q = q1 * q2 * ... * @param BskmtildeModuli: basis {Bsk U mtilde} ... * @param mtildeqDivqiModqi: mtilde*(q/qi)^-1 (mod qi) * @param mtildeqDivqiModqiPrecon * @param qDivqiModBj: q/qi mod {Bsk U mtilde} * @param qModBski: q mod {Bsk} * @param qModBskiPrecon * @param negqInvModmtilde: -1/q mod mtilde * @param negqInvModmtildePrecon * @param mtildeInvModBskiTable: mtilde^-1 mod {Bsk} * @param mtildeInvModBskiPreconTable */ void FastBaseConvqToBskMontgomery( const shared_ptr<Params> paramsBsk, const std::vector<NativeInteger> &qModuli, const std::vector<NativeInteger> &BskmtildeModuli, const std::vector<DoubleNativeInt> &BskmtildeModulimu, const std::vector<NativeInteger> &mtildeqDivqiModqi, const std::vector<NativeInteger> &mtildeqDivqiModqiPrecon, const std::vector<std::vector<NativeInteger>> &qDivqiModBj, const std::vector<NativeInteger> &qModBski, const std::vector<NativeInteger> &qModBskiPrecon, const NativeInteger &negqInvModmtilde, const NativeInteger &negqInvModmtildePrecon, const std::vector<NativeInteger> &mtildeInvModBskiTable, const std::vector<NativeInteger> &mtildeInvModBskiPreconTable); /** * @brief Scales polynomial in CRT basis {q U Bsk} by scalar t/q. * @param t: plaintext modulus * @param qModuli: basis q = q1 * q2 * ... * @param BskModuli: Bsk basis * @param qDivqiModqi: (q/qi)^-1 mod qi * @param tqDivqiModqiPrecon * @param qDivqiModBj: (q/qi) mod {Bsk} * @param qInvModBi: q^-1 mod {Bsk} * @param qInvModBiPrecon */ void FastRNSFloorq(const NativeInteger &t, const std::vector<NativeInteger> &qModuli, const std::vector<NativeInteger> &BskModuli, const std::vector<DoubleNativeInt> &BskModulimu, const std::vector<NativeInteger> &tqDivqiModqi, const std::vector<NativeInteger> &tqDivqiModqiPrecon, const std::vector<std::vector<NativeInteger>> &qDivqiModBj, const std::vector<NativeInteger> &qInvModBi, const std::vector<NativeInteger> &qInvModBiPrecon); /** * @brief Converts fast polynomial in CRT basis {q U Bsk} to basis {q} using * Shenoy Kumaresan method. * @param qModuli: basis q = q1 * q2 * ... * @param BskModuli: Bsk basis * @param BDivBiModBi: (B/Bi)^-1 mod Bi, where B = m1 * m2 * ... (without * msk). Note in the source paper, B is referred to by M. * @param BDivBiModBiPrecon * @param BDivBiModmsk: B/Bi mod msk * @param BInvModmsk: B^-1 mod msk * @param BInvModmskPrecon * @param BDivBiModqj: B/Bi mod {q} * @param BModqi: B mod {q} * @param BModqiPrecon */ void FastBaseConvSK( const std::vector<NativeInteger> &qModuli, const std::vector<DoubleNativeInt> &qModulimu, const std::vector<NativeInteger> &BskModuli, const std::vector<DoubleNativeInt> &BskModulimu, const std::vector<NativeInteger> &BDivBiModBi, const std::vector<NativeInteger> &BDivBiModBiPrecon, const std::vector<NativeInteger> &BDivBiModmsk, const NativeInteger &BInvModmsk, const NativeInteger &BInvModmskPrecon, const std::vector<std::vector<NativeInteger>> &BDivBiModqj, const std::vector<NativeInteger> &BModqi, const std::vector<NativeInteger> &BModqiPrecon); /** * @brief Computes Round(p/Q*x), where x is in the CRT basis Q*S, * as [\sum_{i=1}^n alpha_i*x_i + Round(\sum_{i=1}^n beta_i*x_i)]_si, * with the result in the Q CRT basis; used in homomorphic multiplication of * BFVrns * * @param &params parameters for the CRT basis Q * @param &alpha a matrix of precomputed integer factors = * {Floor[p*S*[(Q*S/vi)^{-1}]_{vi}/vi]}_si; for all combinations of vi, si; * where vi is a prime modulus in Q*S * @param &beta a vector of precomputed floating-point factors between 0 and 1 * = [p*S*(Q*S/vi)^{-1}]_{vi}/vi; - for each vi * @param &siModulimu Barrett modulo reduction precomputations for si's * @return the result of computation as a polynomial in the CRT basis Q */ DCRTPolyType ScaleAndRound( const shared_ptr<Params> params, const std::vector<std::vector<NativeInteger>> &alpha, const std::vector<long double> &beta, const std::vector<DoubleNativeInt> &siModulimu) const; /** * @brief Convert from Coefficient to CRT or vice versa; calls FFT and inverse * FFT. */ void SwitchFormat(); /** * @brief Switch modulus and adjust the values * * @param &modulus is the modulus to be set * @param &rootOfUnity is the corresponding root of unity for the modulus * @param &modulusArb is the modulus used for arbitrary cyclotomics CRT * @param &rootOfUnityArb is the corresponding root of unity for the modulus * ASSUMPTION: This method assumes that the caller provides the correct * rootOfUnity for the modulus */ void SwitchModulus(const Integer &modulus, const Integer &rootOfUnity, const Integer &modulusArb = Integer(0), const Integer &rootOfUnityArb = Integer(0)) { PALISADE_THROW(not_implemented_error, "SwitchModulus not implemented on DCRTPoly"); } /** * @brief Switch modulus at tower i and adjust the values * * @param index is the index for the tower * @param &modulus is the modulus to be set * @param &rootOfUnity is the corresponding root of unity for the modulus * ASSUMPTION: This method assumes that the caller provides the correct * rootOfUnity for the modulus */ void SwitchModulusAtIndex(usint index, const Integer &modulus, const Integer &rootOfUnity); /** * @brief Determines if inverse exists * * @return is the Boolean representation of the existence of multiplicative * inverse. */ bool InverseExists() const; /** * @brief Returns the infinity norm, basically the largest value in the ring * element. * * @return is the largest value in the ring element. */ double Norm() const; /** * @brief ostream operator * @param os the input preceding output stream * @param vec the element to add to the output stream. * @return a resulting concatenated output stream */ friend inline std::ostream &operator<<(std::ostream &os, const DCRTPolyType &vec) { // os << (vec.m_format == EVALUATION ? "EVAL: " : "COEF: "); for (usint i = 0; i < vec.GetAllElements().size(); i++) { if (i != 0) os << std::endl; os << i << ": "; os << vec.GetAllElements()[i]; } return os; } /** * @brief Element-element addition operator. * @param a first element to add. * @param b second element to add. * @return the result of the addition operation. */ friend inline DCRTPolyType operator+(const DCRTPolyType &a, const DCRTPolyType &b) { return a.Plus(b); } /** * @brief Element-integer addition operator. * @param a first element to add. * @param b integer to add. * @return the result of the addition operation. */ friend inline DCRTPolyType operator+(const DCRTPolyType &a, const Integer &b) { return a.Plus(b); } /** * @brief Integer-element addition operator. * @param a integer to add. * @param b element to add. * @return the result of the addition operation. */ friend inline DCRTPolyType operator+(const Integer &a, const DCRTPolyType &b) { return b.Plus(a); } /** * @brief Element-integer addition operator with CRT integer. * @param a first element to add. * @param b integer to add. * @return the result of the addition operation. */ friend inline DCRTPolyType operator+(const DCRTPolyType &a, const vector<Integer> &b) { return a.Plus(b); } /** * @brief Integer-element addition operator with CRT integer. * @param a integer to add. * @param b element to add. * @return the result of the addition operation. */ friend inline DCRTPolyType operator+(const vector<Integer> &a, const DCRTPolyType &b) { return b.Plus(a); } /** * @brief Element-element subtraction operator. * @param a element to subtract from. * @param b element to subtract. * @return the result of the subtraction operation. */ friend inline DCRTPolyType operator-(const DCRTPolyType &a, const DCRTPolyType &b) { return a.Minus(b); } /** * @brief Element-integer subtraction operator with CRT integer. * @param a first element to subtract. * @param b integer to subtract. * @return the result of the subtraction operation. */ friend inline DCRTPolyType operator-(const DCRTPolyType &a, const vector<Integer> &b) { return a.Minus(b); } /** * @brief Integer-element subtraction operator with CRT integer. * @param a integer to subtract. * @param b element to subtract. * @return the result of the subtraction operation. */ friend inline DCRTPolyType operator-(const vector<Integer> &a, const DCRTPolyType &b) { return b.Minus(a); } /** * @brief Element-integer subtraction operator. * @param a element to subtract from. * @param b integer to subtract. * @return the result of the subtraction operation. */ friend inline DCRTPolyType operator-(const DCRTPolyType &a, const Integer &b) { return a.Minus(b); } /** * @brief Element-element multiplication operator. * @param a element to multiply. * @param b element to multiply. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(const DCRTPolyType &a, const DCRTPolyType &b) { return a.Times(b); } /** * @brief Element-integer multiplication operator. * @param a element to multiply. * @param b integer to multiply. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(const DCRTPolyType &a, const Integer &b) { return a.Times(b); } /** * @brief Element-CRT number multiplication operator. * @param a element to multiply. * @param b integer to multiply, in CRT format. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(const DCRTPolyType &a, const vector<Integer> &b) { return a.Times(b); } /** * @brief Integer-element multiplication operator. * @param a integer to multiply. * @param b element to multiply. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(const Integer &a, const DCRTPolyType &b) { return b.Times(a); } /** * @brief Element-signed-integer multiplication operator. * @param a element to multiply. * @param b integer to multiply. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(const DCRTPolyType &a, int64_t b) { return a.Times(b); } /** * @brief signed-Integer-element multiplication operator. * @param a integer to multiply. * @param b element to multiply. * @return the result of the multiplication operation. */ friend inline DCRTPolyType operator*(int64_t a, const DCRTPolyType &b) { return b.Times(a); } template <class Archive> void save(Archive &ar, std::uint32_t const version) const { ar(::cereal::make_nvp("v", m_vectors)); ar(::cereal::make_nvp("f", m_format)); ar(::cereal::make_nvp("p", m_params)); } template <class Archive> void load(Archive &ar, std::uint32_t const version) { if (version > SerializedVersion()) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar(::cereal::make_nvp("v", m_vectors)); ar(::cereal::make_nvp("f", m_format)); ar(::cereal::make_nvp("p", m_params)); } std::string SerializedObjectName() const { return "DCRTPoly"; } static uint32_t SerializedVersion() { return 1; } private: shared_ptr<Params> m_params; // array of vectors used for double-CRT presentation std::vector<PolyType> m_vectors; // Either Format::EVALUATION (0) or Format::COEFFICIENT (1) Format m_format; }; } // namespace lbcrypto namespace lbcrypto { typedef DCRTPolyImpl<BigVector> DCRTPoly; } #endif
ProcessHelpers.h
// // Cubism3D // Copyright (c) 2018 CSE-Lab, ETH Zurich, Switzerland. // Distributed under the terms of the MIT license. // // Created by Guido Novati (novatig@ethz.ch) and Christian Conti. // #ifndef CubismUP_3D_ProcessOperators_h #define CubismUP_3D_ProcessOperators_h #include "../SimulationData.h" #include "../ObstacleBlock.h" #include "Operator.h" CubismUP_3D_NAMESPACE_BEGIN #ifndef CUP_SINGLE_PRECISION #define MPIREAL MPI_DOUBLE #else #define MPIREAL MPI_FLOAT #endif /* CUP_SINGLE_PRECISION */ inline Real findMaxUzeroMom(const SimulationData& sim) { const std::vector<cubism::BlockInfo>& myInfo = sim.vInfo(); const Real uinf[3] = {sim.uinf[0], sim.uinf[1], sim.uinf[2]}; Real mom[3] = {0, 0, 0}; #pragma omp parallel for schedule(static) reduction(+ : mom[:3]) for(size_t i=0; i<myInfo.size(); i++) { const cubism::BlockInfo& info = myInfo[i]; const FluidBlock& b = *(const FluidBlock *)info.ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; ++iz) for(int iy=0; iy<FluidBlock::sizeY; ++iy) for(int ix=0; ix<FluidBlock::sizeX; ++ix) { Real h[3]; info.spacing(h, ix, iy, iz); const Real vol = h[0] * h[1] * h[2]; mom[0] += vol * b(ix,iy,iz).u; mom[1] += vol * b(ix,iy,iz).v; mom[2] += vol * b(ix,iy,iz).w; } } MPI_Allreduce(MPI_IN_PLACE, mom, 3, MPIREAL, MPI_SUM, sim.app_comm); const Real corrX = mom[0] / (sim.extent[0] * sim.extent[1] * sim.extent[2]); const Real corrY = mom[1] / (sim.extent[0] * sim.extent[1] * sim.extent[2]); const Real corrZ = mom[2] / (sim.extent[0] * sim.extent[1] * sim.extent[2]); if(sim.verbose) printf("Correction in relative momenta:[%e %e %e]\n",corrX,corrY,corrZ); Real maxU = 0; #pragma omp parallel for schedule(static) reduction(max : maxU) for(size_t i=0; i<myInfo.size(); i++) { const cubism::BlockInfo& info = myInfo[i]; FluidBlock& b = *(FluidBlock *)info.ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; ++iz) for(int iy=0; iy<FluidBlock::sizeY; ++iy) for(int ix=0; ix<FluidBlock::sizeX; ++ix) { b(ix,iy,iz).u -= corrX; const Real u = std::fabs(b(ix,iy,iz).u +uinf[0]); b(ix,iy,iz).v -= corrY; const Real v = std::fabs(b(ix,iy,iz).v +uinf[1]); b(ix,iy,iz).w -= corrZ; const Real w = std::fabs(b(ix,iy,iz).w +uinf[2]); const Real maxUabsAdv = std::max({u, v, w}); maxU = std::max(maxU, maxUabsAdv); } } MPI_Allreduce(MPI_IN_PLACE, & maxU, 1, MPIREAL, MPI_MAX, sim.app_comm); assert(maxU >= 0); return maxU; } inline Real findMaxU(const SimulationData& sim) { const std::vector<cubism::BlockInfo>& myInfo = sim.vInfo(); const Real uinf[3] = {sim.uinf[0], sim.uinf[1], sim.uinf[2]}; Real maxU = 0; #pragma omp parallel for schedule(static) reduction(max : maxU) for(size_t i=0; i<myInfo.size(); i++) { const cubism::BlockInfo& info = myInfo[i]; const FluidBlock& b = *(const FluidBlock *)info.ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; ++iz) for(int iy=0; iy<FluidBlock::sizeY; ++iy) for(int ix=0; ix<FluidBlock::sizeX; ++ix) { const Real advu = std::fabs(b(ix,iy,iz).u + uinf[0]); const Real advv = std::fabs(b(ix,iy,iz).v + uinf[1]); const Real advw = std::fabs(b(ix,iy,iz).w + uinf[2]); const Real maxUl = std::max({advu, advv, advw}); maxU = std::max(maxU, maxUl); } } MPI_Allreduce(MPI_IN_PLACE, & maxU, 1, MPIREAL, MPI_MAX, sim.app_comm); assert(maxU >= 0); return maxU; } #undef MPIREAL using v_v_ob = std::vector<std::vector<ObstacleBlock*>*>; inline void putCHIonGrid( const std::vector<cubism::BlockInfo>& vInfo, const v_v_ob & vec_obstacleBlocks ) { #pragma omp parallel for schedule(dynamic,1) for(size_t i=0; i<vInfo.size(); i++) { FluidBlock& b = * (FluidBlock*) vInfo[i].ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; iz++) for(int iy=0; iy<FluidBlock::sizeY; iy++) for(int ix=0; ix<FluidBlock::sizeX; ix++) b(ix,iy,iz).chi = 0; for(size_t o=0; o<vec_obstacleBlocks.size(); o++) { const auto& pos = ( * vec_obstacleBlocks[o] )[vInfo[i].blockID]; if(pos == nullptr) continue; for(int iz=0; iz<FluidBlock::sizeZ; iz++) for(int iy=0; iy<FluidBlock::sizeY; iy++) for(int ix=0; ix<FluidBlock::sizeX; ix++) b(ix,iy,iz).chi = std::max(pos->chi[iz][iy][ix], b(ix,iy,iz).chi); } } } inline void putSDFonGrid( const std::vector<cubism::BlockInfo>& vInfo, const v_v_ob & vec_obstacleBlocks ) { #pragma omp parallel for schedule(dynamic,1) for(size_t i=0; i<vInfo.size(); i++) { FluidBlock& b = * (FluidBlock*) vInfo[i].ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; iz++) for(int iy=0; iy<FluidBlock::sizeY; iy++) for(int ix=0; ix<FluidBlock::sizeX; ix++) b(ix,iy,iz).p = -1; for(size_t o=0; o<vec_obstacleBlocks.size(); o++) { const auto& pos = ( * vec_obstacleBlocks[o] )[vInfo[i].blockID]; if(pos == nullptr) continue; for(int iz=0; iz<FluidBlock::sizeZ; iz++) for(int iy=0; iy<FluidBlock::sizeY; iy++) for(int ix=0; ix<FluidBlock::sizeX; ix++) b(ix,iy,iz).p = std::max(pos->sdf[iz][iy][ix], b(ix,iy,iz).p); } } } class KernelVorticity { public: KernelVorticity() = default; const std::array<int, 3> stencil_start = {-1,-1,-1}, stencil_end = {2, 2, 2}; const cubism::StencilInfo stencil{-1,-1,-1, 2,2,2, false, {FE_U,FE_V,FE_W}}; template <typename Lab, typename BlockType> void operator()(Lab & lab, const cubism::BlockInfo& info, BlockType& o) const { const Real inv2h = .5 / info.h_gridpoint; for (int iz=0; iz<FluidBlock::sizeZ; ++iz) for (int iy=0; iy<FluidBlock::sizeY; ++iy) for (int ix=0; ix<FluidBlock::sizeX; ++ix) { const FluidElement &LW=lab(ix-1,iy,iz), &LE=lab(ix+1,iy,iz); const FluidElement &LS=lab(ix,iy-1,iz), &LN=lab(ix,iy+1,iz); const FluidElement &LF=lab(ix,iy,iz-1), &LB=lab(ix,iy,iz+1); o(ix,iy,iz).tmpU = inv2h * ( (LN.w-LS.w) - (LB.v-LF.v) ); o(ix,iy,iz).tmpV = inv2h * ( (LB.u-LF.u) - (LE.w-LW.w) ); o(ix,iy,iz).tmpW = inv2h * ( (LE.v-LW.v) - (LN.u-LS.u) ); //o(ix,iy,iz).tmpU = __FD_2ND(iy, cy, phiS.w, phiC.w, phiN.w) // - __FD_2ND(iz, cz, phiF.v, phiC.v, phiB.v); //o(ix,iy,iz).tmpV = __FD_2ND(iz, cz, phiF.u, phiC.u, phiB.u) // - __FD_2ND(ix, cx, phiW.w, phiC.w, phiE.w); //o(ix,iy,iz).tmpW = __FD_2ND(ix, cx, phiW.v, phiC.v, phiE.v) // - __FD_2ND(iy, cy, phiS.u, phiC.u, phiN.u); } } }; class ComputeVorticity : public Operator { public: ComputeVorticity(SimulationData & s) : Operator(s) { } void operator()(const double dt) { sim.startProfiler("Vorticity Kernel"); if(sim.bUseStretchedGrid) { printf("TODO Compute Vorticity with stretched grids"); fflush(0); abort(); } else { const KernelVorticity K; compute<KernelVorticity>(K); } sim.stopProfiler(); check("Vorticity"); } std::string getName() { return "Vorticity"; } }; class KernelQcriterion { public: KernelQcriterion() = default; const std::array<int, 3> stencil_start = {-1,-1,-1}, stencil_end = {2, 2, 2}; const cubism::StencilInfo stencil{-1,-1,-1, 2,2,2, false, {FE_U,FE_V,FE_W}}; template <typename Lab, typename BlockType> void operator()(Lab & lab, const cubism::BlockInfo& info, BlockType& o) const { const Real inv2h = .5 / info.h_gridpoint; for (int iz=0; iz<FluidBlock::sizeZ; ++iz) for (int iy=0; iy<FluidBlock::sizeY; ++iy) for (int ix=0; ix<FluidBlock::sizeX; ++ix) { const FluidElement &LW=lab(ix-1,iy,iz), &LE=lab(ix+1,iy,iz); const FluidElement &LS=lab(ix,iy-1,iz), &LN=lab(ix,iy+1,iz); const FluidElement &LF=lab(ix,iy,iz-1), &LB=lab(ix,iy,iz+1); const Real WX = inv2h * ( (LN.w-LS.w) - (LB.v-LF.v) ); const Real WY = inv2h * ( (LB.u-LF.u) - (LE.w-LW.w) ); const Real WZ = inv2h * ( (LE.v-LW.v) - (LN.u-LS.u) ); const Real D11 = inv2h * (LE.u-LW.u); // shear stresses const Real D22 = inv2h * (LN.v-LS.v); // shear stresses const Real D33 = inv2h * (LB.w-LF.w); // shear stresses const Real D12 = inv2h * (LN.u-LS.u + LE.v-LW.v); // shear stresses const Real D13 = inv2h * (LE.w-LW.w + LB.u-LF.u); // shear stresses const Real D23 = inv2h * (LB.v-LF.v + LN.w-LS.w); // shear stresses // trace( S S^t ) where S is the sym part of the vel gradient: const Real SS = D11*D11 +D22*D22 +D33*D33 +(D12*D12 +D13*D13 +D23*D23)/2; o(ix,iy,iz).p = ( (WX*WX + WY*WY + WZ*WZ)/2 - SS ) / 2; } } }; class ComputeQcriterion : public Operator { public: ComputeQcriterion(SimulationData & s) : Operator(s) { } void operator()(const double dt) { sim.startProfiler("Qcriterion Kernel"); if(sim.bUseStretchedGrid) { printf("TODO Compute Q-criterion with stretched grids"); fflush(0); abort(); } else { const KernelQcriterion K; compute<KernelQcriterion>(K); } sim.stopProfiler(); check("Qcriterion"); } std::string getName() { return "Qcriterion"; } }; #ifdef CUP_ASYNC_DUMP static void copyDumpGrid(FluidGridMPI& grid, DumpGridMPI& dump) { std::vector<cubism::BlockInfo> vInfo1 = grid.getBlocksInfo(); std::vector<cubism::BlockInfo> vInfo2 = dump.getBlocksInfo(); const int N = vInfo1.size(); if(vInfo1.size() != vInfo2.size()) { printf("Async dump fail 1.\n"); fflush(0); MPI_Abort(grid.getCartComm(), MPI_ERR_OTHER); } #pragma omp parallel for schedule(static) for(int i=0; i<N; i++) { const cubism::BlockInfo& info1 = vInfo1[i]; const cubism::BlockInfo& info2 = vInfo2[i]; #ifndef NDEBUG Real p1[3], p2[3]; info1.pos(p1, 0,0,0); info2.pos(p2, 0,0,0); if (fabs(p1[0]-p2[0])>info1.h_gridpoint/2 || fabs(p1[1]-p2[1])>info1.h_gridpoint/2 || fabs(p1[2]-p2[2])>info1.h_gridpoint/2) { printf("Async dump fail 2.\n"); fflush(0); MPI_Abort(grid.getCartComm(), MPI_ERR_OTHER); } #endif const FluidBlock& b = *(FluidBlock*)info1.ptrBlock; DumpBlock& d = *( DumpBlock*)info2.ptrBlock; for(int iz=0; iz<FluidBlock::sizeZ; ++iz) for(int iy=0; iy<FluidBlock::sizeY; ++iy) for(int ix=0; ix<FluidBlock::sizeX; ++ix) { d(ix,iy,iz).u = b(ix,iy,iz).u; d(ix,iy,iz).v = b(ix,iy,iz).v; d(ix,iy,iz).w = b(ix,iy,iz).w; d(ix,iy,iz).chi = b(ix,iy,iz).chi; d(ix,iy,iz).p = b(ix,iy,iz).p; } } } #endif CubismUP_3D_NAMESPACE_END #endif // CubismUP_3D_ProcessOperators_h
omp_in_parallel.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include "omp_testsuite.h" /* * Checks that false is returned when called from serial region * and true is returned when called within parallel region. */ int test_omp_in_parallel() { int serial; int isparallel; serial = 1; isparallel = 0; serial = omp_in_parallel(); #pragma omp parallel { #pragma omp single { isparallel = omp_in_parallel(); } } return (!(serial) && isparallel); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_in_parallel()) { num_failed++; } } return num_failed; }
4symbol_new.h
//// //// Created by nikita on 26.09.2020. //// // //#ifndef CPU_4SYMBOL_NEW_H //#define CPU_4SYMBOL_NEW_H // //#include <vector> //#include <cmath> // //#define UNROLL_LARGE_CONSTANT 128 // //template<class Input> //inline void process_cubes_antidiag(int lower_bound, int upper_bound, int left_edge, int top_edge, // Input braid_ones, // Input *bitset_left_strand_map, // Input *bitset_top_strand_map, // Input *a_reverse, Input *b) { // // for (int j = lower_bound; j < upper_bound; ++j) { // Input left_cap, symbols, combing_condition, rev_combing_cond, top_strand_shifted; // // Input left_strand = bitset_left_strand_map[left_edge + j]; // Input top_strand = bitset_top_strand_map[top_edge + j]; // Input symbol_a = a_reverse[left_edge + j]; // Input symbol_b = b[top_edge + j]; // // int rev_counter = (sizeof(Input) * 8 - 2); // Input mask = Input(1); //// Input mask_r = Input(1) << rev_counter; // // // // upper half //#pragma GCC unroll 128 // for (int inside_diag_num = 0; inside_diag_num < sizeof(Input) * 8 / 2 - 1; ++inside_diag_num) { // left_cap = left_strand >> rev_counter; // symbols = ~(((symbol_a >> rev_counter)) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = mask & (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // if (combing_condition) { // top_strand_shifted = top_strand << rev_counter; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); // // //// symbols = ~(((symbol_a)) ^ (symbol_b << rev_counter)); //// symbols &= (symbols >> 1) & braid_ones; //// combing_condition = mask_r & (symbols | ((~(left_strand) & top_strand_shifted))); // // combing_condition <<= rev_counter; // rev_combing_cond = combing_condition ^ braid_ones; // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // // // rev_counter -= 2; // mask = (mask << 2) | Input(1); //// mask_r = mask_r | (mask_r >> 2); // } // // // center // symbols = (~(symbol_a ^ symbol_b)); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = (symbols | ((~left_strand) & top_strand)); // rev_combing_cond = combing_condition ^ braid_ones; // if (combing_condition) { // top_strand_shifted = top_strand; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_strand); // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // // // mask = braid_ones; //// mask_r = braid_ones; // // //lower half //#pragma GCC unroll 128 // for (int inside_diag_num = 0; inside_diag_num < sizeof(Input) * 8 / 2 - 1; ++inside_diag_num) { // mask <<= 2; //// mask_r >>= 2; // // left_cap = left_strand << (2 * (inside_diag_num + 1)); // symbols = ~(((symbol_a << (2 * (inside_diag_num + 1)))) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // // combing_condition = mask & (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // if (combing_condition) { // top_strand_shifted = top_strand >> (2 * (inside_diag_num + 1)); // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); //// symbols = ~(((symbol_a)) ^ (symbol_b >> (2 * (inside_diag_num + 1)))); //// symbols &= (symbols >> 1) & braid_ones; // //// combing_condition = mask_r & (symbols | ((~(left_strand) & top_strand_shifted))); // combing_condition >>= (2 * (inside_diag_num + 1)); // rev_combing_cond = combing_condition ^ braid_ones; // // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // } // // // bitset_left_strand_map[left_edge + j] = left_strand; // // bitset_top_strand_map[top_edge + j] = top_strand; // } //} // //template<class Input> //inline void process_cubes_antidiag_mpi(int lower_bound, int upper_bound, int left_edge, int top_edge, // Input braid_ones, // Input *bitset_left_strand_map, // Input *bitset_top_strand_map, // Input *a_reverse, Input *b) { // // const int upper = sizeof(Input) * 8 / 2 - 1; // //#pragma omp for simd schedule(static) aligned(bitset_top_strand_map, bitset_left_strand_map, a_reverse, b:sizeof(Input)*8) // for (int j = lower_bound; j < upper_bound; ++j) { // Input left_cap, symbols, combing_condition, rev_combing_cond, top_strand_shifted; // // Input left_strand = bitset_left_strand_map[left_edge + j]; // Input top_strand = bitset_top_strand_map[top_edge + j]; // Input symbol_a = a_reverse[left_edge + j]; // Input symbol_b = b[top_edge + j]; // // Input mask = Input(1); // // // // upper half // #pragma GCC unroll 64 // for (int rev_counter = (sizeof(Input) * 8 - 2); rev_counter > 0; rev_counter -= 2) { // // left_cap = left_strand >> rev_counter; // symbols = ~(((symbol_a >> rev_counter)) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = mask & (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // top_strand_shifted = top_strand << rev_counter; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); // // combing_condition <<= rev_counter; // rev_combing_cond = combing_condition ^ braid_ones; // // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // // // mask = (mask << 2) | Input(1); // } // // // center // // // symbols = (~(symbol_a ^ symbol_b)); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = (symbols | ((~left_strand) & top_strand)); // rev_combing_cond = combing_condition ^ braid_ones; // top_strand_shifted = top_strand; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_strand); // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // // // mask = braid_ones; // // //lower half // #pragma GCC unroll 64 // for (int inside_diag_num = 2; inside_diag_num < upper * 2 + 1; inside_diag_num += 2) { // mask <<= 2; // // left_cap = left_strand << (inside_diag_num); // symbols = ~(((symbol_a << inside_diag_num)) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // // combing_condition = mask & (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // top_strand_shifted = top_strand >> ((inside_diag_num)); // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); // combing_condition >>= ((inside_diag_num)); // rev_combing_cond = combing_condition ^ braid_ones; // // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // // // bitset_left_strand_map[left_edge + j] = left_strand; // bitset_top_strand_map[top_edge + j] = top_strand; // } //} // // //template<class Input> //inline void process_cube_with_exception(int left_edge, int top_edge, int j, Input braid_ones, Input l_active_mask, // Input r_active_mask, // Input *bitset_left_strand_map, Input *bitset_top_strand_map, Input *a_reverse, // Input *b) { // // Input left_cap, symbols, combing_condition, rev_combing_cond, top_strand_shifted; // // Input left_strand = bitset_left_strand_map[left_edge + j]; // Input top_strand = bitset_top_strand_map[top_edge + j]; // Input symbol_a = a_reverse[left_edge + j]; // Input symbol_b = b[top_edge + j]; // // int rev_counter = (sizeof(Input) * 8 - 2); // Input mask = Input(1); // Input mask_r = Input(1) << rev_counter; // // // // upper half // for (int inside_diag_num = 0; inside_diag_num < sizeof(Input) * 8 / 2; ++inside_diag_num) { // left_cap = left_strand >> rev_counter; // symbols = ~(((symbol_a >> rev_counter)) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = // r_active_mask & (l_active_mask >> rev_counter) & mask & (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // if (combing_condition) { // top_strand_shifted = top_strand << rev_counter; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); // // symbols = ~(((symbol_a)) ^ (symbol_b << rev_counter)); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = (r_active_mask << rev_counter) & l_active_mask & mask_r & // (symbols | ((~(left_strand) & top_strand_shifted))); // rev_combing_cond = combing_condition ^ braid_ones; // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // // // rev_counter -= 2; // mask = (mask << 2) | Input(1); // mask_r = mask_r | (mask_r >> 2); // } // // // center // symbols = (~(symbol_a ^ symbol_b)); // symbols &= (symbols >> 1) & braid_ones; // combing_condition = l_active_mask & r_active_mask & (symbols | ((~left_strand) & top_strand)); // rev_combing_cond = combing_condition ^ braid_ones; // if (combing_condition) { // top_strand_shifted = top_strand; // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_strand); // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // // // mask = braid_ones; // mask_r = braid_ones; // // //lower half // for (int inside_diag_num = 0; inside_diag_num < sizeof(Input) * 8 / 2; ++inside_diag_num) { // mask <<= 2; // mask_r >>= 2; // // left_cap = left_strand << (2 * (inside_diag_num + 1)); // symbols = ~(((symbol_a << (2 * (inside_diag_num + 1)))) ^ symbol_b); // symbols &= (symbols >> 1) & braid_ones; // // combing_condition = r_active_mask & (l_active_mask << (2 * (inside_diag_num + 1))) & mask & // (symbols | (((~(left_cap)) & top_strand))); // rev_combing_cond = combing_condition ^ braid_ones; // // if (combing_condition) { // top_strand_shifted = top_strand >> (2 * (inside_diag_num + 1)); // top_strand = (rev_combing_cond & top_strand) | (combing_condition & left_cap); // symbols = ~(((symbol_a)) ^ (symbol_b >> (2 * (inside_diag_num + 1)))); // symbols &= (symbols >> 1) & braid_ones; // // combing_condition = (r_active_mask >> (2 * (inside_diag_num + 1))) & l_active_mask & mask_r & // (symbols | ((~(left_strand) & top_strand_shifted))); // rev_combing_cond = combing_condition ^ braid_ones; // // left_strand = (rev_combing_cond & left_strand) | (combing_condition & top_strand_shifted); // } // } // // // bitset_left_strand_map[left_edge + j] = left_strand; // bitset_top_strand_map[top_edge + j] = top_strand; // //} // // //template<class Input> //int prefix_lcs_via_braid_bits_4symbol_v2_full_mask(Input *a_reverse, int a_size, int a_total_symbols, // Input *b, int b_size, int b_total_symbols, int threads_num) { // // // Input *bitset_left_strand_map = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * a_size)); // Input *bitset_top_strand_map = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * b_size)); // // // auto m = a_size, n = b_size; // // int dis_braid = 0; // auto num_diag = m + n - 1; // auto total_same_length_diag = num_diag - (m - 1) - (m - 1); // // Input braid_ones = Input(1); // for (int shift = 0; shift < sizeof(Input) * 8 / 2; shift++) { // braid_ones |= (braid_ones << shift * 2); // } // //#pragma omp parallel num_threads(threads_num) default(none) shared(bitset_left_strand_map, bitset_top_strand_map, a_reverse, b, m, n, dis_braid, total_same_length_diag, braid_ones) // { // //#pragma omp for simd schedule(static) aligned(bitset_left_strand_map:sizeof(Input)*8) // for (int k = 0; k < n; ++k) { // bitset_top_strand_map[k] = Input(0); // } // //#pragma omp for simd schedule(static) aligned(bitset_left_strand_map:sizeof(Input)*8) // for (int k = 0; k < m; ++k) { // bitset_left_strand_map[k] = braid_ones; // } // // for (int diag_len = 0; diag_len < m - 1; diag_len++) { // process_cubes_antidiag_mpi(0, diag_len + 1, m - 1 - diag_len, 0, braid_ones, bitset_left_strand_map, // bitset_top_strand_map, a_reverse, b); // // } // // for (int k = 0; k < total_same_length_diag; k++) { // process_cubes_antidiag_mpi(0, m, 0, k, braid_ones, bitset_left_strand_map, // bitset_top_strand_map, a_reverse, b); // } // // auto start_j = total_same_length_diag; // // for (int diag_len = m - 1; diag_len >= 1; diag_len--) { // process_cubes_antidiag_mpi(0, diag_len, 0, start_j, braid_ones, bitset_left_strand_map, // bitset_top_strand_map, a_reverse, b); // start_j++; // } // //#pragma omp for simd schedule(static) reduction(+:dis_braid) aligned(bitset_top_strand_map, bitset_left_strand_map, a_reverse, b:sizeof(Input)*8) // for (int i1 = 0; i1 < m; ++i1) { // // Brian Kernighan’s Algorithm // int counter = 0; //// dis_braid+= __builtin_popcount(bitset_left_strand_map[i1]); // Input number = bitset_left_strand_map[i1]; // // LogNumber // while (number) { // number &= (number - 1); // counter++; // } // dis_braid += counter; // } // // } // // // free(bitset_left_strand_map); // free(bitset_top_strand_map); // // return a_total_symbols - dis_braid; // //} // // // ////[..... ////.....] /////** //// * a <= b //// * @tparam Input //// * @param a_reverse //// * @param a_size //// * @param a_total_symbols //// * @param b //// * @param b_size //// * @param b_total_symbols //// * @return //// */ ////template<class Input> ////int prefix_lcs_via_braid_bits_4symbol_mpi(Input *a_reverse, int a_size, int a_total_symbols, //// Input *b, int b_size, int b_total_symbols, int threads_num) { //// int active_symbols_a_active = a_total_symbols % (sizeof(Input) * 8 / 2); //// int active_symbols_b_active = b_total_symbols % (sizeof(Input) * 8 / 2); //// phase //// //// if (active_symbols_a_active == 0 && active_symbols_b_active == 0) { //// //multiple case //// return prefix_lcs_via_braid_bits_4symbol_splited_mpi(a_reverse, a_size, a_total_symbols, b, b_size, //// b_total_symbols, threads_num); //// } else if (a_size == 1 && b_size == 1) { //// return prefix_lcs_via_braid_4symbol_one_one_size(a_reverse[0], a_total_symbols, b[0], b_total_symbols); //// } else if (a_size == 1) { //// return prefix_lcs_via_braid_bits_4symbol_splited_a_one_b_arbitrary(a_reverse, a_size, a_total_symbols, b, //// b_size, b_total_symbols); //// } else if (a_size == b_size) { //// return prefix_lcs_via_braid_bits_4symbol_splited_a_equals_b_mpi(a_reverse, a_size, a_total_symbols, b, b_size, //// b_total_symbols, threads_num); //// } //// return prefix_lcs_via_braid_bits_4symbol_splited_a_less_b_mpi( //// a_reverse, a_size, a_total_symbols, b, b_size, b_total_symbols, threads_num); ////} //// //#endif //CPU_4SYMBOL_NEW_H
pi2.c
/* * This code calculates pi using the formula to calculate * the atan(z) which is the integral from 0 to z of 1/(1+x*x) * times dx. atan(1) is 45 degrees or pi/4 */ #include <omp.h> static long num_steps = 100000; /* number of intervals */ double step; /* the size of the interval - dx */ #define NUM_THREADS 2 void main () { int i; /* Loop control variable */ double x; /* Actually not used */ double pi; /* final results */ double sum[NUM_THREADS]; /* Maintains partial sum for thread */ step = 1.0 / ( double ) num_steps; /* * This may be done more flexibly by using an environment * variable instead. */ omp_set_num_threads( NUM_THREADS ); /* * Each thread executes the code below * * See what happens if private ( i ) is removed! */ #pragma omp parallel private ( i ) { double x; /* The current x position for function evaluation */ int id; /* The identity of the thread */ id = omp_get_thread_num(); /* * Calculate the integral */ for ( i = id, sum[ id ] = 0.0; i < num_steps; i = i + NUM_THREADS ){ x = ( i + 0.5 ) * step; sum[ id ] += 4.0 / ( 1.0 + x * x ); } } /* * Multiply by dx */ for ( i = 0, pi = 0.0; i < NUM_THREADS; i++) pi += sum[ i ] * step; printf( "The computed value of pi is %f\n", pi ); }
traverse.h
#ifndef traverse_lazy_h #define traverse_lazy_h #include "exafmm.h" #if USE_XITAO #include "hilbert.h" #include "xitao.h" #endif namespace exafmm { #ifdef USE_XITAO //#define RANDOM_STA double hilbert_sta(real_t X[2]) { const int locs = 8; constexpr float dx = 2 * M_PI / (1 << locs); int x = floor((X[0] + M_PI) / dx); int y = floor((X[1] + M_PI) / dx); int key = xy2d(locs, x, y); double sta = double(key) / (1 << (2 * locs)); return sta; } class FMM_TAO_1 : public AssemblyTask { typedef std::function<void(Cell*)> fmm_func_type; Cell* cell; fmm_func_type fmm_func; public: FMM_TAO_1(Cell*& _cell, fmm_func_type _fmm_func, size_t _workload_hint ) : AssemblyTask(1), cell(_cell), fmm_func(_fmm_func) { workload_hint = _workload_hint; //set_sta(hilbert_sta(_cell->X)); #ifdef RANDOM_STA set_sta(drand48()); #else set_sta(hilbert_sta(_cell->X)); #endif } void execute(int nthread) { if(nthread == leader) { fmm_func(cell); } } void cleanup() {} }; class P2PListTAO : public AssemblyTask { Cell* cell_i; public: P2PListTAO(Cell* _cell_i) : AssemblyTask(1), cell_i (_cell_i) { //criticality = 1; // set_sta(hilbert_sta(cell_i->X)); #ifdef RANDOM_STA set_sta(drand48()); #else set_sta(hilbert_sta(cell_i->X)); #endif } void execute(int nthread) { assert(width > 0); int tid = nthread - leader; int size = cell_i->NBODY / width; int start = tid * size; int end = (tid == width - 1)? cell_i->NBODY : start + size; // if(nthread == leader) { for (size_t j=0; j<cell_i->listP2P.size(); j++) { // Loop over P2P list // assert(start < end); P2P(cell_i,cell_i->listP2P[j], start, end); // P2P kernel // P2P(cell_i,cell_i->listP2P[j]); // P2P kernel } //} } void cleanup() {} }; class M2LListTAO : public AssemblyTask { Cell* cell_i; public: M2LListTAO(Cell* _cell_i) : AssemblyTask(1), cell_i (_cell_i) { #ifdef RANDOM_STA set_sta(drand48()); #else set_sta(hilbert_sta(cell_i->X)); #endif } void execute(int nthread) { if(nthread == leader) { for (size_t j=0; j<cell_i->listM2L.size(); j++) { // Loop over P2P list M2L(cell_i,cell_i->listM2L[j]); // M2L kernel } } } void cleanup() {} }; std::vector<FMM_TAO_1*> M2M_map; std::vector<M2LListTAO*> M2L_map; std::vector<P2PListTAO*> P2P_map; FMM_TAO_1* upwardPass_xitao(Cell * Ci) { std::vector<FMM_TAO_1*> childTAOs; for (Cell * Cj=Ci->CHILD; Cj!=Ci->CHILD+Ci->NCHILD; Cj++) { // Loop over child cells childTAOs.push_back(upwardPass_xitao(Cj)); // Recursive call for child cell } // End loop over child cells Ci->M.resize(P, 0.0); // Allocate and initialize multipole coefs Ci->L.resize(P, 0.0); // Allocate and initialize local coefs FMM_TAO_1* M2M_tao = new FMM_TAO_1(Ci, M2M, 1); if (Ci->NCHILD == 0) { FMM_TAO_1* P2M_tao = new FMM_TAO_1(Ci, P2M, 0); P2M_tao->make_edge(M2M_tao); xitao_push(P2M_tao); } else { for(auto&& child : childTAOs) child->make_edge(M2M_tao); } M2M_map[Ci->INDEX] = M2M_tao; return M2M_tao; } void upwardPass(Cells & cells) { M2M_map.resize(cells.size(), NULL); M2L_map.resize(cells.size(), NULL); P2P_map.resize(cells.size(), NULL); auto val = upwardPass_xitao(&cells[0]); if(val == NULL) { cout << "Empty upward pass DAG" << endl; } } //! Recursive call to dual tree traversal for list construction void getList(Cell * Ci, Cell * Cj) { for (int d=0; d<2; d++) dX[d] = Ci->X[d] - Cj->X[d]; // Distance vector from source to target real_t R2 = norm(dX) * theta * theta; // Scalar distance squared if (R2 > (Ci->R + Cj->R) * (Ci->R + Cj->R)) { // If distance is far enough Ci->listM2L.push_back(Cj); // Add to M2L list } else if (Ci->NCHILD == 0 && Cj->NCHILD == 0) { // Else if both cells are leafs Ci->listP2P.push_back(Cj); // Add to P2P list } else if (Cj->NCHILD == 0 || (Ci->R >= Cj->R && Ci->NCHILD != 0)) {// Else if Cj is leaf or Ci is larger for (Cell * ci=Ci->CHILD; ci!=Ci->CHILD+Ci->NCHILD; ci++) {// Loop over Ci's children getList(ci, Cj); // Recursive call to target child cells } // End loop over Ci's children } else { // Else if Ci is leaf or Cj is larger for (Cell * cj=Cj->CHILD; cj!=Cj->CHILD+Cj->NCHILD; cj++) {// Loop over Cj's children getList(Ci, cj); // Recursive call to source child cells } // End loop over Cj's children } // End if for leafs and Ci Cj size } void buildHorizonalDAG(Cells & cells) { for (size_t i=0; i<cells.size(); i++) { // Loop over cells if(cells[i].listM2L.size() > 0) { M2LListTAO* M2L_tao = new M2LListTAO(&cells[i]); // M2L kernel M2L_map[cells[i].INDEX] = M2L_tao; for (size_t j=0; j<cells[i].listM2L.size(); j++) { // Loop over M2L list M2M_map[cells[i].listM2L[j]->INDEX]->make_edge(M2L_tao); } } if(cells[i].listP2P.size() > 0) { P2PListTAO* P2P_tao = new P2PListTAO(&cells[i]); // P2P kernel P2P_map[cells[i].INDEX] = P2P_tao; xitao_push(P2P_tao); } } } //! Horizontal pass interface void horizontalPass(Cells & icells, Cells & jcells) { getList(&icells[0], &jcells[0]); // Pass root cell to recursive call buildHorizonalDAG(icells); } //! Recursive call to pre-order traversal for downward pass void downwardPass(Cell * Cj, FMM_TAO_1* parent) { FMM_TAO_1* L2L_tao = new FMM_TAO_1(Cj, L2L, 2); if(M2L_map[Cj->INDEX] != NULL){ M2L_map[Cj->INDEX]->make_edge(L2L_tao); } for (Cell * Ci=Cj->CHILD; Ci!=Cj->CHILD+Cj->NCHILD; Ci++) { // Loop over child cells if(M2L_map[Ci->INDEX] != NULL){ M2L_map[Ci->INDEX]->make_edge(L2L_tao); // L2L kernel } } if(parent) { parent->make_edge(L2L_tao); } else { xitao_push(L2L_tao); } if (Cj->NCHILD == 0) { FMM_TAO_1* L2P_tao = new FMM_TAO_1(Cj, L2P, 3); P2P_map[Cj->INDEX]->make_edge(L2P_tao); L2L_tao->make_edge(L2P_tao); } // L2P kernel for (Cell * Ci=Cj->CHILD; Ci!=Cj->CHILD+Cj->NCHILD; Ci++) { // Loop over child cells downwardPass(Ci, L2L_tao); // Recursive call for child cell } // End loop over child cells } //! Downward pass interface void downwardPass(Cells & cells) { downwardPass(&cells[0], NULL); // Pass root cell to recursive call } #else //! Recursive call to post-order tree traversal for upward pass void upwardPass(Cell * Ci) { for (Cell * Cj=Ci->CHILD; Cj!=Ci->CHILD+Ci->NCHILD; Cj++) { // Loop over child cells #pragma omp task untied if(Cj->NBODY > 100) // Start OpenMP task if large enough task upwardPass(Cj); // Recursive call for child cell } // End loop over child cells #pragma omp taskwait // Synchronize OpenMP tasks Ci->M.resize(P, 0.0); // Allocate and initialize multipole coefs Ci->L.resize(P, 0.0); // Allocate and initialize local coefs if (Ci->NCHILD == 0) P2M(Ci); // P2M kernel M2M(Ci); // M2M kernel } //! Upward pass interface void upwardPass(Cells & cells) { #pragma omp parallel // Start OpenMP #pragma omp single nowait // Start OpenMP single region with nowait upwardPass(&cells[0]); // Pass root cell to recursive call } //! Recursive call to dual tree traversal for list construction void getList(Cell * Ci, Cell * Cj) { for (int d=0; d<2; d++) dX[d] = Ci->X[d] - Cj->X[d]; // Distance vector from source to target real_t R2 = norm(dX) * theta * theta; // Scalar distance squared if (R2 > (Ci->R + Cj->R) * (Ci->R + Cj->R)) { // If distance is far enough Ci->listM2L.push_back(Cj); // Add to M2L list } else if (Ci->NCHILD == 0 && Cj->NCHILD == 0) { // Else if both cells are leafs Ci->listP2P.push_back(Cj); // Add to P2P list } else if (Cj->NCHILD == 0 || (Ci->R >= Cj->R && Ci->NCHILD != 0)) {// Else if Cj is leaf or Ci is larger for (Cell * ci=Ci->CHILD; ci!=Ci->CHILD+Ci->NCHILD; ci++) {// Loop over Ci's children getList(ci, Cj); // Recursive call to target child cells } // End loop over Ci's children } else { // Else if Ci is leaf or Cj is larger for (Cell * cj=Cj->CHILD; cj!=Cj->CHILD+Cj->NCHILD; cj++) {// Loop over Cj's children getList(Ci, cj); // Recursive call to source child cells } // End loop over Cj's children } // End if for leafs and Ci Cj size } //! Evaluate M2L, P2P kernels void evaluate(Cells & cells) { #pragma omp parallel for schedule(dynamic) for (size_t i=0; i<cells.size(); i++) { // Loop over cells for (size_t j=0; j<cells[i].listM2L.size(); j++) { // Loop over M2L list M2L(&cells[i],cells[i].listM2L[j]); // M2L kernel } // End loop over M2L list for (size_t j=0; j<cells[i].listP2P.size(); j++) { // Loop over P2P list P2P(&cells[i],cells[i].listP2P[j]); // P2P kernel } // End loop over P2P list } // End loop over cells } //! Horizontal pass interface void horizontalPass(Cells & icells, Cells & jcells) { getList(&icells[0], &jcells[0]); // Pass root cell to recursive call evaluate(icells); // Evaluate M2L & P2P kernels } //! Recursive call to pre-order traversal for downward pass void downwardPass(Cell * Cj) { L2L(Cj); // L2L kernel if (Cj->NCHILD == 0) L2P(Cj); // L2P kernel for (Cell * Ci=Cj->CHILD; Ci!=Cj->CHILD+Cj->NCHILD; Ci++) { // Loop over child cells #pragma omp task untied if(Ci->NBODY > 100) // Start OpenMP task if large enough task downwardPass(Ci); // Recursive call for child cell } // End loop over child cells #pragma omp taskwait // Synchronize OpenMP tasks } //! Downward pass interface void downwardPass(Cells & cells) { #pragma omp parallel // Start OpenMP #pragma omp single nowait // Start OpenMP single region with nowait downwardPass(&cells[0]); // Pass root cell to recursive call } #endif //! Direct summation void direct(Bodies & bodies, Bodies & jbodies) { Cells cells(2); // Define a pair of cells to pass to P2P kernel Cell * Ci = &cells[0]; // Allocate single target cell Cell * Cj = &cells[1]; // Allocate single source cell Ci->BODY = &bodies[0]; // Pointer of first target body Ci->NBODY = bodies.size(); // Number of target bodies Cj->BODY = &jbodies[0]; // Pointer of first source body Cj->NBODY = jbodies.size(); // Number of source bodies P2P(Ci, Cj); // Evaluate P2P kernel } } #endif
GB_unop__identity_uint32_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__identity_uint32_fp32) // op(A') function: GB (_unop_tran__identity_uint32_fp32) // C type: uint32_t // A type: float // cast: uint32_t cij = GB_cast_to_uint32_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ uint32_t // 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 = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = GB_cast_to_uint32_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = GB_cast_to_uint32_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint32_fp32) ( uint32_t *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] ; uint32_t z = GB_cast_to_uint32_t ((double) (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 ; float aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_t ((double) (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_uint32_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
par_nongalerkin.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG 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. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "../HYPRE.h" /* This file contains the routines for constructing non-Galerkin coarse grid * operators, based on the original Galerkin coarse grid */ /* Take all of the indices from indices[start, start+1, start+2, ..., end] * and take the corresponding entries in array and place them in-order in output. * Assumptions: * output is of length end-start+1 * indices never contains an index that goes out of bounds in array * */ HYPRE_Int hypre_GrabSubArray(HYPRE_Int * indices, HYPRE_Int start, HYPRE_Int end, HYPRE_Int * array, HYPRE_Int * output) { HYPRE_Int i, length; length = end - start + 1; for(i = 0; i < length; i++) { output[i] = array[ indices[start + i] ]; } return 0; } /* Quick Sort based on magnitude on w (HYPRE_Real), move v */ void hypre_qsort2_abs( HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap2( v, w, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (fabs(w[i]) < fabs(w[left])) { hypre_swap2(v, w, ++last, i); } hypre_swap2(v, w, left, last); hypre_qsort2_abs(v, w, left, last-1); hypre_qsort2_abs(v, w, last+1, right); } /* Compute the intersection of x and y, placing * the intersection in z. Additionally, the array * x_data is associated with x, i.e., the entries * that we grab from x, we also grab from x_data. * If x[k] is placed in z[m], then x_data[k] goes to * output_x_data[m]. * * Assumptions: * z is of length min(x_length, y_length) * x and y are sorted * x_length and y_length are similar in size, otherwise, * in the longer array is faster. * */ HYPRE_Int hypre_IntersectTwoArrays(HYPRE_Int *x, HYPRE_Real *x_data, HYPRE_Int x_length, HYPRE_Int *y, HYPRE_Int y_length, HYPRE_Int *z, HYPRE_Real *output_x_data, HYPRE_Int *intersect_length) { HYPRE_Int x_index = 0; HYPRE_Int y_index = 0; *intersect_length = 0; /* Compute Intersection, looping over each array */ while ( (x_index < x_length) && (y_index < y_length) ) { if (x[x_index] > y[y_index]) { y_index = y_index + 1; } else if (x[x_index] < y[y_index]) { x_index = x_index + 1; } else { z[*intersect_length] = x[x_index]; output_x_data[*intersect_length] = x_data[x_index]; x_index = x_index + 1; y_index = y_index + 1; *intersect_length = *intersect_length + 1; } } return 1; } /* Copy CSR matrix A to CSR matrix B. The column indices are * assumed to be sorted, and the sparsity pattern of B is a subset * of the sparsity pattern of A. * * Assumptions: * Column indices of A and B are sorted * Sparsity pattern of B is a subset of A's * A and B are the same size and have same data layout **/ HYPRE_Int hypre_SortedCopyParCSRData(hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B) { /* Grab off A and B's data structures */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Real *B_diag_data = hypre_CSRMatrixData(B_diag); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Real *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int *temp_int_array = NULL; HYPRE_Int temp_int_array_length=0; HYPRE_Int i, length, offset_A, offset_B; for(i = 0; i < num_variables; i++) { /* Deal with the first row entries, which may be diagonal elements */ if( A_diag_j[A_diag_i[i]] == i) { offset_A = 1; } else { offset_A = 0; } if( B_diag_j[B_diag_i[i]] == i) { offset_B = 1; } else { offset_B = 0; } if( (offset_B == 1) && (offset_A == 1) ) { B_diag_data[B_diag_i[i]] = A_diag_data[A_diag_i[i]]; } /* This finds the intersection of the column indices, and * also copies the matching data in A to the data array in B **/ if( (A_diag_i[i+1] - A_diag_i[i] - offset_A) > temp_int_array_length ) { hypre_TFree(temp_int_array); temp_int_array_length = (A_diag_i[i+1] - A_diag_i[i] - offset_A); temp_int_array = hypre_CTAlloc(HYPRE_Int, temp_int_array_length); } hypre_IntersectTwoArrays(&(A_diag_j[A_diag_i[i] + offset_A]), &(A_diag_data[A_diag_i[i] + offset_A]), A_diag_i[i+1] - A_diag_i[i] - offset_A, &(B_diag_j[B_diag_i[i] + offset_B]), B_diag_i[i+1] - B_diag_i[i] - offset_B, temp_int_array, &(B_diag_data[B_diag_i[i] + offset_B]), &length); if( (A_offd_i[i+1] - A_offd_i[i]) > temp_int_array_length ) { hypre_TFree(temp_int_array); temp_int_array_length = (A_offd_i[i+1] - A_offd_i[i]); temp_int_array = hypre_CTAlloc(HYPRE_Int, temp_int_array_length); } hypre_IntersectTwoArrays(&(A_offd_j[A_offd_i[i]]), &(A_offd_data[A_offd_i[i]]), A_offd_i[i+1] - A_offd_i[i], &(B_offd_j[B_offd_i[i]]), B_offd_i[i+1] - B_offd_i[i], temp_int_array, &(B_offd_data[B_offd_i[i]]), &length); } if(temp_int_array) { hypre_TFree(temp_int_array); } return 1; } /* * Equivalent to hypre_BoomerAMGCreateS, except, the data array of S * is not Null and contains the data entries from A. */ HYPRE_Int hypre_BoomerAMG_MyCreateS(hypre_ParCSRMatrix *A, HYPRE_Real strength_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = NULL; HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int num_cols_offd = 0; hypre_ParCSRMatrix *S; hypre_CSRMatrix *S_diag; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; HYPRE_Real *S_diag_data; hypre_CSRMatrix *S_offd; HYPRE_Int *S_offd_i = NULL; HYPRE_Int *S_offd_j = NULL; HYPRE_Real *S_offd_data; HYPRE_Real diag, row_scale, row_sum; HYPRE_Int i, jA, jS; HYPRE_Int ierr = 0; HYPRE_Int *dof_func_offd; HYPRE_Int num_sends; HYPRE_Int *int_buf_data; HYPRE_Int index, start, j; /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = aij, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ num_nonzeros_diag = A_diag_i[num_variables]; num_cols_offd = hypre_CSRMatrixNumCols(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); num_nonzeros_offd = A_offd_i[num_variables]; /* Initialize S */ S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars, row_starts, row_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); /* row_starts is owned by A, col_starts = row_starts */ hypre_ParCSRMatrixSetRowStartsOwner(S,0); S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1); hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag); hypre_CSRMatrixData(S_diag) = hypre_CTAlloc(HYPRE_Real, num_nonzeros_diag); S_offd = hypre_ParCSRMatrixOffd(S); hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1); S_diag_i = hypre_CSRMatrixI(S_diag); S_diag_j = hypre_CSRMatrixJ(S_diag); S_diag_data = hypre_CSRMatrixData(S_diag); S_offd_i = hypre_CSRMatrixI(S_offd); dof_func_offd = NULL; if (num_cols_offd) { A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); hypre_CSRMatrixData(S_offd) = hypre_CTAlloc(HYPRE_Real, num_nonzeros_offd); S_offd_j = hypre_CSRMatrixJ(S_offd); S_offd_data = hypre_CSRMatrixData(S_offd); hypre_ParCSRMatrixColMapOffd(S) = hypre_CTAlloc(HYPRE_Int, num_cols_offd); if (num_functions > 1) dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); } /*------------------------------------------------------------------- * Get the dof_func data for the off-processor columns *-------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_functions > 1) { int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); } /* give S same nonzero structure as A */ hypre_ParCSRMatrixCopy(A,S,1); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,diag,row_scale,row_sum,jA) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_variables; i++) { diag = A_diag_data[A_diag_i[i]]; /* compute scaling factor and row sum */ row_scale = 0.0; row_sum = diag; if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } } else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } /* compute row entries of S */ S_diag_j[A_diag_i[i]] = -1; if ((fabs(row_sum) > fabs(diag)*max_row_sum) && (max_row_sum < 1.0)) { /* make all dependencies weak */ for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { S_diag_j[jA] = -1; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { S_offd_j[jA] = -1; } } else { if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_offd_j[jA] = -1; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_offd_j[jA] = -1; } } } } else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale) { S_offd_j[jA] = -1; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale) { S_offd_j[jA] = -1; } } } } } } /*-------------------------------------------------------------- * "Compress" the strength matrix. * * NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor! * * NOTE: This "compression" section of code may not be removed, the * non-Galerkin routine depends on it. *----------------------------------------------------------------*/ /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_diag_i[i] = jS; for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++) { if (S_diag_j[jA] > -1) { S_diag_j[jS] = S_diag_j[jA]; S_diag_data[jS] = S_diag_data[jA]; jS++; } } } S_diag_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_diag) = jS; /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_offd_i[i] = jS; for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (S_offd_j[jA] > -1) { S_offd_j[jS] = S_offd_j[jA]; S_offd_data[jS] = S_offd_data[jA]; jS++; } } } S_offd_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_offd) = jS; hypre_ParCSRMatrixCommPkg(S) = NULL; *S_ptr = S; hypre_TFree(dof_func_offd); return (ierr); } /** * Initialize the IJBuffer counters **/ HYPRE_Int hypre_NonGalerkinIJBufferInit( HYPRE_Int *ijbuf_cnt, /* See NonGalerkinIJBufferWrite for parameter descriptions */ HYPRE_Int *ijbuf_rowcounter, HYPRE_Int *ijbuf_numcols ) { HYPRE_Int ierr = 0; (*ijbuf_cnt) = 0; (*ijbuf_rowcounter) = 1; /*Always points to the next row*/ ijbuf_numcols[0] = 0; return ierr; } /** * Update the buffer counters **/ HYPRE_Int hypre_NonGalerkinIJBufferNewRow(HYPRE_Int *ijbuf_rownums, /* See NonGalerkinIJBufferWrite for parameter descriptions */ HYPRE_Int *ijbuf_numcols, HYPRE_Int *ijbuf_rowcounter, HYPRE_Int new_row) { HYPRE_Int ierr = 0; /* First check to see if the previous row was empty, and if so, overwrite that row */ if( ijbuf_numcols[(*ijbuf_rowcounter)-1] == 0 ) { ijbuf_rownums[(*ijbuf_rowcounter)-1] = new_row; } else { /* Move to the next row */ ijbuf_rownums[(*ijbuf_rowcounter)] = new_row; ijbuf_numcols[(*ijbuf_rowcounter)] = 0; (*ijbuf_rowcounter)++; } return ierr; } /** * Compress the current row in an IJ Buffer by removing duplicate entries **/ HYPRE_Int hypre_NonGalerkinIJBufferCompressRow( HYPRE_Int *ijbuf_cnt, /* See NonGalerkinIJBufferWrite for parameter descriptions */ HYPRE_Int ijbuf_rowcounter, HYPRE_Real *ijbuf_data, HYPRE_Int *ijbuf_cols, HYPRE_Int *ijbuf_rownums, HYPRE_Int *ijbuf_numcols) { HYPRE_Int ierr = 0; HYPRE_Int nentries, i, nduplicate; /* Compress the current row by removing any repeat entries, * making sure to decrement ijbuf_cnt by nduplicate */ nentries = ijbuf_numcols[ ijbuf_rowcounter-1 ]; nduplicate = 0; hypre_qsort1(ijbuf_cols, ijbuf_data, (*ijbuf_cnt)-nentries, (*ijbuf_cnt)-1 ); for(i =(*ijbuf_cnt)-nentries+1; i <= (*ijbuf_cnt)-1; i++) { if( ijbuf_cols[i] == ijbuf_cols[i-1] ) { /* Shift duplicate entry down */ nduplicate++; ijbuf_data[i - nduplicate] += ijbuf_data[i]; } else if(nduplicate > 0) { ijbuf_data[i - nduplicate] = ijbuf_data[i]; ijbuf_cols[i - nduplicate] = ijbuf_cols[i]; } } (*ijbuf_cnt) -= nduplicate; ijbuf_numcols[ ijbuf_rowcounter-1 ] -= nduplicate; return ierr; } /** * Compress the entire buffer, removing duplicate rows **/ HYPRE_Int hypre_NonGalerkinIJBufferCompress( HYPRE_Int ijbuf_size, HYPRE_Int *ijbuf_cnt, /* See NonGalerkinIJBufferWrite for parameter descriptions */ HYPRE_Int *ijbuf_rowcounter, HYPRE_Real **ijbuf_data, HYPRE_Int **ijbuf_cols, HYPRE_Int **ijbuf_rownums, HYPRE_Int **ijbuf_numcols) { HYPRE_Int ierr = 0; HYPRE_Int *indys = hypre_CTAlloc(HYPRE_Int, (*ijbuf_rowcounter) ); HYPRE_Int i, j, duplicate, cnt_new, rowcounter_new, prev_row; HYPRE_Int row_start, row_stop, row_loc, row; HYPRE_Real *data_new; HYPRE_Int *cols_new; HYPRE_Int *rownums_new; HYPRE_Int *numcols_new; /* Do a sort on rownums, but store the original order in indys. * Then see if there are any duplicate rows */ for(i = 0; i < (*ijbuf_rowcounter); i++) { indys[i] = i; } hypre_qsort2i((*ijbuf_rownums), indys, 0, (*ijbuf_rowcounter)-1); duplicate = 0; for(i = 1; i < (*ijbuf_rowcounter); i++) { if(indys[i] != (indys[i-1]+1)) { duplicate = 1; break; } } /* Compress duplicate rows */ if(duplicate) { /* Accumulate numcols, so that it functions like a CSR row-pointer */ for(i = 1; i < (*ijbuf_rowcounter); i++) { (*ijbuf_numcols)[i] += (*ijbuf_numcols)[i-1]; } /* Initialize new buffer */ prev_row = -1; rowcounter_new = 0; cnt_new = 0; data_new = hypre_CTAlloc(HYPRE_Real, ijbuf_size); cols_new = hypre_CTAlloc(HYPRE_Int, ijbuf_size); rownums_new = hypre_CTAlloc(HYPRE_Int, ijbuf_size); numcols_new = hypre_CTAlloc(HYPRE_Int, ijbuf_size); numcols_new[0] = 0; /* Cycle through each row */ for(i = 0; i < (*ijbuf_rowcounter); i++) { /* Find which row this is in local and global numberings, and where * this row's data starts and stops in the buffer*/ row_loc = indys[i]; row = (*ijbuf_rownums)[i]; if(row_loc > 0) { row_start = (*ijbuf_numcols)[row_loc-1]; row_stop = (*ijbuf_numcols)[row_loc]; } else { row_start = 0; row_stop = (*ijbuf_numcols)[row_loc]; } /* Is this a new row? If so, compress previous row, and add a new * one. Noting that prev_row = -1 is a special value */ if(row != prev_row) { if(prev_row != -1) { /* Compress previous row */ hypre_NonGalerkinIJBufferCompressRow(&cnt_new, rowcounter_new, data_new, cols_new, rownums_new, numcols_new); } prev_row = row; numcols_new[rowcounter_new] = 0; rownums_new[rowcounter_new] = row; rowcounter_new++; } /* Copy row into new buffer */ for(j = row_start; j < row_stop; j++) { data_new[cnt_new] = (*ijbuf_data)[j]; cols_new[cnt_new] = (*ijbuf_cols)[j]; numcols_new[rowcounter_new-1]++; cnt_new++; } } /* Compress the final row */ if(i > 1) { hypre_NonGalerkinIJBufferCompressRow(&cnt_new, rowcounter_new, data_new, cols_new, rownums_new, numcols_new); } *ijbuf_cnt = cnt_new; *ijbuf_rowcounter = rowcounter_new; /* Point to the new buffer */ hypre_TFree(*ijbuf_data); hypre_TFree(*ijbuf_cols); hypre_TFree(*ijbuf_rownums); hypre_TFree(*ijbuf_numcols); (*ijbuf_data) = data_new; (*ijbuf_cols) = cols_new; (*ijbuf_rownums) = rownums_new; (*ijbuf_numcols) = numcols_new; } hypre_TFree(indys); return ierr; } /** * Do a buffered write to an IJ matrix. * That is, write to the buffer, until the buffer is full. Then when the * buffer is full, write to the IJ matrix and reset the buffer counters * In effect, this buffers this operation * A[row_to_write, col_to_write] += val_to_write **/ HYPRE_Int hypre_NonGalerkinIJBufferWrite( HYPRE_IJMatrix B, /* Unassembled matrix to add an entry to */ HYPRE_Int *ijbuf_cnt, /* current buffer size */ HYPRE_Int ijbuf_size, /* max buffer size */ HYPRE_Int *ijbuf_rowcounter, /* num of rows in rownums, (i.e., size of rownums) */ /* This counter will increase as you call this function for multiple rows */ HYPRE_Real **ijbuf_data, /* Array of values, of size ijbuf_size */ HYPRE_Int **ijbuf_cols, /* Array of col indices, of size ijbuf_size */ HYPRE_Int **ijbuf_rownums, /* Holds row-indices that with numcols makes for a CSR-like data structure*/ HYPRE_Int **ijbuf_numcols, /* rownums[i] is the row num, and numcols holds the number of entries being added */ /* for that row. Note numcols is not cumulative like an actual CSR data structure*/ HYPRE_Int row_to_write, /* Entry to add to the buffer */ HYPRE_Int col_to_write, /* Ditto */ HYPRE_Real val_to_write ) /* Ditto */ { HYPRE_Int ierr = 0; if( (*ijbuf_cnt) == 0 ) { /* brand new buffer: increment buffer structures for the new row */ hypre_NonGalerkinIJBufferNewRow((*ijbuf_rownums), (*ijbuf_numcols), ijbuf_rowcounter, row_to_write); } else if((*ijbuf_rownums)[ (*ijbuf_rowcounter)-1 ] != row_to_write) { /* If this is a new row, compress the previous row */ hypre_NonGalerkinIJBufferCompressRow(ijbuf_cnt, (*ijbuf_rowcounter), (*ijbuf_data), (*ijbuf_cols), (*ijbuf_rownums), (*ijbuf_numcols)); /* increment buffer structures for the new row */ hypre_NonGalerkinIJBufferNewRow( (*ijbuf_rownums), (*ijbuf_numcols), ijbuf_rowcounter, row_to_write); } /* Add new entry to buffer */ (*ijbuf_cols)[(*ijbuf_cnt)] = col_to_write; (*ijbuf_data)[(*ijbuf_cnt)] = val_to_write; (*ijbuf_numcols)[ (*ijbuf_rowcounter)-1 ]++; (*ijbuf_cnt)++; /* Buffer is full, write to the matrix object */ if ( (*ijbuf_cnt) == (ijbuf_size-1) ) { /* If the last row is empty, decrement rowcounter */ if( (*ijbuf_numcols)[ (*ijbuf_rowcounter)-1 ] == 0) { (*ijbuf_rowcounter)--; } /* Compress and Add Entries */ hypre_NonGalerkinIJBufferCompressRow(ijbuf_cnt, (*ijbuf_rowcounter), (*ijbuf_data), (*ijbuf_cols), (*ijbuf_rownums), (*ijbuf_numcols)); hypre_NonGalerkinIJBufferCompress(ijbuf_size, ijbuf_cnt, ijbuf_rowcounter, ijbuf_data, ijbuf_cols, ijbuf_rownums, ijbuf_numcols); ierr += HYPRE_IJMatrixAddToValues(B, *ijbuf_rowcounter, (*ijbuf_numcols), (*ijbuf_rownums), (*ijbuf_cols), (*ijbuf_data)); /* Reinitialize the buffer */ hypre_NonGalerkinIJBufferInit( ijbuf_cnt, ijbuf_rowcounter, (*ijbuf_numcols)); hypre_NonGalerkinIJBufferNewRow((*ijbuf_rownums), (*ijbuf_numcols), ijbuf_rowcounter, row_to_write); } return ierr; } /** * Empty the IJ Buffer with a final AddToValues. **/ HYPRE_Int hypre_NonGalerkinIJBufferEmpty(HYPRE_IJMatrix B, /* See NonGalerkinIJBufferWrite for parameter descriptions */ HYPRE_Int ijbuf_size, HYPRE_Int *ijbuf_cnt, HYPRE_Int ijbuf_rowcounter, HYPRE_Real **ijbuf_data, HYPRE_Int **ijbuf_cols, HYPRE_Int **ijbuf_rownums, HYPRE_Int **ijbuf_numcols) { HYPRE_Int ierr = 0; if( (*ijbuf_cnt) > 0) { /* Compress the last row and then write */ hypre_NonGalerkinIJBufferCompressRow(ijbuf_cnt, ijbuf_rowcounter, (*ijbuf_data), (*ijbuf_cols), (*ijbuf_rownums), (*ijbuf_numcols)); hypre_NonGalerkinIJBufferCompress(ijbuf_size, ijbuf_cnt, &ijbuf_rowcounter, ijbuf_data, ijbuf_cols, ijbuf_rownums, ijbuf_numcols); ierr += HYPRE_IJMatrixAddToValues(B, ijbuf_rowcounter, (*ijbuf_numcols), (*ijbuf_rownums), (*ijbuf_cols), (*ijbuf_data)); } (*ijbuf_cnt = 0); return ierr; } /* * Construct sparsity pattern based on R_I A P, plus entries required by drop tolerance */ hypre_ParCSRMatrix * hypre_NonGalerkinSparsityPattern(hypre_ParCSRMatrix *R_IAP, hypre_ParCSRMatrix *RAP, HYPRE_Int * CF_marker, HYPRE_Real droptol, HYPRE_Int sym_collapse, HYPRE_Int collapse_beta ) { /* MPI Communicator */ MPI_Comm comm = hypre_ParCSRMatrixComm(RAP); /* Declare R_IAP */ hypre_CSRMatrix *R_IAP_diag = hypre_ParCSRMatrixDiag(R_IAP); HYPRE_Int *R_IAP_diag_i = hypre_CSRMatrixI(R_IAP_diag); HYPRE_Int *R_IAP_diag_j = hypre_CSRMatrixJ(R_IAP_diag); hypre_CSRMatrix *R_IAP_offd = hypre_ParCSRMatrixOffd(R_IAP); HYPRE_Int *R_IAP_offd_i = hypre_CSRMatrixI(R_IAP_offd); HYPRE_Int *R_IAP_offd_j = hypre_CSRMatrixJ(R_IAP_offd); HYPRE_Int *col_map_offd_R_IAP = hypre_ParCSRMatrixColMapOffd(R_IAP); /* Declare RAP */ hypre_CSRMatrix *RAP_diag = hypre_ParCSRMatrixDiag(RAP); HYPRE_Int *RAP_diag_i = hypre_CSRMatrixI(RAP_diag); HYPRE_Real *RAP_diag_data = hypre_CSRMatrixData(RAP_diag); HYPRE_Int *RAP_diag_j = hypre_CSRMatrixJ(RAP_diag); HYPRE_Int first_col_diag_RAP = hypre_ParCSRMatrixFirstColDiag(RAP); HYPRE_Int num_cols_diag_RAP = hypre_CSRMatrixNumCols(RAP_diag); HYPRE_Int last_col_diag_RAP = first_col_diag_RAP + num_cols_diag_RAP - 1; hypre_CSRMatrix *RAP_offd = hypre_ParCSRMatrixOffd(RAP); HYPRE_Int *RAP_offd_i = hypre_CSRMatrixI(RAP_offd); HYPRE_Real *RAP_offd_data = NULL; HYPRE_Int *RAP_offd_j = hypre_CSRMatrixJ(RAP_offd); HYPRE_Int *col_map_offd_RAP = hypre_ParCSRMatrixColMapOffd(RAP); HYPRE_Int num_cols_RAP_offd = hypre_CSRMatrixNumCols(RAP_offd); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(RAP_diag); /* Declare A */ HYPRE_Int num_fine_variables = hypre_CSRMatrixNumRows(R_IAP_diag); /* Declare IJ matrices */ HYPRE_IJMatrix Pattern; hypre_ParCSRMatrix *Pattern_CSR = NULL; /* Buffered IJAddToValues */ HYPRE_Int ijbuf_cnt, ijbuf_size, ijbuf_rowcounter; HYPRE_Real *ijbuf_data; HYPRE_Int *ijbuf_cols, *ijbuf_rownums, *ijbuf_numcols; /* Buffered IJAddToValues for Symmetric Entries */ HYPRE_Int ijbuf_sym_cnt, ijbuf_sym_rowcounter; HYPRE_Real *ijbuf_sym_data; HYPRE_Int *ijbuf_sym_cols, *ijbuf_sym_rownums, *ijbuf_sym_numcols; /* Other Declarations */ HYPRE_Int ierr = 0; HYPRE_Real max_entry = 0.0; HYPRE_Real max_entry_offd = 0.0; HYPRE_Int * rownz = NULL; HYPRE_Int i, j, Cpt, row_start, row_end, global_row, global_col; /* Other Setup */ if (num_cols_RAP_offd) { RAP_offd_data = hypre_CSRMatrixData(RAP_offd); } /* * Initialize the IJ matrix, leveraging our rough knowledge of the * nonzero structure of Pattern based on RAP * * ilower, iupper, jlower, jupper */ ierr += HYPRE_IJMatrixCreate(comm, first_col_diag_RAP, last_col_diag_RAP, first_col_diag_RAP, last_col_diag_RAP, &Pattern); ierr += HYPRE_IJMatrixSetObjectType(Pattern, HYPRE_PARCSR); rownz = hypre_CTAlloc (HYPRE_Int, num_variables); for(i = 0; i < num_variables; i++) { rownz[i] = 1.2*(RAP_diag_i[i+1] - RAP_diag_i[i]) + 1.2*(RAP_offd_i[i+1] - RAP_offd_i[i]); } HYPRE_IJMatrixSetRowSizes(Pattern, rownz); ierr += HYPRE_IJMatrixInitialize(Pattern); hypre_TFree(rownz); /* *For efficiency, we do a buffered IJAddToValues. * Here, we initialize the buffer and then initialize the buffer counters */ ijbuf_size = 1000; ijbuf_data = hypre_CTAlloc(HYPRE_Real, ijbuf_size); ijbuf_cols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_rownums = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_numcols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); hypre_NonGalerkinIJBufferInit( &ijbuf_cnt, &ijbuf_rowcounter, ijbuf_cols ); if(sym_collapse) { ijbuf_sym_data = hypre_CTAlloc(HYPRE_Real, ijbuf_size); ijbuf_sym_cols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_sym_rownums= hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_sym_numcols= hypre_CTAlloc(HYPRE_Int, ijbuf_size); hypre_NonGalerkinIJBufferInit( &ijbuf_sym_cnt, &ijbuf_sym_rowcounter, ijbuf_sym_cols ); } /* * Place entries in R_IAP into Pattern */ Cpt = -1; /* Cpt contains the fine grid index of the i-th Cpt */ for(i = 0; i < num_variables; i++) { global_row = i+first_col_diag_RAP; /* Find the next Coarse Point in CF_marker */ for(j = Cpt+1; j < num_fine_variables; j++) { if(CF_marker[j] == 1) /* Found Next C-point */ { Cpt = j; break; } } /* Diag Portion */ row_start = R_IAP_diag_i[Cpt]; row_end = R_IAP_diag_i[Cpt+1]; for(j = row_start; j < row_end; j++) { global_col = R_IAP_diag_j[j] + first_col_diag_RAP; /* This call adds a 1 x 1 to i j data */ hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_col, 1.0); if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, global_col, global_row, 1.0); } } /* Offdiag Portion */ row_start = R_IAP_offd_i[Cpt]; row_end = R_IAP_offd_i[Cpt+1]; for(j = row_start; j < row_end; j++) { global_col = col_map_offd_R_IAP[ R_IAP_offd_j[j] ]; /* This call adds a 1 x 1 to i j data */ hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_col, 1.0); if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, global_col, global_row, 1.0); } } } /* * Use drop-tolerance to compute new entries for sparsity pattern */ /*#ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,max_entry,max_entry_offd,global_col,global_row) HYPRE_SMP_SCHEDULE #endif*/ for(i = 0; i < num_variables; i++) { global_row = i+first_col_diag_RAP; /* Compute the drop tolerance for this row, which is just * abs(max of row i)*droptol */ max_entry = -1.0; for(j = RAP_diag_i[i]; j < RAP_diag_i[i+1]; j++) { if( (RAP_diag_j[j] != i) && (max_entry < fabs(RAP_diag_data[j]) ) ) { max_entry = fabs(RAP_diag_data[j]); } } for(j = RAP_offd_i[i]; j < RAP_offd_i[i+1]; j++) { { if( max_entry < fabs(RAP_offd_data[j]) ) { max_entry = fabs(RAP_offd_data[j]); } } } max_entry *= droptol; max_entry_offd = max_entry*collapse_beta; /* Loop over diag portion, adding all entries that are "strong" */ for(j = RAP_diag_i[i]; j < RAP_diag_i[i+1]; j++) { if( fabs(RAP_diag_data[j]) > max_entry ) { global_col = RAP_diag_j[j] + first_col_diag_RAP; /*#ifdef HYPRE_USING_OPENMP #pragma omp critical (IJAdd) #endif {*/ /* For efficiency, we do a buffered IJAddToValues * A[global_row, global_col] += 1.0 */ hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_col, 1.0 ); if(sym_collapse) { hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, global_col, global_row, 1.0 ); } /*}*/ } } /* Loop over offd portion, adding all entries that are "strong" */ for(j = RAP_offd_i[i]; j < RAP_offd_i[i+1]; j++) { if( fabs(RAP_offd_data[j]) > max_entry_offd ) { global_col = col_map_offd_RAP[ RAP_offd_j[j] ]; /*#ifdef HYPRE_USING_OPENMP #pragma omp critical (IJAdd) #endif {*/ /* For efficiency, we do a buffered IJAddToValues * A[global_row, global_col] += 1.0 */ hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_col, 1.0 ); if(sym_collapse) { hypre_NonGalerkinIJBufferWrite( Pattern, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, global_col, global_row, 1.0 ); } /*}*/ } } } /* For efficiency, we do a buffered IJAddToValues. * This empties the buffer of any remaining values */ hypre_NonGalerkinIJBufferEmpty(Pattern, ijbuf_size, &ijbuf_cnt, ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols); if(sym_collapse) hypre_NonGalerkinIJBufferEmpty(Pattern, ijbuf_size, &ijbuf_sym_cnt, ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols); /* Finalize Construction of Pattern */ ierr += HYPRE_IJMatrixAssemble(Pattern); ierr += HYPRE_IJMatrixGetObject( Pattern, (void**) &Pattern_CSR ); /* Deallocate */ ierr += HYPRE_IJMatrixSetObjectType(Pattern, -1); ierr += HYPRE_IJMatrixDestroy(Pattern); hypre_TFree(ijbuf_data); hypre_TFree(ijbuf_cols); hypre_TFree(ijbuf_rownums); hypre_TFree(ijbuf_numcols); if(sym_collapse) { hypre_TFree(ijbuf_sym_data); hypre_TFree(ijbuf_sym_cols); hypre_TFree(ijbuf_sym_rownums); hypre_TFree(ijbuf_sym_numcols); } return Pattern_CSR; } HYPRE_Int hypre_BoomerAMGBuildNonGalerkinCoarseOperator( hypre_ParCSRMatrix **RAP_ptr, hypre_ParCSRMatrix *AP, HYPRE_Real strong_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int * dof_func_value, HYPRE_Real S_commpkg_switch, HYPRE_Int * CF_marker, HYPRE_Real droptol, HYPRE_Int sym_collapse, HYPRE_Real lump_percent, HYPRE_Int collapse_beta ) { /* Initializations */ MPI_Comm comm = hypre_ParCSRMatrixComm(*RAP_ptr); hypre_ParCSRMatrix *S = NULL; hypre_ParCSRMatrix *RAP = *RAP_ptr; HYPRE_Int *col_offd_S_to_A = NULL; HYPRE_Int i, j, k, row_start, row_end, value, num_cols_offd_Sext, num_procs; HYPRE_Int S_ext_diag_size, S_ext_offd_size, last_col_diag_RAP, cnt_offd, cnt_diag, cnt; HYPRE_Int col_indx_Pattern, current_Pattern_j, col_indx_RAP; /* HYPRE_Real start_time = hypre_MPI_Wtime(); */ /* HYPRE_Real end_time; */ HYPRE_Int * temp = NULL; HYPRE_Int ierr = 0; char filename[256]; /* Lumping related variables */ HYPRE_IJMatrix ijmatrix; HYPRE_Int * Pattern_offd_indices = NULL; HYPRE_Int * S_offd_indices = NULL; HYPRE_Int * offd_intersection = NULL; HYPRE_Real * offd_intersection_data = NULL; HYPRE_Int * diag_intersection = NULL; HYPRE_Real * diag_intersection_data = NULL; HYPRE_Int Pattern_offd_indices_len = 0; HYPRE_Int Pattern_offd_indices_allocated_len= 0; HYPRE_Int S_offd_indices_len = 0; HYPRE_Int S_offd_indices_allocated_len = 0; HYPRE_Int offd_intersection_len = 0; HYPRE_Int offd_intersection_allocated_len = 0; HYPRE_Int diag_intersection_len = 0; HYPRE_Int diag_intersection_allocated_len = 0; HYPRE_Real intersection_len = 0; HYPRE_Int * Pattern_indices_ptr = NULL; HYPRE_Int Pattern_diag_indices_len = 0; HYPRE_Int global_row = 0; HYPRE_Int has_row_ended = 0; HYPRE_Real lump_value = 0.; HYPRE_Real diagonal_lump_value = 0.; HYPRE_Real neg_lump_value = 0.; HYPRE_Real sum_strong_neigh = 0.; HYPRE_Int * rownz = NULL; /* offd and diag portions of RAP */ hypre_CSRMatrix *RAP_diag = hypre_ParCSRMatrixDiag(RAP); HYPRE_Int *RAP_diag_i = hypre_CSRMatrixI(RAP_diag); HYPRE_Real *RAP_diag_data = hypre_CSRMatrixData(RAP_diag); HYPRE_Int *RAP_diag_j = hypre_CSRMatrixJ(RAP_diag); HYPRE_Int first_col_diag_RAP = hypre_ParCSRMatrixFirstColDiag(RAP); HYPRE_Int num_cols_diag_RAP = hypre_CSRMatrixNumCols(RAP_diag); hypre_CSRMatrix *RAP_offd = hypre_ParCSRMatrixOffd(RAP); HYPRE_Int *RAP_offd_i = hypre_CSRMatrixI(RAP_offd); HYPRE_Real *RAP_offd_data = NULL; HYPRE_Int *RAP_offd_j = hypre_CSRMatrixJ(RAP_offd); HYPRE_Int *col_map_offd_RAP = hypre_ParCSRMatrixColMapOffd(RAP); HYPRE_Int num_cols_RAP_offd = hypre_CSRMatrixNumCols(RAP_offd); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(RAP_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(RAP); /* offd and diag portions of S */ hypre_CSRMatrix *S_diag = NULL; HYPRE_Int *S_diag_i = NULL; HYPRE_Real *S_diag_data = NULL; HYPRE_Int *S_diag_j = NULL; hypre_CSRMatrix *S_offd = NULL; HYPRE_Int *S_offd_i = NULL; HYPRE_Real *S_offd_data = NULL; HYPRE_Int *S_offd_j = NULL; HYPRE_Int *col_map_offd_S = NULL; HYPRE_Int num_cols_offd_S; /* HYPRE_Int num_nonzeros_S_diag; */ /* off processor portions of S */ hypre_CSRMatrix *S_ext = NULL; HYPRE_Int *S_ext_i = NULL; HYPRE_Real *S_ext_data = NULL; HYPRE_Int *S_ext_j = NULL; HYPRE_Int *S_ext_diag_i = NULL; HYPRE_Real *S_ext_diag_data = NULL; HYPRE_Int *S_ext_diag_j = NULL; HYPRE_Int *S_ext_offd_i = NULL; HYPRE_Real *S_ext_offd_data = NULL; HYPRE_Int *S_ext_offd_j = NULL; HYPRE_Int *col_map_offd_Sext = NULL; /* HYPRE_Int num_nonzeros_S_ext_diag; HYPRE_Int num_nonzeros_S_ext_offd; HYPRE_Int num_rows_Sext = 0; */ HYPRE_Int row_indx_Sext = 0; /* offd and diag portions of Pattern */ hypre_ParCSRMatrix *Pattern = NULL; hypre_CSRMatrix *Pattern_diag = NULL; HYPRE_Int *Pattern_diag_i = NULL; HYPRE_Real *Pattern_diag_data = NULL; HYPRE_Int *Pattern_diag_j = NULL; hypre_CSRMatrix *Pattern_offd = NULL; HYPRE_Int *Pattern_offd_i = NULL; HYPRE_Real *Pattern_offd_data = NULL; HYPRE_Int *Pattern_offd_j = NULL; HYPRE_Int *col_map_offd_Pattern = NULL; HYPRE_Int num_cols_Pattern_offd; HYPRE_Int my_id; /* Buffered IJAddToValues */ HYPRE_Int ijbuf_cnt, ijbuf_size, ijbuf_rowcounter; HYPRE_Real *ijbuf_data; HYPRE_Int *ijbuf_cols, *ijbuf_rownums, *ijbuf_numcols; /* Buffered IJAddToValues for Symmetric Entries */ HYPRE_Int ijbuf_sym_cnt, ijbuf_sym_rowcounter; HYPRE_Real *ijbuf_sym_data; HYPRE_Int *ijbuf_sym_cols, *ijbuf_sym_rownums, *ijbuf_sym_numcols; /* Further Initializations */ if (num_cols_RAP_offd) { RAP_offd_data = hypre_CSRMatrixData(RAP_offd); } hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* Compute Sparsity Pattern */ Pattern = hypre_NonGalerkinSparsityPattern(AP, RAP, CF_marker, droptol, sym_collapse, collapse_beta); Pattern_diag = hypre_ParCSRMatrixDiag(Pattern); Pattern_diag_i = hypre_CSRMatrixI(Pattern_diag); Pattern_diag_data = hypre_CSRMatrixData(Pattern_diag); Pattern_diag_j = hypre_CSRMatrixJ(Pattern_diag); Pattern_offd = hypre_ParCSRMatrixOffd(Pattern); Pattern_offd_i = hypre_CSRMatrixI(Pattern_offd); Pattern_offd_j = hypre_CSRMatrixJ(Pattern_offd); col_map_offd_Pattern = hypre_ParCSRMatrixColMapOffd(Pattern); num_cols_Pattern_offd = hypre_CSRMatrixNumCols(Pattern_offd); if (num_cols_Pattern_offd) { Pattern_offd_data = hypre_CSRMatrixData(Pattern_offd); } /** * Fill in the entries of Pattern with entries from RAP **/ /* First, sort column indices in RAP and Pattern */ for(i = 0; i < num_variables; i++) { /* The diag matrices store the diagonal as first element in each row. * We maintain that for the case of Pattern and RAP, because the * strength of connection routine relies on it and we need to ignore * diagonal entries in Pattern later during set intersections. * */ /* Sort diag portion of RAP */ row_start = RAP_diag_i[i]; if( RAP_diag_j[row_start] == i) { row_start = row_start + 1; } row_end = RAP_diag_i[i+1]; hypre_qsort1(RAP_diag_j, RAP_diag_data, row_start, row_end-1 ); /* Sort diag portion of Pattern */ row_start = Pattern_diag_i[i]; if( Pattern_diag_j[row_start] == i) { row_start = row_start + 1; } row_end = Pattern_diag_i[i+1]; hypre_qsort1(Pattern_diag_j, Pattern_diag_data, row_start, row_end-1 ); /* Sort offd portion of RAP */ row_start = RAP_offd_i[i]; row_end = RAP_offd_i[i+1]; hypre_qsort1(RAP_offd_j, RAP_offd_data, row_start, row_end-1 ); /* Sort offd portion of Pattern */ /* Be careful to map coarse dof i with CF_marker into Pattern */ row_start = Pattern_offd_i[i]; row_end = Pattern_offd_i[i+1]; hypre_qsort1(Pattern_offd_j, Pattern_offd_data, row_start, row_end-1 ); } /* Create Strength matrix based on RAP or Pattern. If Pattern is used, * then the SortedCopyParCSRData(...) function call must also be commented * back in */ /* hypre_SortedCopyParCSRData(RAP, Pattern); */ if(0) { /* hypre_BoomerAMG_MyCreateS(Pattern, strong_threshold, max_row_sum, */ hypre_BoomerAMG_MyCreateS(RAP, strong_threshold, max_row_sum, num_functions, dof_func_value, &S); } else { /* Passing in "1, NULL" because dof_array is not needed * because we assume that the number of functions is 1 */ /* hypre_BoomerAMG_MyCreateS(Pattern, strong_threshold, max_row_sum,*/ hypre_BoomerAMG_MyCreateS(RAP, strong_threshold, max_row_sum, 1, NULL, &S); } /*if (0)*/ /*(strong_threshold > S_commpkg_switch)*/ /*{ hypre_BoomerAMG_MyCreateSCommPkg(RAP, S, &col_offd_S_to_A); }*/ /* Grab diag and offd parts of S */ S_diag = hypre_ParCSRMatrixDiag(S); S_diag_i = hypre_CSRMatrixI(S_diag); S_diag_j = hypre_CSRMatrixJ(S_diag); S_diag_data = hypre_CSRMatrixData(S_diag); S_offd = hypre_ParCSRMatrixOffd(S); S_offd_i = hypre_CSRMatrixI(S_offd); S_offd_j = hypre_CSRMatrixJ(S_offd); S_offd_data = hypre_CSRMatrixData(S_offd); col_map_offd_S = hypre_ParCSRMatrixColMapOffd(S); num_cols_offd_S = hypre_CSRMatrixNumCols(S_offd); /* num_nonzeros_S_diag = S_diag_i[num_variables]; */ /* Grab part of S that is distance one away from the local rows * This is needed later for the stencil collapsing. This section * of the code mimics par_rap.c when it extracts Ps_ext. * When moving from par_rap.c, the variable name changes were: * A --> RAP * P --> S * Ps_ext --> S_ext * P_ext_diag --> S_ext_diag * P_ext_offd --> S_ext_offd * * The data layout of S_ext as returned by ExtractBExt gives you only global * column indices, and must be converted to the local numbering. This code * section constructs S_ext_diag and S_ext_offd, which are the distance 1 * couplings in S based on the sparsity structure in RAP. * --> S_ext_diag corresponds to the same column slice that RAP_diag * corresponds to. Thus, the column indexing is the same as in * RAP_diag such that S_ext_diag_j[k] just needs to be offset by * the RAP_diag first global dof offset. * --> S_ext_offd column indexing is a little more complicated, and * requires the computation below of col_map_S_ext_offd, which * maps the local 0,1,2,... column indexing in S_ext_offd to global * dof numbers. Note, that the num_cols_RAP_offd is NOT equal to * num_cols_offd_S_ext * --> The row indexing of S_ext_diag|offd is as follows. Use * col_map_offd_RAP, where the first index corresponds to the * first global row index in S_ext_diag|offd. Remember that ExtractBExt * grabs the information from S required for locally computing * (RAP*S)[proc_k row slice, :] */ if (num_procs > 1) { S_ext = hypre_ParCSRMatrixExtractBExt(S,RAP,1); S_ext_data = hypre_CSRMatrixData(S_ext); S_ext_i = hypre_CSRMatrixI(S_ext); S_ext_j = hypre_CSRMatrixJ(S_ext); } /* This uses the num_cols_RAP_offd to set S_ext_diag|offd_i, because S_ext * is the off-processor information needed to compute RAP*S. That is, * num_cols_RAP_offd represents the number of rows needed from S_ext for * the multiplication */ S_ext_diag_i = hypre_CTAlloc(HYPRE_Int,num_cols_RAP_offd+1); S_ext_offd_i = hypre_CTAlloc(HYPRE_Int,num_cols_RAP_offd+1); S_ext_diag_size = 0; S_ext_offd_size = 0; /* num_rows_Sext = num_cols_RAP_offd; */ last_col_diag_RAP = first_col_diag_RAP + num_cols_diag_RAP - 1; /* construct the S_ext_diag and _offd row-pointer arrays by counting elements * This looks to create offd and diag blocks related to the local rows belonging * to this processor...we may not need to split up S_ext this way...or we could. * be the bottle neck so LETS SPLIT THIS UP Between offd and diag*/ for (i=0; i < num_cols_RAP_offd; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) if (S_ext_j[j] < first_col_diag_RAP || S_ext_j[j] > last_col_diag_RAP) S_ext_offd_size++; else S_ext_diag_size++; S_ext_diag_i[i+1] = S_ext_diag_size; S_ext_offd_i[i+1] = S_ext_offd_size; } if (S_ext_diag_size) { S_ext_diag_j = hypre_CTAlloc(HYPRE_Int, S_ext_diag_size); S_ext_diag_data = hypre_CTAlloc(HYPRE_Real, S_ext_diag_size); } if (S_ext_offd_size) { S_ext_offd_j = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size); S_ext_offd_data = hypre_CTAlloc(HYPRE_Real, S_ext_offd_size); } /* This copies over the column indices into the offd and diag parts. * The diag portion has it's local column indices shifted to start at 0. * The offd portion requires more work to construct the col_map_offd array * and a local column ordering. */ cnt_offd = 0; cnt_diag = 0; cnt = 0; for (i=0; i < num_cols_RAP_offd; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) if (S_ext_j[j] < first_col_diag_RAP || S_ext_j[j] > last_col_diag_RAP) { S_ext_offd_data[cnt_offd] = S_ext_data[j]; S_ext_offd_j[cnt_offd++] = S_ext_j[j]; } else { S_ext_diag_data[cnt_diag] = S_ext_data[j]; S_ext_diag_j[cnt_diag++] = S_ext_j[j] - first_col_diag_RAP; } } if (num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); S_ext = NULL; } /* This creates col_map_offd_Sext */ if (S_ext_offd_size || num_cols_offd_S) { temp = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size+num_cols_offd_S); for (i=0; i < S_ext_offd_size; i++) temp[i] = S_ext_offd_j[i]; cnt = S_ext_offd_size; for (i=0; i < num_cols_offd_S; i++) temp[cnt++] = col_map_offd_S[i]; } if (cnt) { /* after this, the first so many entries of temp will hold the * unique column indices in S_ext_offd_j unioned with the indices * in col_map_offd_S */ hypre_qsort0(temp, 0, cnt-1); num_cols_offd_Sext = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_Sext++] = value; } } } else { num_cols_offd_Sext = 0; } /* num_nonzeros_S_ext_diag = cnt_diag; num_nonzeros_S_ext_offd = S_ext_offd_size; */ if (num_cols_offd_Sext) col_map_offd_Sext = hypre_CTAlloc(HYPRE_Int, num_cols_offd_Sext); for (i=0; i < num_cols_offd_Sext; i++) col_map_offd_Sext[i] = temp[i]; if (S_ext_offd_size || num_cols_offd_S) hypre_TFree(temp); /* look for S_ext_offd_j[i] in col_map_offd_Sext, and set S_ext_offd_j[i] * to the index of that column value in col_map_offd_Sext */ for (i=0 ; i < S_ext_offd_size; i++) S_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_Sext, S_ext_offd_j[i], num_cols_offd_Sext); /* Need to sort column indices in S and S_ext */ for(i = 0; i < num_variables; i++) { /* Re-Sort diag portion of Pattern, placing the diagonal entry in a * sorted position */ row_start = Pattern_diag_i[i]; row_end = Pattern_diag_i[i+1]; hypre_qsort1(Pattern_diag_j, Pattern_diag_data, row_start, row_end-1 ); /* Sort diag portion of S, noting that no diagonal entry */ /* S has not "data" array...it's just NULL */ row_start = S_diag_i[i]; row_end = S_diag_i[i+1]; hypre_qsort1(S_diag_j, S_diag_data, row_start, row_end-1 ); /* Sort offd portion of S */ /* S has no "data" array...it's just NULL */ row_start = S_offd_i[i]; row_end = S_offd_i[i+1]; hypre_qsort1(S_offd_j, S_offd_data, row_start, row_end-1 ); } /* Sort S_ext * num_cols_RAP_offd equals num_rows for S_ext*/ for(i = 0; i < num_cols_RAP_offd; i++) { /* Sort diag portion of S_ext */ row_start = S_ext_diag_i[i]; row_end = S_ext_diag_i[i+1]; hypre_qsort1(S_ext_diag_j, S_ext_diag_data, row_start, row_end-1 ); /* Sort offd portion of S_ext */ row_start = S_ext_offd_i[i]; row_end = S_ext_offd_i[i+1]; hypre_qsort1(S_ext_offd_j, S_ext_offd_data, row_start, row_end-1 ); } /* * Now, for the fun stuff -- Computing the Non-Galerkin Operator */ /* Initialize the ijmatrix, leveraging our knowledge of the nonzero * structure in Pattern */ ierr += HYPRE_IJMatrixCreate(comm, first_col_diag_RAP, last_col_diag_RAP, first_col_diag_RAP, last_col_diag_RAP, &ijmatrix); ierr += HYPRE_IJMatrixSetObjectType(ijmatrix, HYPRE_PARCSR); rownz = hypre_CTAlloc (HYPRE_Int, num_variables); for(i = 0; i < num_variables; i++) { rownz[i] = 1.2*(Pattern_diag_i[i+1] - Pattern_diag_i[i]) + 1.2*(Pattern_offd_i[i+1] - Pattern_offd_i[i]); } HYPRE_IJMatrixSetRowSizes(ijmatrix, rownz); ierr += HYPRE_IJMatrixInitialize(ijmatrix); hypre_TFree(rownz); /* *For efficiency, we do a buffered IJAddToValues. * Here, we initialize the buffer and then initialize the buffer counters */ ijbuf_size = 1000; ijbuf_data = hypre_CTAlloc(HYPRE_Real,ijbuf_size); ijbuf_cols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_rownums = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_numcols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); hypre_NonGalerkinIJBufferInit( &ijbuf_cnt, &ijbuf_rowcounter, ijbuf_cols ); if(sym_collapse) { ijbuf_sym_data = hypre_CTAlloc(HYPRE_Real,ijbuf_size); ijbuf_sym_cols = hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_sym_rownums= hypre_CTAlloc(HYPRE_Int, ijbuf_size); ijbuf_sym_numcols= hypre_CTAlloc(HYPRE_Int, ijbuf_size); hypre_NonGalerkinIJBufferInit( &ijbuf_sym_cnt, &ijbuf_sym_rowcounter, ijbuf_sym_cols ); } /* * Eliminate Entries In RAP_diag * */ for(i = 0; i < num_variables; i++) { global_row = i+first_col_diag_RAP; row_start = RAP_diag_i[i]; row_end = RAP_diag_i[i+1]; has_row_ended = 0; /* Only do work if row has nonzeros */ if( row_start < row_end) { /* Grab pointer to current entry in Pattern_diag */ current_Pattern_j = Pattern_diag_i[i]; col_indx_Pattern = Pattern_diag_j[current_Pattern_j]; /* Grab this row's indices out of Pattern offd and diag. This will * be for computing index set intersections for lumping */ /* Ensure adequate length */ Pattern_offd_indices_len = Pattern_offd_i[i+1] - Pattern_offd_i[i]; if(Pattern_offd_indices_allocated_len < Pattern_offd_indices_len) { hypre_TFree(Pattern_offd_indices); Pattern_offd_indices = hypre_CTAlloc(HYPRE_Int, Pattern_offd_indices_len); Pattern_offd_indices_allocated_len = Pattern_offd_indices_len; } /* Grab sub array from col_map, corresponding to the slice of Pattern_offd_j */ hypre_GrabSubArray(Pattern_offd_j, Pattern_offd_i[i], Pattern_offd_i[i+1]-1, col_map_offd_Pattern, Pattern_offd_indices); /* No need to grab info out of Pattern_diag_j[...], here we just start from * Pattern_diag_i[i] and end at index Pattern_diag_i[i+1] - 1. We do need to * ignore the diagonal entry in Pattern, because we don't lump entries there */ if( Pattern_diag_j[Pattern_diag_i[i]] == i ) { Pattern_indices_ptr = &( Pattern_diag_j[Pattern_diag_i[i]+1]); Pattern_diag_indices_len = Pattern_diag_i[i+1] - Pattern_diag_i[i] - 1; } else { Pattern_indices_ptr = &( Pattern_diag_j[Pattern_diag_i[i]]); Pattern_diag_indices_len = Pattern_diag_i[i+1] - Pattern_diag_i[i]; } } for(j = row_start; j < row_end; j++) { col_indx_RAP = RAP_diag_j[j]; /* Ignore zero entries in RAP */ if( RAP_diag_data[j] != 0.0) { /* Don't change the diagonal, just write it */ if(col_indx_RAP == i) { /*#ifdef HY PRE_USING_OPENMP #pragma omp critical (IJAdd) #endif {*/ /* For efficiency, we do a buffered IJAddToValues. * A[global_row, global_row] += RAP_diag_data[j] */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_row, RAP_diag_data[j] ); /*}*/ } /* The entry in RAP does not appear in Pattern, so LUMP it */ else if( (col_indx_RAP < col_indx_Pattern) || has_row_ended) { /* Lump entry (i, col_indx_RAP) in RAP */ /* Grab the indices for row col_indx_RAP of S_offd and diag. This will * be for computing lumping locations */ S_offd_indices_len = S_offd_i[col_indx_RAP+1] - S_offd_i[col_indx_RAP]; if(S_offd_indices_allocated_len < S_offd_indices_len) { hypre_TFree(S_offd_indices); S_offd_indices = hypre_CTAlloc(HYPRE_Int, S_offd_indices_len); S_offd_indices_allocated_len = S_offd_indices_len; } /* Grab sub array from col_map, corresponding to the slice of S_offd_j */ hypre_GrabSubArray(S_offd_j, S_offd_i[col_indx_RAP], S_offd_i[col_indx_RAP+1]-1, col_map_offd_S, S_offd_indices); /* No need to grab info out of S_diag_j[...], here we just start from * S_diag_i[col_indx_RAP] and end at index S_diag_i[col_indx_RAP+1] - 1 */ /* Intersect the diag and offd pieces, remembering that the * diag array will need to have the offset +first_col_diag_RAP */ cnt = hypre_max(S_offd_indices_len, Pattern_offd_indices_len); if(offd_intersection_allocated_len < cnt) { hypre_TFree(offd_intersection); hypre_TFree(offd_intersection_data); offd_intersection = hypre_CTAlloc(HYPRE_Int, cnt); offd_intersection_data = hypre_CTAlloc(HYPRE_Real, cnt); offd_intersection_allocated_len = cnt; } /* This intersection also tracks S_offd_data and assumes that * S_offd_indices is the first argument here */ hypre_IntersectTwoArrays(S_offd_indices, &(S_offd_data[ S_offd_i[col_indx_RAP] ]), S_offd_indices_len, Pattern_offd_indices, Pattern_offd_indices_len, offd_intersection, offd_intersection_data, &offd_intersection_len); /* Now, intersect the indices for the diag block. Note that S_diag_j does * not have a diagonal entry, so no lumping occurs to the diagonal. */ cnt = hypre_max(Pattern_diag_indices_len, S_diag_i[col_indx_RAP+1] - S_diag_i[col_indx_RAP] ); if(diag_intersection_allocated_len < cnt) { hypre_TFree(diag_intersection); hypre_TFree(diag_intersection_data); diag_intersection = hypre_CTAlloc(HYPRE_Int, cnt); diag_intersection_data = hypre_CTAlloc(HYPRE_Real, cnt); diag_intersection_allocated_len = cnt; } /* There is no diagonal entry in first position of S */ hypre_IntersectTwoArrays( &(S_diag_j[S_diag_i[col_indx_RAP]]), &(S_diag_data[ S_diag_i[col_indx_RAP] ]), S_diag_i[col_indx_RAP+1] - S_diag_i[col_indx_RAP], Pattern_indices_ptr, Pattern_diag_indices_len, diag_intersection, diag_intersection_data, &diag_intersection_len); /* Loop over these intersections, and lump a constant fraction of * RAP_diag_data[j] to each entry */ intersection_len = diag_intersection_len + offd_intersection_len; if(intersection_len > 0) { /* Sum the strength-of-connection values from row * col_indx_RAP in S, corresponding to the indices we are * collapsing to in row i This will give us our collapsing * weights. */ sum_strong_neigh = 0.0; for(k = 0; k < diag_intersection_len; k++) { sum_strong_neigh += fabs(diag_intersection_data[k]); } for(k = 0; k < offd_intersection_len; k++) { sum_strong_neigh += fabs(offd_intersection_data[k]); } sum_strong_neigh = RAP_diag_data[j]/sum_strong_neigh; /* When lumping with the diag_intersection, must offset column index */ for(k = 0; k < diag_intersection_len; k++) { lump_value = lump_percent * fabs(diag_intersection_data[k])*sum_strong_neigh; diagonal_lump_value = (1.0 - lump_percent) * fabs(diag_intersection_data[k])*sum_strong_neigh; neg_lump_value = -1.0 * lump_value; cnt = diag_intersection[k]+first_col_diag_RAP; /*#ifdef HY PRE_USING_OPENMP #pragma omp critical (IJAdd) #endif {*/ /* For efficiency, we do a buffered IJAddToValues. * A[global_row, cnt] += RAP_diag_data[j] */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, cnt, lump_value ); if (lump_percent < 1.0) { /* Preserve row sum by updating diagonal */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_row, diagonal_lump_value ); } /* Update mirror entries, if symmetric collapsing */ if(sym_collapse) { /* Update mirror entry */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, cnt, global_row, lump_value ); /* Update mirror entry diagonal */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, cnt, cnt, neg_lump_value ); } /*}*/ } /* The offd_intersection has global column indices, i.e., the * col_map arrays contain global indices */ for(k = 0; k < offd_intersection_len; k++) { lump_value = lump_percent * fabs(offd_intersection_data[k])*sum_strong_neigh; diagonal_lump_value = (1.0 - lump_percent) * fabs(offd_intersection_data[k])*sum_strong_neigh; neg_lump_value = -1.0 * lump_value; hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, offd_intersection[k], lump_value ); if (lump_percent < 1.0) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_row, diagonal_lump_value ); } /* Update mirror entries, if symmetric collapsing */ if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, offd_intersection[k], global_row, lump_value ); hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, offd_intersection[k], offd_intersection[k], neg_lump_value ); } } } /* If intersection is empty, do not eliminate entry */ else { /* Don't forget to update mirror entry if collapsing symmetrically */ if (sym_collapse) { lump_value = 0.5*RAP_diag_data[j]; } else { lump_value = RAP_diag_data[j]; } cnt = col_indx_RAP+first_col_diag_RAP; hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, cnt, lump_value ); if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, cnt, global_row, lump_value ); } } } /* The entry in RAP appears in Pattern, so keep it */ else if(col_indx_RAP == col_indx_Pattern) { cnt = col_indx_RAP+first_col_diag_RAP; hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, cnt, RAP_diag_data[j] ); /* Only go to the next entry in Pattern, if this is not the end of a row */ if( current_Pattern_j < Pattern_diag_i[i+1]-1 ) { current_Pattern_j += 1; col_indx_Pattern = Pattern_diag_j[current_Pattern_j]; } else { has_row_ended = 1;} } /* Increment col_indx_Pattern, and repeat this loop iter for current * col_ind_RAP value */ else if(col_indx_RAP > col_indx_Pattern) { for(; current_Pattern_j < Pattern_diag_i[i+1]; current_Pattern_j++) { col_indx_Pattern = Pattern_diag_j[current_Pattern_j]; if(col_indx_RAP <= col_indx_Pattern) { break;} } /* If col_indx_RAP is still greater (i.e., we've reached a row end), then * we need to lump everything else in this row */ if(col_indx_RAP > col_indx_Pattern) { has_row_ended = 1; } /* Decrement j, in order to repeat this loop iteration for the current * col_indx_RAP value */ j--; } } } } /* * Eliminate Entries In RAP_offd * Structure of this for-loop is very similar to the RAP_diag for-loop * */ if(num_cols_RAP_offd) { for(i = 0; i < num_variables; i++) { global_row = i+first_col_diag_RAP; row_start = RAP_offd_i[i]; row_end = RAP_offd_i[i+1]; has_row_ended = 0; /* Only do work if row has nonzeros */ if( row_start < row_end) { current_Pattern_j = Pattern_offd_i[i]; Pattern_offd_indices_len = Pattern_offd_i[i+1] - Pattern_offd_i[i]; if( (Pattern_offd_j != NULL) && (Pattern_offd_indices_len > 0) ) { col_indx_Pattern = col_map_offd_Pattern[ Pattern_offd_j[current_Pattern_j] ]; } else { /* if Pattern_offd_j is not allocated or this is a zero length row, then all entries need to be lumped. This is an analagous situation to has_row_ended=1. */ col_indx_Pattern = -1; has_row_ended = 1; } /* Grab this row's indices out of Pattern offd and diag. This will * be for computing index set intersections for lumping. The above * loop over RAP_diag ensures adequate length of Pattern_offd_indices */ /* Ensure adequate length */ hypre_GrabSubArray(Pattern_offd_j, Pattern_offd_i[i], Pattern_offd_i[i+1]-1, col_map_offd_Pattern, Pattern_offd_indices); /* No need to grab info out of Pattern_diag_j[...], here we just start from * Pattern_diag_i[i] and end at index Pattern_diag_i[i+1] - 1. We do need to * ignore the diagonal entry in Pattern, because we don't lump entries there */ if( Pattern_diag_j[Pattern_diag_i[i]] == i ) { Pattern_indices_ptr = &( Pattern_diag_j[Pattern_diag_i[i]+1]); Pattern_diag_indices_len = Pattern_diag_i[i+1] - Pattern_diag_i[i] - 1; } else { Pattern_indices_ptr = &( Pattern_diag_j[Pattern_diag_i[i]]); Pattern_diag_indices_len = Pattern_diag_i[i+1] - Pattern_diag_i[i]; } } for(j = row_start; j < row_end; j++) { /* Ignore zero entries in RAP */ if( RAP_offd_data[j] != 0.0) { /* In general for all the offd_j arrays, we have to indirectly * index with the col_map_offd array to get a global index */ col_indx_RAP = col_map_offd_RAP[ RAP_offd_j[j] ]; /* The entry in RAP does not appear in Pattern, so LUMP it */ if( (col_indx_RAP < col_indx_Pattern) || has_row_ended) { /* The row_indx_Sext would be found with: row_indx_Sext = hypre_BinarySearch(col_map_offd_RAP, col_indx_RAP, num_cols_RAP_offd); But, we already know the answer to this with, */ row_indx_Sext = RAP_offd_j[j]; /* Grab the indices for row row_indx_Sext from the offd and diag parts. This will * be for computing lumping locations */ S_offd_indices_len = S_ext_offd_i[row_indx_Sext+1] - S_ext_offd_i[row_indx_Sext]; if(S_offd_indices_allocated_len < S_offd_indices_len) { hypre_TFree(S_offd_indices); S_offd_indices = hypre_CTAlloc(HYPRE_Int, S_offd_indices_len); S_offd_indices_allocated_len = S_offd_indices_len; } /* Grab sub array from col_map, corresponding to the slice of S_ext_offd_j */ hypre_GrabSubArray(S_ext_offd_j, S_ext_offd_i[row_indx_Sext], S_ext_offd_i[row_indx_Sext+1]-1, col_map_offd_Sext, S_offd_indices); /* No need to grab info out of S_ext_diag_j[...], here we just start from * S_ext_diag_i[row_indx_Sext] and end at index S_ext_diag_i[row_indx_Sext+1] - 1 */ /* Intersect the diag and offd pieces, remembering that the * diag array will need to have the offset +first_col_diag_RAP */ cnt = hypre_max(S_offd_indices_len, Pattern_offd_indices_len); if(offd_intersection_allocated_len < cnt) { hypre_TFree(offd_intersection); hypre_TFree(offd_intersection_data); offd_intersection = hypre_CTAlloc(HYPRE_Int, cnt); offd_intersection_data = hypre_CTAlloc(HYPRE_Real, cnt); offd_intersection_allocated_len = cnt; } hypre_IntersectTwoArrays(S_offd_indices, &(S_ext_offd_data[ S_ext_offd_i[row_indx_Sext] ]), S_offd_indices_len, Pattern_offd_indices, Pattern_offd_indices_len, offd_intersection, offd_intersection_data, &offd_intersection_len); /* Now, intersect the indices for the diag block. */ cnt = hypre_max(Pattern_diag_indices_len, S_ext_diag_i[row_indx_Sext+1] - S_ext_diag_i[row_indx_Sext] ); if(diag_intersection_allocated_len < cnt) { hypre_TFree(diag_intersection); hypre_TFree(diag_intersection_data); diag_intersection = hypre_CTAlloc(HYPRE_Int, cnt); diag_intersection_data = hypre_CTAlloc(HYPRE_Real, cnt); diag_intersection_allocated_len = cnt; } hypre_IntersectTwoArrays( &(S_ext_diag_j[S_ext_diag_i[row_indx_Sext]]), &(S_ext_diag_data[ S_ext_diag_i[row_indx_Sext] ]), S_ext_diag_i[row_indx_Sext+1] - S_ext_diag_i[row_indx_Sext], Pattern_indices_ptr, Pattern_diag_indices_len, diag_intersection, diag_intersection_data, &diag_intersection_len); /* Loop over these intersections, and lump a constant fraction of * RAP_offd_data[j] to each entry */ intersection_len = diag_intersection_len + offd_intersection_len; if(intersection_len > 0) { /* Sum the strength-of-connection values from row * row_indx_Sext in S, corresponding to the indices we are * collapsing to in row i. This will give us our collapsing * weights. */ sum_strong_neigh = 0.0; for(k = 0; k < diag_intersection_len; k++) { sum_strong_neigh += fabs(diag_intersection_data[k]); } for(k = 0; k < offd_intersection_len; k++) { sum_strong_neigh += fabs(offd_intersection_data[k]); } sum_strong_neigh = RAP_offd_data[j]/sum_strong_neigh; /* When lumping with the diag_intersection, must offset column index */ for(k = 0; k < diag_intersection_len; k++) { lump_value = lump_percent * fabs(diag_intersection_data[k])*sum_strong_neigh; diagonal_lump_value = (1.0 - lump_percent) * fabs(diag_intersection_data[k])*sum_strong_neigh; neg_lump_value = -1.0 * lump_value; cnt = diag_intersection[k]+first_col_diag_RAP; hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, cnt, lump_value ); if (lump_percent < 1.0) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_row, diagonal_lump_value ); } /* Update mirror entries, if symmetric collapsing */ if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, cnt, global_row, lump_value); hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, cnt, cnt, neg_lump_value ); } } /* The offd_intersection has global column indices, i.e., the * col_map arrays contain global indices */ for(k = 0; k < offd_intersection_len; k++) { lump_value = lump_percent * fabs(offd_intersection_data[k])*sum_strong_neigh; diagonal_lump_value = (1.0 - lump_percent) * fabs(offd_intersection_data[k])*sum_strong_neigh; neg_lump_value = -1.0 * lump_value; hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, offd_intersection[k], lump_value ); if (lump_percent < 1.0) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, global_row, diagonal_lump_value ); } /* Update mirror entries, if symmetric collapsing */ if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, offd_intersection[k], global_row, lump_value ); hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, offd_intersection[k], offd_intersection[k], neg_lump_value ); } } } /* If intersection is empty, do not eliminate entry */ else { /* Don't forget to update mirror entry if collapsing symmetrically */ if (sym_collapse) { lump_value = 0.5*RAP_offd_data[j]; } else { lump_value = RAP_offd_data[j]; } hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, col_indx_RAP, lump_value ); if (sym_collapse) { hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_sym_cnt, ijbuf_size, &ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols, col_indx_RAP, global_row, lump_value ); } } } /* The entry in RAP appears in Pattern, so keep it */ else if (col_indx_RAP == col_indx_Pattern) { /* For the offd structure, col_indx_RAP is a global dof number */ hypre_NonGalerkinIJBufferWrite( ijmatrix, &ijbuf_cnt, ijbuf_size, &ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols, global_row, col_indx_RAP, RAP_offd_data[j]); /* Only go to the next entry in Pattern, if this is not the end of a row */ if( current_Pattern_j < Pattern_offd_i[i+1]-1 ) { current_Pattern_j += 1; col_indx_Pattern = col_map_offd_Pattern[ Pattern_offd_j[current_Pattern_j] ]; } else { has_row_ended = 1;} } /* Increment col_indx_Pattern, and repeat this loop iter for current * col_ind_RAP value */ else if(col_indx_RAP > col_indx_Pattern) { for(; current_Pattern_j < Pattern_offd_i[i+1]; current_Pattern_j++) { col_indx_Pattern = col_map_offd_Pattern[ Pattern_offd_j[current_Pattern_j] ]; if(col_indx_RAP <= col_indx_Pattern) { break;} } /* If col_indx_RAP is still greater (i.e., we've reached a row end), then * we need to lump everything else in this row */ if(col_indx_RAP > col_indx_Pattern) { has_row_ended = 1; } /* Decrement j, in order to repeat this loop iteration for the current * col_indx_RAP value */ j--; } } } } } /* For efficiency, we do a buffered IJAddToValues. * This empties the buffer of any remaining values */ hypre_NonGalerkinIJBufferEmpty(ijmatrix, ijbuf_size, &ijbuf_cnt, ijbuf_rowcounter, &ijbuf_data, &ijbuf_cols, &ijbuf_rownums, &ijbuf_numcols); if(sym_collapse) hypre_NonGalerkinIJBufferEmpty(ijmatrix, ijbuf_size, &ijbuf_sym_cnt, ijbuf_sym_rowcounter, &ijbuf_sym_data, &ijbuf_sym_cols, &ijbuf_sym_rownums, &ijbuf_sym_numcols); /* Assemble non-Galerkin Matrix, and overwrite current RAP*/ ierr += HYPRE_IJMatrixAssemble (ijmatrix); ierr += HYPRE_IJMatrixGetObject( ijmatrix, (void**) RAP_ptr); /* Optional diagnostic matrix printing */ if (0) { hypre_sprintf(filename, "Pattern_%d.ij", global_num_vars); hypre_ParCSRMatrixPrintIJ(Pattern, 0, 0, filename); hypre_sprintf(filename, "Strength_%d.ij", global_num_vars); hypre_ParCSRMatrixPrintIJ(S, 0, 0, filename); hypre_sprintf(filename, "RAP_%d.ij", global_num_vars); hypre_ParCSRMatrixPrintIJ(RAP, 0, 0, filename); hypre_sprintf(filename, "RAPc_%d.ij", global_num_vars); hypre_ParCSRMatrixPrintIJ(*RAP_ptr, 0, 0, filename); hypre_sprintf(filename, "AP_%d.ij", global_num_vars); hypre_ParCSRMatrixPrintIJ(AP, 0, 0, filename); } /* Free matrices and variables and arrays */ hypre_TFree(ijbuf_data); hypre_TFree(ijbuf_cols); hypre_TFree(ijbuf_rownums); hypre_TFree(ijbuf_numcols); if(sym_collapse) { hypre_TFree(ijbuf_sym_data); hypre_TFree(ijbuf_sym_cols); hypre_TFree(ijbuf_sym_rownums); hypre_TFree(ijbuf_sym_numcols); } hypre_TFree(Pattern_offd_indices); hypre_TFree(S_ext_diag_i); hypre_TFree(S_ext_offd_i); hypre_TFree(S_offd_indices); hypre_TFree(offd_intersection); hypre_TFree(offd_intersection_data); hypre_TFree(diag_intersection); hypre_TFree(diag_intersection_data); if (S_ext_diag_size) { hypre_TFree(S_ext_diag_j); hypre_TFree(S_ext_diag_data); } if (S_ext_offd_size) { hypre_TFree(S_ext_offd_j); hypre_TFree(S_ext_offd_data); } if (num_cols_offd_Sext) { hypre_TFree(col_map_offd_Sext); } if (0) /*(strong_threshold > S_commpkg_switch)*/ { hypre_TFree(col_offd_S_to_A); } ierr += hypre_ParCSRMatrixDestroy(Pattern); ierr += hypre_ParCSRMatrixDestroy(RAP); ierr += hypre_ParCSRMatrixDestroy(S); ierr += HYPRE_IJMatrixSetObjectType(ijmatrix, -1); ierr += HYPRE_IJMatrixDestroy(ijmatrix); /*end_time = hypre_MPI_Wtime(); if(my_id == 0) { fprintf(stdout, "NonGalerkin Time: %1.2e\n", end_time-start_time); } */ return ierr; }
residualbased_simple_steady_scheme.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Michael Andre, https://github.com/msandre // #if !defined(KRATOS_RESIDUALBASED_SIMPLE_STEADY_SCHEME ) #define KRATOS_RESIDUALBASED_SIMPLE_STEADY_SCHEME // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "solving_strategies/schemes/scheme.h" #include "includes/variables.h" #include "includes/cfd_variables.h" #include "containers/array_1d.h" #include "utilities/openmp_utils.h" #include "utilities/coordinate_transformation_utilities.h" #include "processes/process.h" namespace Kratos { ///@name Kratos Classes ///@{ template<class TSparseSpace, class TDenseSpace > class ResidualBasedSimpleSteadyScheme : public Scheme<TSparseSpace, TDenseSpace> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedSimpleSteadyScheme); typedef Scheme<TSparseSpace, TDenseSpace> BaseType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef Element::GeometryType GeometryType; ///@} ///@name Life Cycle ///@{ ResidualBasedSimpleSteadyScheme(double VelocityRelaxationFactor, double PressureRelaxationFactor, unsigned int DomainSize) : Scheme<TSparseSpace, TDenseSpace>(), mVelocityRelaxationFactor(VelocityRelaxationFactor), mPressureRelaxationFactor(PressureRelaxationFactor), mRotationTool(DomainSize,DomainSize+1,SLIP) {} ResidualBasedSimpleSteadyScheme( double VelocityRelaxationFactor, double PressureRelaxationFactor, unsigned int DomainSize, Process::Pointer pTurbulenceModel) : Scheme<TSparseSpace, TDenseSpace>(), mVelocityRelaxationFactor(VelocityRelaxationFactor), mPressureRelaxationFactor(PressureRelaxationFactor), mRotationTool(DomainSize,DomainSize+1,SLIP), mpTurbulenceModel(pTurbulenceModel) {} ~ResidualBasedSimpleSteadyScheme() override {} ///@} ///@name Operators ///@{ double GetVelocityRelaxationFactor() const { return mVelocityRelaxationFactor; } void SetVelocityRelaxationFactor(double factor) { mVelocityRelaxationFactor = factor; } double GetPressureRelaxationFactor() const { return mPressureRelaxationFactor; } void SetPressureRelaxationFactor(double factor) { mPressureRelaxationFactor = factor; } void Update(ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb) override { KRATOS_TRY; mRotationTool.RotateVelocities(rModelPart); TSparseSpace::InplaceMult(rDx, mVelocityRelaxationFactor); mpDofUpdater->UpdateDofs(rDofSet,rDx); mRotationTool.RecoverVelocities(rModelPart); KRATOS_CATCH(""); } void CalculateSystemContributions( Element& rCurrentElement, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY; rCurrentElement.InitializeNonLinearIteration(CurrentProcessInfo); rCurrentElement.CalculateLocalSystem(LHS_Contribution, RHS_Contribution, CurrentProcessInfo); Matrix SteadyLHS; rCurrentElement.CalculateLocalVelocityContribution(SteadyLHS, RHS_Contribution, CurrentProcessInfo); rCurrentElement.EquationIdVector(EquationId, CurrentProcessInfo); if (SteadyLHS.size1() != 0) noalias(LHS_Contribution) += SteadyLHS; // apply slip condition mRotationTool.Rotate(LHS_Contribution,RHS_Contribution,rCurrentElement.GetGeometry()); mRotationTool.ApplySlipCondition(LHS_Contribution,RHS_Contribution,rCurrentElement.GetGeometry()); KRATOS_CATCH(""); } void CalculateSystemContributions( Condition& rCurrentCondition, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Condition::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY; rCurrentCondition.InitializeNonLinearIteration(CurrentProcessInfo); rCurrentCondition.CalculateLocalSystem(LHS_Contribution, RHS_Contribution, CurrentProcessInfo); Matrix SteadyLHS; rCurrentCondition.CalculateLocalVelocityContribution(SteadyLHS, RHS_Contribution, CurrentProcessInfo); rCurrentCondition.EquationIdVector(EquationId, CurrentProcessInfo); if (SteadyLHS.size1() != 0) noalias(LHS_Contribution) += SteadyLHS; // apply slip condition mRotationTool.Rotate(LHS_Contribution,RHS_Contribution,rCurrentCondition.GetGeometry()); mRotationTool.ApplySlipCondition(LHS_Contribution,RHS_Contribution,rCurrentCondition.GetGeometry()); KRATOS_CATCH(""); } void CalculateRHSContribution( Element& rCurrentElement, LocalSystemVectorType& rRHS_Contribution, Element::EquationIdVectorType& rEquationId, const ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY; //TODO: This is very inefficient. Check why the RHS-only methods are not called. Matrix LHS_Contribution; CalculateSystemContributions( rCurrentElement, LHS_Contribution, rRHS_Contribution, rEquationId, rCurrentProcessInfo); KRATOS_CATCH(""); } void CalculateRHSContribution( Condition& rCurrentCondition, LocalSystemVectorType& rRHS_Contribution, Element::EquationIdVectorType& rEquationId, const ProcessInfo& rCurrentProcessInfo) override { KRATOS_TRY; //TODO: This is very inefficient. Check why the RHS-only methods are not called. Matrix LHS_Contribution; CalculateSystemContributions( rCurrentCondition, LHS_Contribution, rRHS_Contribution, rEquationId, rCurrentProcessInfo); KRATOS_CATCH(""); } void FinalizeNonLinIteration(ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb) override { if (mpTurbulenceModel) // If not null { mpTurbulenceModel->Execute(); } ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //if orthogonal subscales are computed if (CurrentProcessInfo[OSS_SWITCH] == 1.0) { KRATOS_INFO_IF("ResidualBasedSimpleSteadyScheme", rModelPart.GetCommunicator().MyPID() == 0) << "Computing OSS projections" << std::endl; const int number_of_nodes = rModelPart.NumberOfNodes(); #pragma omp parallel for for (int i = 0; i < number_of_nodes; i++) { ModelPart::NodeIterator it_node = rModelPart.NodesBegin() + i; noalias(it_node->FastGetSolutionStepValue(ADVPROJ)) = ZeroVector(3); it_node->FastGetSolutionStepValue(DIVPROJ) = 0.0; it_node->FastGetSolutionStepValue(NODAL_AREA) = 0.0; } const int number_of_elements = rModelPart.NumberOfElements(); array_1d<double, 3 > output; #pragma omp parallel for private(output) for (int i = 0; i < number_of_elements; i++) { ModelPart::ElementIterator it_elem = rModelPart.ElementsBegin() + i; it_elem->Calculate(ADVPROJ,output,CurrentProcessInfo); } rModelPart.GetCommunicator().AssembleCurrentData(NODAL_AREA); rModelPart.GetCommunicator().AssembleCurrentData(DIVPROJ); rModelPart.GetCommunicator().AssembleCurrentData(ADVPROJ); #pragma omp parallel for for (int i = 0; i < number_of_nodes; i++) { ModelPart::NodeIterator it_node = rModelPart.NodesBegin() + i; if (it_node->FastGetSolutionStepValue(NODAL_AREA) == 0.0) it_node->FastGetSolutionStepValue(NODAL_AREA) = 1.0; const double area_inverse = 1.0 / it_node->FastGetSolutionStepValue(NODAL_AREA); it_node->FastGetSolutionStepValue(ADVPROJ) *= area_inverse; it_node->FastGetSolutionStepValue(DIVPROJ) *= area_inverse; } } } void FinalizeSolutionStep(ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb) override { LocalSystemVectorType RHS_Contribution; LocalSystemMatrixType LHS_Contribution; const ProcessInfo& rCurrentProcessInfo = rModelPart.GetProcessInfo(); for (ModelPart::NodeIterator itNode = rModelPart.NodesBegin(); itNode != rModelPart.NodesEnd(); ++itNode) { itNode->FastGetSolutionStepValue(REACTION_X,0) = 0.0; itNode->FastGetSolutionStepValue(REACTION_Y,0) = 0.0; itNode->FastGetSolutionStepValue(REACTION_Z,0) = 0.0; } for (ModelPart::ElementsContainerType::ptr_iterator itElem = rModelPart.Elements().ptr_begin(); itElem != rModelPart.Elements().ptr_end(); ++itElem) { (*itElem)->InitializeNonLinearIteration(rCurrentProcessInfo); (*itElem)->CalculateLocalSystem(LHS_Contribution,RHS_Contribution,rCurrentProcessInfo); Matrix SteadyLHS; (*itElem)->CalculateLocalVelocityContribution(SteadyLHS,RHS_Contribution,rCurrentProcessInfo); GeometryType& rGeom = (*itElem)->GetGeometry(); unsigned int NumNodes = rGeom.PointsNumber(); unsigned int Dimension = rGeom.WorkingSpaceDimension(); unsigned int index = 0; for (unsigned int i = 0; i < NumNodes; i++) { rGeom[i].FastGetSolutionStepValue(REACTION_X,0) -= RHS_Contribution[index++]; rGeom[i].FastGetSolutionStepValue(REACTION_Y,0) -= RHS_Contribution[index++]; if (Dimension == 3) rGeom[i].FastGetSolutionStepValue(REACTION_Z,0) -= RHS_Contribution[index++]; index++; // skip pressure dof } } rModelPart.GetCommunicator().AssembleCurrentData(REACTION); Scheme<TSparseSpace, TDenseSpace>::FinalizeSolutionStep(rModelPart, rA, rDx, rb); } ///@} protected: ///@name Protected Operators ///@{ ///@} private: ///@name Member Variables ///@{ double mVelocityRelaxationFactor; double mPressureRelaxationFactor; CoordinateTransformationUtils<LocalSystemMatrixType,LocalSystemVectorType,double> mRotationTool; Process::Pointer mpTurbulenceModel; typename TSparseSpace::DofUpdaterPointerType mpDofUpdater = TSparseSpace::CreateDofUpdater(); ///@} }; ///@} } // namespace Kratos #endif /* KRATOS_RESIDUALBASED_SIMPLE_STEADY_SCHEME defined */
pocketfft_hdronly.h
/* This file is part of pocketfft. Copyright (C) 2010-2019 Max-Planck-Society Author: Martin Reinecke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef POCKETFFT_HDRONLY_H #define POCKETFFT_HDRONLY_H #ifndef __cplusplus #error This file is C++ and requires a C++ compiler. #endif #if !(__cplusplus >= 201103L || _MSVC_LANG+0L >= 201103L) #error This file requires at least C++11 support. #endif #ifndef POCKETFFT_CACHE_SIZE #define POCKETFFT_CACHE_SIZE 16 #endif #include <cmath> #include <cstring> #include <cstdlib> #include <stdexcept> #include <memory> #include <vector> #include <complex> #if POCKETFFT_CACHE_SIZE!=0 #include <array> #include <mutex> #endif #ifdef POCKETFFT_OPENMP #include <omp.h> #endif #if defined(__GNUC__) #define POCKETFFT_NOINLINE __attribute__((noinline)) #define POCKETFFT_RESTRICT __restrict__ #elif defined(_MSC_VER) #define POCKETFFT_NOINLINE __declspec(noinline) #define POCKETFFT_RESTRICT __restrict #else #define POCKETFFT_NOINLINE #define POCKETFFT_RESTRICT #endif namespace pocketfft { namespace detail { using namespace std; using shape_t = vector<size_t>; using stride_t = vector<ptrdiff_t>; constexpr bool FORWARD = true, BACKWARD = false; // only enable vector support for gcc>=5.0 and clang>=5.0 #ifndef POCKETFFT_NO_VECTORS #define POCKETFFT_NO_VECTORS #if defined(__INTEL_COMPILER) // do nothing. This is necessary because this compiler also sets __GNUC__. #elif defined(__clang__) #if __clang__>=5 #undef POCKETFFT_NO_VECTORS #endif #elif defined(__GNUC__) #if __GNUC__>=5 #undef POCKETFFT_NO_VECTORS #endif #endif #endif template<typename T> struct VLEN { static constexpr size_t val=1; }; #ifndef POCKETFFT_NO_VECTORS #if (defined(__AVX512F__)) template<> struct VLEN<float> { static constexpr size_t val=16; }; template<> struct VLEN<double> { static constexpr size_t val=8; }; #elif (defined(__AVX__)) template<> struct VLEN<float> { static constexpr size_t val=8; }; template<> struct VLEN<double> { static constexpr size_t val=4; }; #elif (defined(__SSE2__)) template<> struct VLEN<float> { static constexpr size_t val=4; }; template<> struct VLEN<double> { static constexpr size_t val=2; }; #elif (defined(__VSX__)) template<> struct VLEN<float> { static constexpr size_t val=4; }; template<> struct VLEN<double> { static constexpr size_t val=2; }; #else #define POCKETFFT_NO_VECTORS #endif #endif template<typename T> class arr { private: T *p; size_t sz; #if defined(POCKETFFT_NO_VECTORS) static T *ralloc(size_t num) { if (num==0) return nullptr; void *res = malloc(num*sizeof(T)); if (!res) throw bad_alloc(); return reinterpret_cast<T *>(res); } static void dealloc(T *ptr) { free(ptr); } #elif __cplusplus >= 201703L static T *ralloc(size_t num) { if (num==0) return nullptr; void *res = aligned_alloc(64,num*sizeof(T)); if (!res) throw bad_alloc(); return reinterpret_cast<T *>(res); } static void dealloc(T *ptr) { free(ptr); } #else // portable emulation static T *ralloc(size_t num) { if (num==0) return nullptr; void *ptr = malloc(num*sizeof(T)+64); if (!ptr) throw bad_alloc(); T *res = reinterpret_cast<T *> ((reinterpret_cast<size_t>(ptr) & ~(size_t(63))) + 64); (reinterpret_cast<void**>(res))[-1] = ptr; return res; } static void dealloc(T *ptr) { if (ptr) free((reinterpret_cast<void**>(ptr))[-1]); } #endif public: arr() : p(0), sz(0) {} arr(size_t n) : p(ralloc(n)), sz(n) {} arr(arr &&other) : p(other.p), sz(other.sz) { other.p=nullptr; other.sz=0; } ~arr() { dealloc(p); } void resize(size_t n) { if (n==sz) return; dealloc(p); p = ralloc(n); sz = n; } T &operator[](size_t idx) { return p[idx]; } const T &operator[](size_t idx) const { return p[idx]; } T *data() { return p; } const T *data() const { return p; } size_t size() const { return sz; } }; template<typename T> struct cmplx { T r, i; cmplx() {} cmplx(T r_, T i_) : r(r_), i(i_) {} void Set(T r_, T i_) { r=r_; i=i_; } void Set(T r_) { r=r_; i=T(0); } cmplx &operator+= (const cmplx &other) { r+=other.r; i+=other.i; return *this; } template<typename T2>cmplx &operator*= (T2 other) { r*=other; i*=other; return *this; } cmplx operator+ (const cmplx &other) const { return cmplx(r+other.r, i+other.i); } cmplx operator- (const cmplx &other) const { return cmplx(r-other.r, i-other.i); } template<typename T2> auto operator* (const T2 &other) const -> cmplx<decltype(r*other)> { return {r*other, i*other}; } template<typename T2> auto operator* (const cmplx<T2> &other) const -> cmplx<decltype(r+other.r)> { return {r*other.r-i*other.i, r*other.i + i*other.r}; } template<bool fwd, typename T2> auto special_mul (const cmplx<T2> &other) const -> cmplx<decltype(r+other.r)> { using Tres = cmplx<decltype(r+other.r)>; return fwd ? Tres(r*other.r+i*other.i, i*other.r-r*other.i) : Tres(r*other.r-i*other.i, r*other.i+i*other.r); } }; template<typename T> void PMC(cmplx<T> &a, cmplx<T> &b, const cmplx<T> &c, const cmplx<T> &d) { a = c+d; b = c-d; } template<typename T> cmplx<T> conj(const cmplx<T> &a) { return {a.r, -a.i}; } template<typename T> void ROT90(cmplx<T> &a) { auto tmp_=a.r; a.r=-a.i; a.i=tmp_; } template<bool fwd, typename T> void ROTX90(cmplx<T> &a) { auto tmp_= fwd ? -a.r : a.r; a.r = fwd ? a.i : -a.i; a.i=tmp_; } // // twiddle factor section // template<typename T> class sincos_2pibyn { private: using Thigh = typename conditional<(sizeof(T)>sizeof(double)), T, double>::type; arr<T> data; void my_sincosm1pi (Thigh a_, Thigh *POCKETFFT_RESTRICT res) { if (sizeof(Thigh)>sizeof(double)) // don't have the code for long double { constexpr Thigh pi = Thigh(3.141592653589793238462643383279502884197L); auto s = sin(pi*a_); res[1] = s; res[0] = (s*s)/(-sqrt((1-s)*(1+s))-1); return; } // adapted from https://stackoverflow.com/questions/42792939/ // CAUTION: this function only works for arguments in the range // [-0.25; 0.25]! double a = double(a_); double s = a * a; /* Approximate cos(pi*x)-1 for x in [-0.25,0.25] */ double r = -1.0369917389758117e-4; r = fma (r, s, 1.9294935641298806e-3); r = fma (r, s, -2.5806887942825395e-2); r = fma (r, s, 2.3533063028328211e-1); r = fma (r, s, -1.3352627688538006e+0); r = fma (r, s, 4.0587121264167623e+0); r = fma (r, s, -4.9348022005446790e+0); double c = r*s; /* Approximate sin(pi*x) for x in [-0.25,0.25] */ r = 4.6151442520157035e-4; r = fma (r, s, -7.3700183130883555e-3); r = fma (r, s, 8.2145868949323936e-2); r = fma (r, s, -5.9926452893214921e-1); r = fma (r, s, 2.5501640398732688e+0); r = fma (r, s, -5.1677127800499516e+0); s = s * a; r = r * s; s = fma (a, 3.1415926535897931e+0, r); res[0] = c; res[1] = s; } POCKETFFT_NOINLINE void calc_first_octant(size_t den, T * POCKETFFT_RESTRICT res) { size_t n = (den+4)>>3; if (n==0) return; res[0]=1.; res[1]=0.; if (n==1) return; size_t l1 = size_t(sqrt(n)); arr<Thigh> tmp(2*l1); for (size_t i=1; i<l1; ++i) { my_sincosm1pi(Thigh(2*i)/Thigh(den),&tmp[2*i]); res[2*i ] = T(tmp[2*i]+1); res[2*i+1] = T(tmp[2*i+1]); } size_t start=l1; while(start<n) { Thigh cs[2]; my_sincosm1pi((Thigh(2*start))/Thigh(den),cs); res[2*start] = T(cs[0]+1); res[2*start+1] = T(cs[1]); size_t end = l1; if (start+end>n) end = n-start; for (size_t i=1; i<end; ++i) { Thigh csx[2]={tmp[2*i], tmp[2*i+1]}; res[2*(start+i)] = T(((cs[0]*csx[0] - cs[1]*csx[1] + cs[0]) + csx[0]) + 1); res[2*(start+i)+1] = T((cs[0]*csx[1] + cs[1]*csx[0]) + cs[1] + csx[1]); } start += l1; } } void calc_first_quadrant(size_t n, T * POCKETFFT_RESTRICT res) { T * POCKETFFT_RESTRICT p = res+n; calc_first_octant(n<<1, p); size_t ndone=(n+2)>>2; size_t i=0, idx1=0, idx2=2*ndone-2; for (; i+1<ndone; i+=2, idx1+=2, idx2-=2) { res[idx1] = p[2*i ]; res[idx1+1] = p[2*i+1]; res[idx2] = p[2*i+3]; res[idx2+1] = p[2*i+2]; } if (i!=ndone) { res[idx1] = p[2*i]; res[idx1+1] = p[2*i+1]; } } void calc_first_half(size_t n, T * POCKETFFT_RESTRICT res) { int ndone=int(n+1)>>1; T * p = res+n-1; calc_first_octant(n<<2, p); int i4=0, in=int(n), i=0; for (; i4<=in-i4; ++i, i4+=4) // octant 0 { res[2*i] = p[2*i4]; res[2*i+1] = p[2*i4+1]; } for (; i4-in <= 0; ++i, i4+=4) // octant 1 { auto xm = in-i4; res[2*i] = p[2*xm+1]; res[2*i+1] = p[2*xm]; } for (; i4<=3*in-i4; ++i, i4+=4) // octant 2 { auto xm = i4-in; res[2*i] = -p[2*xm+1]; res[2*i+1] = p[2*xm]; } for (; i<ndone; ++i, i4+=4) // octant 3 { auto xm = 2*in-i4; res[2*i] = -p[2*xm]; res[2*i+1] = p[2*xm+1]; } } void fill_first_quadrant(size_t n, T * POCKETFFT_RESTRICT res) { constexpr T hsqt2 = T(0.707106781186547524400844362104849L); size_t quart = n>>2; if ((n&7)==0) res[quart] = res[quart+1] = hsqt2; for (size_t i=2, j=2*quart-2; i<quart; i+=2, j-=2) { res[j] = res[i+1]; res[j+1] = res[i]; } } POCKETFFT_NOINLINE void fill_first_half(size_t n, T * POCKETFFT_RESTRICT res) { size_t half = n>>1; if ((n&3)==0) for (size_t i=0; i<half; i+=2) { res[i+half] = -res[i+1]; res[i+half+1] = res[i]; } else for (size_t i=2, j=2*half-2; i<half; i+=2, j-=2) { res[j] = -res[i]; res[j+1] = res[i+1]; } } void fill_second_half(size_t n, T * POCKETFFT_RESTRICT res) { if ((n&1)==0) for (size_t i=0; i<n; ++i) res[i+n] = -res[i]; else for (size_t i=2, j=2*n-2; i<n; i+=2, j-=2) { res[j] = res[i]; res[j+1] = -res[i+1]; } } POCKETFFT_NOINLINE void sincos_2pibyn_half(size_t n, T * POCKETFFT_RESTRICT res) { if ((n&3)==0) { calc_first_octant(n, res); fill_first_quadrant(n, res); fill_first_half(n, res); } else if ((n&1)==0) { calc_first_quadrant(n, res); fill_first_half(n, res); } else calc_first_half(n, res); } public: POCKETFFT_NOINLINE sincos_2pibyn(size_t n, bool half) : data(2*n) { sincos_2pibyn_half(n, data.data()); if (!half) fill_second_half(n, data.data()); } T operator[](size_t idx) const { return data[idx]; } const T *rdata() const { return data; } const cmplx<T> *cdata() const { return reinterpret_cast<const cmplx<T> *>(data.data()); } }; struct util // hack to avoid duplicate symbols { static POCKETFFT_NOINLINE size_t largest_prime_factor (size_t n) { size_t res=1; while ((n&1)==0) { res=2; n>>=1; } for (size_t x=3; x*x<=n; x+=2) while ((n%x)==0) { res=x; n/=x; } if (n>1) res=n; return res; } static POCKETFFT_NOINLINE double cost_guess (size_t n) { constexpr double lfp=1.1; // penalty for non-hardcoded larger factors size_t ni=n; double result=0.; while ((n&1)==0) { result+=2; n>>=1; } for (size_t x=3; x*x<=n; x+=2) while ((n%x)==0) { result+= (x<=5) ? double(x) : lfp*double(x); // penalize larger prime factors n/=x; } if (n>1) result+=(n<=5) ? double(n) : lfp*double(n); return result*double(ni); } /* returns the smallest composite of 2, 3, 5, 7 and 11 which is >= n */ static POCKETFFT_NOINLINE size_t good_size(size_t n) { if (n<=12) return n; size_t bestfac=2*n; for (size_t f2=1; f2<bestfac; f2*=2) for (size_t f23=f2; f23<bestfac; f23*=3) for (size_t f235=f23; f235<bestfac; f235*=5) for (size_t f2357=f235; f2357<bestfac; f2357*=7) for (size_t f235711=f2357; f235711<bestfac; f235711*=11) if (f235711>=n) bestfac=f235711; return bestfac; } static size_t prod(const shape_t &shape) { size_t res=1; for (auto sz: shape) res*=sz; return res; } static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, bool inplace) { auto ndim = shape.size(); if (ndim<1) throw runtime_error("ndim must be >= 1"); if ((stride_in.size()!=ndim) || (stride_out.size()!=ndim)) throw runtime_error("stride dimension mismatch"); if (inplace && (stride_in!=stride_out)) throw runtime_error("stride mismatch"); } static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, bool inplace, const shape_t &axes) { sanity_check(shape, stride_in, stride_out, inplace); auto ndim = shape.size(); shape_t tmp(ndim,0); for (auto ax : axes) { if (ax>=ndim) throw runtime_error("bad axis number"); if (++tmp[ax]>1) throw runtime_error("axis specified repeatedly"); } } static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, bool inplace, size_t axis) { sanity_check(shape, stride_in, stride_out, inplace); if (axis>=shape.size()) throw runtime_error("bad axis number"); } #ifdef POCKETFFT_OPENMP static size_t nthreads() { return size_t(omp_get_num_threads()); } static size_t thread_num() { return size_t(omp_get_thread_num()); } static size_t thread_count (size_t nthreads, const shape_t &shape, size_t axis) { if (nthreads==1) return 1; if (prod(shape) < 20*shape[axis]) return 1; return (nthreads==0) ? size_t(omp_get_max_threads()) : nthreads; } #else static constexpr size_t nthreads() { return 1; } static constexpr size_t thread_num() { return 0; } #endif }; // // complex FFTPACK transforms // template<typename T0> class cfftp { private: struct fctdata { size_t fct; cmplx<T0> *tw, *tws; }; size_t length; arr<cmplx<T0>> mem; vector<fctdata> fact; void add_factor(size_t factor) { fact.push_back({factor, nullptr, nullptr}); } template<bool fwd, typename T> void pass2 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=2; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { CH(0,k,0) = CC(0,0,k)+CC(0,1,k); CH(0,k,1) = CC(0,0,k)-CC(0,1,k); } else for (size_t k=0; k<l1; ++k) { CH(0,k,0) = CC(0,0,k)+CC(0,1,k); CH(0,k,1) = CC(0,0,k)-CC(0,1,k); for (size_t i=1; i<ido; ++i) { CH(i,k,0) = CC(i,0,k)+CC(i,1,k); CH(i,k,1) = (CC(i,0,k)-CC(i,1,k)).template special_mul<fwd>(WA(0,i)); } } } #define POCKETFFT_PREP3(idx) \ T t0 = CC(idx,0,k), t1, t2; \ PMC (t1,t2,CC(idx,1,k),CC(idx,2,k)); \ CH(idx,k,0)=t0+t1; #define POCKETFFT_PARTSTEP3a(u1,u2,twr,twi) \ { \ T ca,cb; \ ca=t0+t1*twr; \ cb=t2*twi; ROT90(cb); \ PMC(CH(0,k,u1),CH(0,k,u2),ca,cb) ;\ } #define POCKETFFT_PARTSTEP3b(u1,u2,twr,twi) \ { \ T ca,cb,da,db; \ ca=t0+t1*twr; \ cb=t2*twi; ROT90(cb); \ PMC(da,db,ca,cb); \ CH(i,k,u1) = da.template special_mul<fwd>(WA(u1-1,i)); \ CH(i,k,u2) = db.template special_mul<fwd>(WA(u2-1,i)); \ } template<bool fwd, typename T> void pass3 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=3; constexpr T0 tw1r=-0.5, tw1i= (fwd ? -1: 1) * T0(0.8660254037844386467637231707529362L); auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { POCKETFFT_PREP3(0) POCKETFFT_PARTSTEP3a(1,2,tw1r,tw1i) } else for (size_t k=0; k<l1; ++k) { { POCKETFFT_PREP3(0) POCKETFFT_PARTSTEP3a(1,2,tw1r,tw1i) } for (size_t i=1; i<ido; ++i) { POCKETFFT_PREP3(i) POCKETFFT_PARTSTEP3b(1,2,tw1r,tw1i) } } } #undef POCKETFFT_PARTSTEP3b #undef POCKETFFT_PARTSTEP3a #undef POCKETFFT_PREP3 template<bool fwd, typename T> void pass4 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=4; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { T t1, t2, t3, t4; PMC(t2,t1,CC(0,0,k),CC(0,2,k)); PMC(t3,t4,CC(0,1,k),CC(0,3,k)); ROTX90<fwd>(t4); PMC(CH(0,k,0),CH(0,k,2),t2,t3); PMC(CH(0,k,1),CH(0,k,3),t1,t4); } else for (size_t k=0; k<l1; ++k) { { T t1, t2, t3, t4; PMC(t2,t1,CC(0,0,k),CC(0,2,k)); PMC(t3,t4,CC(0,1,k),CC(0,3,k)); ROTX90<fwd>(t4); PMC(CH(0,k,0),CH(0,k,2),t2,t3); PMC(CH(0,k,1),CH(0,k,3),t1,t4); } for (size_t i=1; i<ido; ++i) { T c2, c3, c4, t1, t2, t3, t4; T cc0=CC(i,0,k), cc1=CC(i,1,k),cc2=CC(i,2,k),cc3=CC(i,3,k); PMC(t2,t1,cc0,cc2); PMC(t3,t4,cc1,cc3); ROTX90<fwd>(t4); PMC(CH(i,k,0),c3,t2,t3); PMC(c2,c4,t1,t4); CH(i,k,1) = c2.template special_mul<fwd>(WA(0,i)); CH(i,k,2) = c3.template special_mul<fwd>(WA(1,i)); CH(i,k,3) = c4.template special_mul<fwd>(WA(2,i)); } } } #define POCKETFFT_PREP5(idx) \ T t0 = CC(idx,0,k), t1, t2, t3, t4; \ PMC (t1,t4,CC(idx,1,k),CC(idx,4,k)); \ PMC (t2,t3,CC(idx,2,k),CC(idx,3,k)); \ CH(idx,k,0).r=t0.r+t1.r+t2.r; \ CH(idx,k,0).i=t0.i+t1.i+t2.i; #define POCKETFFT_PARTSTEP5a(u1,u2,twar,twbr,twai,twbi) \ { \ T ca,cb; \ ca.r=t0.r+twar*t1.r+twbr*t2.r; \ ca.i=t0.i+twar*t1.i+twbr*t2.i; \ cb.i=twai*t4.r twbi*t3.r; \ cb.r=-(twai*t4.i twbi*t3.i); \ PMC(CH(0,k,u1),CH(0,k,u2),ca,cb); \ } #define POCKETFFT_PARTSTEP5b(u1,u2,twar,twbr,twai,twbi) \ { \ T ca,cb,da,db; \ ca.r=t0.r+twar*t1.r+twbr*t2.r; \ ca.i=t0.i+twar*t1.i+twbr*t2.i; \ cb.i=twai*t4.r twbi*t3.r; \ cb.r=-(twai*t4.i twbi*t3.i); \ PMC(da,db,ca,cb); \ CH(i,k,u1) = da.template special_mul<fwd>(WA(u1-1,i)); \ CH(i,k,u2) = db.template special_mul<fwd>(WA(u2-1,i)); \ } template<bool fwd, typename T> void pass5 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=5; constexpr T0 tw1r= T0(0.3090169943749474241022934171828191L), tw1i= (fwd ? -1: 1) * T0(0.9510565162951535721164393333793821L), tw2r= T0(-0.8090169943749474241022934171828191L), tw2i= (fwd ? -1: 1) * T0(0.5877852522924731291687059546390728L); auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { POCKETFFT_PREP5(0) POCKETFFT_PARTSTEP5a(1,4,tw1r,tw2r,+tw1i,+tw2i) POCKETFFT_PARTSTEP5a(2,3,tw2r,tw1r,+tw2i,-tw1i) } else for (size_t k=0; k<l1; ++k) { { POCKETFFT_PREP5(0) POCKETFFT_PARTSTEP5a(1,4,tw1r,tw2r,+tw1i,+tw2i) POCKETFFT_PARTSTEP5a(2,3,tw2r,tw1r,+tw2i,-tw1i) } for (size_t i=1; i<ido; ++i) { POCKETFFT_PREP5(i) POCKETFFT_PARTSTEP5b(1,4,tw1r,tw2r,+tw1i,+tw2i) POCKETFFT_PARTSTEP5b(2,3,tw2r,tw1r,+tw2i,-tw1i) } } } #undef POCKETFFT_PARTSTEP5b #undef POCKETFFT_PARTSTEP5a #undef POCKETFFT_PREP5 #define POCKETFFT_PREP7(idx) \ T t1 = CC(idx,0,k), t2, t3, t4, t5, t6, t7; \ PMC (t2,t7,CC(idx,1,k),CC(idx,6,k)); \ PMC (t3,t6,CC(idx,2,k),CC(idx,5,k)); \ PMC (t4,t5,CC(idx,3,k),CC(idx,4,k)); \ CH(idx,k,0).r=t1.r+t2.r+t3.r+t4.r; \ CH(idx,k,0).i=t1.i+t2.i+t3.i+t4.i; #define POCKETFFT_PARTSTEP7a0(u1,u2,x1,x2,x3,y1,y2,y3,out1,out2) \ { \ T ca,cb; \ ca.r=t1.r+x1*t2.r+x2*t3.r+x3*t4.r; \ ca.i=t1.i+x1*t2.i+x2*t3.i+x3*t4.i; \ cb.i=y1*t7.r y2*t6.r y3*t5.r; \ cb.r=-(y1*t7.i y2*t6.i y3*t5.i); \ PMC(out1,out2,ca,cb); \ } #define POCKETFFT_PARTSTEP7a(u1,u2,x1,x2,x3,y1,y2,y3) \ POCKETFFT_PARTSTEP7a0(u1,u2,x1,x2,x3,y1,y2,y3,CH(0,k,u1),CH(0,k,u2)) #define POCKETFFT_PARTSTEP7(u1,u2,x1,x2,x3,y1,y2,y3) \ { \ T da,db; \ POCKETFFT_PARTSTEP7a0(u1,u2,x1,x2,x3,y1,y2,y3,da,db) \ CH(i,k,u1) = da.template special_mul<fwd>(WA(u1-1,i)); \ CH(i,k,u2) = db.template special_mul<fwd>(WA(u2-1,i)); \ } template<bool fwd, typename T> void pass7(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=7; constexpr T0 tw1r= T0(0.6234898018587335305250048840042398L), tw1i= (fwd ? -1 : 1) * T0(0.7818314824680298087084445266740578L), tw2r= T0(-0.2225209339563144042889025644967948L), tw2i= (fwd ? -1 : 1) * T0(0.9749279121818236070181316829939312L), tw3r= T0(-0.9009688679024191262361023195074451L), tw3i= (fwd ? -1 : 1) * T0(0.433883739117558120475768332848359L); auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { POCKETFFT_PREP7(0) POCKETFFT_PARTSTEP7a(1,6,tw1r,tw2r,tw3r,+tw1i,+tw2i,+tw3i) POCKETFFT_PARTSTEP7a(2,5,tw2r,tw3r,tw1r,+tw2i,-tw3i,-tw1i) POCKETFFT_PARTSTEP7a(3,4,tw3r,tw1r,tw2r,+tw3i,-tw1i,+tw2i) } else for (size_t k=0; k<l1; ++k) { { POCKETFFT_PREP7(0) POCKETFFT_PARTSTEP7a(1,6,tw1r,tw2r,tw3r,+tw1i,+tw2i,+tw3i) POCKETFFT_PARTSTEP7a(2,5,tw2r,tw3r,tw1r,+tw2i,-tw3i,-tw1i) POCKETFFT_PARTSTEP7a(3,4,tw3r,tw1r,tw2r,+tw3i,-tw1i,+tw2i) } for (size_t i=1; i<ido; ++i) { POCKETFFT_PREP7(i) POCKETFFT_PARTSTEP7(1,6,tw1r,tw2r,tw3r,+tw1i,+tw2i,+tw3i) POCKETFFT_PARTSTEP7(2,5,tw2r,tw3r,tw1r,+tw2i,-tw3i,-tw1i) POCKETFFT_PARTSTEP7(3,4,tw3r,tw1r,tw2r,+tw3i,-tw1i,+tw2i) } } } #undef POCKETFFT_PARTSTEP7 #undef POCKETFFT_PARTSTEP7a0 #undef POCKETFFT_PARTSTEP7a #undef POCKETFFT_PREP7 template <bool fwd, typename T> void ROTX45(T &a) { constexpr T0 hsqt2=T0(0.707106781186547524400844362104849L); if (fwd) { auto tmp_=a.r; a.r=hsqt2*(a.r+a.i); a.i=hsqt2*(a.i-tmp_); } else { auto tmp_=a.r; a.r=hsqt2*(a.r-a.i); a.i=hsqt2*(a.i+tmp_); } } template <bool fwd, typename T> void ROTX135(T &a) { constexpr T0 hsqt2=T0(0.707106781186547524400844362104849L); if (fwd) { auto tmp_=a.r; a.r=hsqt2*(a.i-a.r); a.i=hsqt2*(-tmp_-a.i); } else { auto tmp_=a.r; a.r=hsqt2*(-a.r-a.i); a.i=hsqt2*(tmp_-a.i); } } template<typename T> inline void PMINPLACE(T &a, T &b) { T t = a; a.r+=b.r; a.i+=b.i; b.r=t.r-b.r; b.i=t.i-b.i; } template<bool fwd, typename T> void pass8 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=8; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { T a0, a1, a2, a3, a4, a5, a6, a7; PMC(a0,a4,CC(0,0,k),CC(0,4,k)); PMC(a1,a5,CC(0,1,k),CC(0,5,k)); PMC(a2,a6,CC(0,2,k),CC(0,6,k)); PMC(a3,a7,CC(0,3,k),CC(0,7,k)); ROTX90<fwd>(a6); ROTX90<fwd>(a7); PMINPLACE(a0,a2); PMINPLACE(a1,a3); PMINPLACE(a4,a6); PMINPLACE(a5,a7); ROTX45<fwd>(a5); ROTX90<fwd>(a3); ROTX135<fwd>(a7); PMC(CH(0,k,0),CH(0,k,4),a0,a1); PMC(CH(0,k,1),CH(0,k,5),a4,a5); PMC(CH(0,k,2),CH(0,k,6),a2,a3); PMC(CH(0,k,3),CH(0,k,7),a6,a7); } else for (size_t k=0; k<l1; ++k) { T a0, a1, a2, a3, a4, a5, a6, a7; PMC(a0,a4,CC(0,0,k),CC(0,4,k)); PMC(a1,a5,CC(0,1,k),CC(0,5,k)); PMC(a2,a6,CC(0,2,k),CC(0,6,k)); PMC(a3,a7,CC(0,3,k),CC(0,7,k)); ROTX90<fwd>(a6); ROTX90<fwd>(a7); PMINPLACE(a0,a2); PMINPLACE(a1,a3); PMINPLACE(a4,a6); PMINPLACE(a5,a7); ROTX45<fwd>(a5); ROTX90<fwd>(a3); ROTX135<fwd>(a7); PMC(CH(0,k,0),CH(0,k,4),a0,a1); PMC(CH(0,k,1),CH(0,k,5),a4,a5); PMC(CH(0,k,2),CH(0,k,6),a2,a3); PMC(CH(0,k,3),CH(0,k,7),a6,a7); for (size_t i=1; i<ido; ++i) { T a0, a1, a2, a3, a4, a5, a6, a7; PMC(a0,a4,CC(i,0,k),CC(i,4,k)); PMC(a1,a5,CC(i,1,k),CC(i,5,k)); PMC(a2,a6,CC(i,2,k),CC(i,6,k)); PMC(a3,a7,CC(i,3,k),CC(i,7,k)); ROTX90<fwd>(a6); ROTX90<fwd>(a7); PMINPLACE(a0,a2); PMINPLACE(a1,a3); PMINPLACE(a4,a6); PMINPLACE(a5,a7); ROTX45<fwd>(a5); ROTX90<fwd>(a3); ROTX135<fwd>(a7); PMINPLACE(a0,a1); PMINPLACE(a2,a3); PMINPLACE(a4,a5); PMINPLACE(a6,a7); CH(i,k,0) = a0; CH(i,k,1) = a4.template special_mul<fwd>(WA(0,i)); CH(i,k,2) = a2.template special_mul<fwd>(WA(1,i)); CH(i,k,3) = a6.template special_mul<fwd>(WA(2,i)); CH(i,k,4) = a1.template special_mul<fwd>(WA(3,i)); CH(i,k,5) = a5.template special_mul<fwd>(WA(4,i)); CH(i,k,6) = a3.template special_mul<fwd>(WA(5,i)); CH(i,k,7) = a7.template special_mul<fwd>(WA(6,i)); } } } #define POCKETFFT_PREP11(idx) \ T t1 = CC(idx,0,k), t2, t3, t4, t5, t6, t7, t8, t9, t10, t11; \ PMC (t2,t11,CC(idx,1,k),CC(idx,10,k)); \ PMC (t3,t10,CC(idx,2,k),CC(idx, 9,k)); \ PMC (t4,t9 ,CC(idx,3,k),CC(idx, 8,k)); \ PMC (t5,t8 ,CC(idx,4,k),CC(idx, 7,k)); \ PMC (t6,t7 ,CC(idx,5,k),CC(idx, 6,k)); \ CH(idx,k,0).r=t1.r+t2.r+t3.r+t4.r+t5.r+t6.r; \ CH(idx,k,0).i=t1.i+t2.i+t3.i+t4.i+t5.i+t6.i; #define POCKETFFT_PARTSTEP11a0(u1,u2,x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,out1,out2) \ { \ T ca = t1 + t2*x1 + t3*x2 + t4*x3 + t5*x4 +t6*x5, \ cb; \ cb.i=y1*t11.r y2*t10.r y3*t9.r y4*t8.r y5*t7.r; \ cb.r=-(y1*t11.i y2*t10.i y3*t9.i y4*t8.i y5*t7.i ); \ PMC(out1,out2,ca,cb); \ } #define POCKETFFT_PARTSTEP11a(u1,u2,x1,x2,x3,x4,x5,y1,y2,y3,y4,y5) \ POCKETFFT_PARTSTEP11a0(u1,u2,x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,CH(0,k,u1),CH(0,k,u2)) #define POCKETFFT_PARTSTEP11(u1,u2,x1,x2,x3,x4,x5,y1,y2,y3,y4,y5) \ { \ T da,db; \ POCKETFFT_PARTSTEP11a0(u1,u2,x1,x2,x3,x4,x5,y1,y2,y3,y4,y5,da,db) \ CH(i,k,u1) = da.template special_mul<fwd>(WA(u1-1,i)); \ CH(i,k,u2) = db.template special_mul<fwd>(WA(u2-1,i)); \ } template<bool fwd, typename T> void pass11 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=11; constexpr T0 tw1r= T0(0.8412535328311811688618116489193677L), tw1i= (fwd ? -1 : 1) * T0(0.5406408174555975821076359543186917L), tw2r= T0(0.4154150130018864255292741492296232L), tw2i= (fwd ? -1 : 1) * T0(0.9096319953545183714117153830790285L), tw3r= T0(-0.1423148382732851404437926686163697L), tw3i= (fwd ? -1 : 1) * T0(0.9898214418809327323760920377767188L), tw4r= T0(-0.6548607339452850640569250724662936L), tw4i= (fwd ? -1 : 1) * T0(0.7557495743542582837740358439723444L), tw5r= T0(-0.9594929736144973898903680570663277L), tw5i= (fwd ? -1 : 1) * T0(0.2817325568414296977114179153466169L); auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto WA = [wa, ido](size_t x, size_t i) { return wa[i-1+x*(ido-1)]; }; if (ido==1) for (size_t k=0; k<l1; ++k) { POCKETFFT_PREP11(0) POCKETFFT_PARTSTEP11a(1,10,tw1r,tw2r,tw3r,tw4r,tw5r,+tw1i,+tw2i,+tw3i,+tw4i,+tw5i) POCKETFFT_PARTSTEP11a(2, 9,tw2r,tw4r,tw5r,tw3r,tw1r,+tw2i,+tw4i,-tw5i,-tw3i,-tw1i) POCKETFFT_PARTSTEP11a(3, 8,tw3r,tw5r,tw2r,tw1r,tw4r,+tw3i,-tw5i,-tw2i,+tw1i,+tw4i) POCKETFFT_PARTSTEP11a(4, 7,tw4r,tw3r,tw1r,tw5r,tw2r,+tw4i,-tw3i,+tw1i,+tw5i,-tw2i) POCKETFFT_PARTSTEP11a(5, 6,tw5r,tw1r,tw4r,tw2r,tw3r,+tw5i,-tw1i,+tw4i,-tw2i,+tw3i) } else for (size_t k=0; k<l1; ++k) { { POCKETFFT_PREP11(0) POCKETFFT_PARTSTEP11a(1,10,tw1r,tw2r,tw3r,tw4r,tw5r,+tw1i,+tw2i,+tw3i,+tw4i,+tw5i) POCKETFFT_PARTSTEP11a(2, 9,tw2r,tw4r,tw5r,tw3r,tw1r,+tw2i,+tw4i,-tw5i,-tw3i,-tw1i) POCKETFFT_PARTSTEP11a(3, 8,tw3r,tw5r,tw2r,tw1r,tw4r,+tw3i,-tw5i,-tw2i,+tw1i,+tw4i) POCKETFFT_PARTSTEP11a(4, 7,tw4r,tw3r,tw1r,tw5r,tw2r,+tw4i,-tw3i,+tw1i,+tw5i,-tw2i) POCKETFFT_PARTSTEP11a(5, 6,tw5r,tw1r,tw4r,tw2r,tw3r,+tw5i,-tw1i,+tw4i,-tw2i,+tw3i) } for (size_t i=1; i<ido; ++i) { POCKETFFT_PREP11(i) POCKETFFT_PARTSTEP11(1,10,tw1r,tw2r,tw3r,tw4r,tw5r,+tw1i,+tw2i,+tw3i,+tw4i,+tw5i) POCKETFFT_PARTSTEP11(2, 9,tw2r,tw4r,tw5r,tw3r,tw1r,+tw2i,+tw4i,-tw5i,-tw3i,-tw1i) POCKETFFT_PARTSTEP11(3, 8,tw3r,tw5r,tw2r,tw1r,tw4r,+tw3i,-tw5i,-tw2i,+tw1i,+tw4i) POCKETFFT_PARTSTEP11(4, 7,tw4r,tw3r,tw1r,tw5r,tw2r,+tw4i,-tw3i,+tw1i,+tw5i,-tw2i) POCKETFFT_PARTSTEP11(5, 6,tw5r,tw1r,tw4r,tw2r,tw3r,+tw5i,-tw1i,+tw4i,-tw2i,+tw3i) } } } #undef PARTSTEP11 #undef PARTSTEP11a0 #undef PARTSTEP11a #undef POCKETFFT_PREP11 template<bool fwd, typename T> void passg (size_t ido, size_t ip, size_t l1, T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const cmplx<T0> * POCKETFFT_RESTRICT wa, const cmplx<T0> * POCKETFFT_RESTRICT csarr) { const size_t cdim=ip; size_t ipph = (ip+1)/2; size_t idl1 = ido*l1; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CX = [cc, ido, l1](size_t a, size_t b, size_t c) -> T& { return cc[a+ido*(b+l1*c)]; }; auto CX2 = [cc, idl1](size_t a, size_t b) -> T& { return cc[a+idl1*b]; }; auto CH2 = [ch, idl1](size_t a, size_t b) -> const T& { return ch[a+idl1*b]; }; arr<cmplx<T0>> wal(ip); wal[0] = cmplx<T0>(1., 0.); for (size_t i=1; i<ip; ++i) wal[i]=cmplx<T0>(csarr[i].r,fwd ? -csarr[i].i : csarr[i].i); for (size_t k=0; k<l1; ++k) for (size_t i=0; i<ido; ++i) CH(i,k,0) = CC(i,0,k); for (size_t j=1, jc=ip-1; j<ipph; ++j, --jc) for (size_t k=0; k<l1; ++k) for (size_t i=0; i<ido; ++i) PMC(CH(i,k,j),CH(i,k,jc),CC(i,j,k),CC(i,jc,k)); for (size_t k=0; k<l1; ++k) for (size_t i=0; i<ido; ++i) { T tmp = CH(i,k,0); for (size_t j=1; j<ipph; ++j) tmp+=CH(i,k,j); CX(i,k,0) = tmp; } for (size_t l=1, lc=ip-1; l<ipph; ++l, --lc) { // j=0 for (size_t ik=0; ik<idl1; ++ik) { CX2(ik,l).r = CH2(ik,0).r+wal[l].r*CH2(ik,1).r+wal[2*l].r*CH2(ik,2).r; CX2(ik,l).i = CH2(ik,0).i+wal[l].r*CH2(ik,1).i+wal[2*l].r*CH2(ik,2).i; CX2(ik,lc).r=-wal[l].i*CH2(ik,ip-1).i-wal[2*l].i*CH2(ik,ip-2).i; CX2(ik,lc).i=wal[l].i*CH2(ik,ip-1).r+wal[2*l].i*CH2(ik,ip-2).r; } size_t iwal=2*l; size_t j=3, jc=ip-3; for (; j<ipph-1; j+=2, jc-=2) { iwal+=l; if (iwal>ip) iwal-=ip; cmplx<T0> xwal=wal[iwal]; iwal+=l; if (iwal>ip) iwal-=ip; cmplx<T0> xwal2=wal[iwal]; for (size_t ik=0; ik<idl1; ++ik) { CX2(ik,l).r += CH2(ik,j).r*xwal.r+CH2(ik,j+1).r*xwal2.r; CX2(ik,l).i += CH2(ik,j).i*xwal.r+CH2(ik,j+1).i*xwal2.r; CX2(ik,lc).r -= CH2(ik,jc).i*xwal.i+CH2(ik,jc-1).i*xwal2.i; CX2(ik,lc).i += CH2(ik,jc).r*xwal.i+CH2(ik,jc-1).r*xwal2.i; } } for (; j<ipph; ++j, --jc) { iwal+=l; if (iwal>ip) iwal-=ip; cmplx<T0> xwal=wal[iwal]; for (size_t ik=0; ik<idl1; ++ik) { CX2(ik,l).r += CH2(ik,j).r*xwal.r; CX2(ik,l).i += CH2(ik,j).i*xwal.r; CX2(ik,lc).r -= CH2(ik,jc).i*xwal.i; CX2(ik,lc).i += CH2(ik,jc).r*xwal.i; } } } // shuffling and twiddling if (ido==1) for (size_t j=1, jc=ip-1; j<ipph; ++j, --jc) for (size_t ik=0; ik<idl1; ++ik) { T t1=CX2(ik,j), t2=CX2(ik,jc); PMC(CX2(ik,j),CX2(ik,jc),t1,t2); } else { for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) for (size_t k=0; k<l1; ++k) { T t1=CX(0,k,j), t2=CX(0,k,jc); PMC(CX(0,k,j),CX(0,k,jc),t1,t2); for (size_t i=1; i<ido; ++i) { T x1, x2; PMC(x1,x2,CX(i,k,j),CX(i,k,jc)); size_t idij=(j-1)*(ido-1)+i-1; CX(i,k,j) = x1.template special_mul<fwd>(wa[idij]); idij=(jc-1)*(ido-1)+i-1; CX(i,k,jc) = x2.template special_mul<fwd>(wa[idij]); } } } } template<bool fwd, typename T> void pass_all(T c[], T0 fct) { if (length==1) { c[0]*=fct; return; } size_t l1=1; arr<T> ch(length); T *p1=c, *p2=ch.data(); for(size_t k1=0; k1<fact.size(); k1++) { size_t ip=fact[k1].fct; size_t l2=ip*l1; size_t ido = length/l2; if (ip==4) pass4<fwd> (ido, l1, p1, p2, fact[k1].tw); else if(ip==8) pass8<fwd>(ido, l1, p1, p2, fact[k1].tw); else if(ip==2) pass2<fwd>(ido, l1, p1, p2, fact[k1].tw); else if(ip==3) pass3<fwd> (ido, l1, p1, p2, fact[k1].tw); else if(ip==5) pass5<fwd> (ido, l1, p1, p2, fact[k1].tw); else if(ip==7) pass7<fwd> (ido, l1, p1, p2, fact[k1].tw); else if(ip==11) pass11<fwd> (ido, l1, p1, p2, fact[k1].tw); else { passg<fwd>(ido, ip, l1, p1, p2, fact[k1].tw, fact[k1].tws); swap(p1,p2); } swap(p1,p2); l1=l2; } if (p1!=c) { if (fct!=1.) for (size_t i=0; i<length; ++i) c[i] = ch[i]*fct; else memcpy (c,p1,length*sizeof(T)); } else if (fct!=1.) for (size_t i=0; i<length; ++i) c[i] *= fct; } public: template<typename T> void forward(T c[], T0 fct) { pass_all<true>(c, fct); } template<typename T> void backward(T c[], T0 fct) { pass_all<false>(c, fct); } private: POCKETFFT_NOINLINE void factorize() { size_t len=length; while ((len&7)==0) { add_factor(8); len>>=3; } while ((len&3)==0) { add_factor(4); len>>=2; } if ((len&1)==0) { len>>=1; // factor 2 should be at the front of the factor list add_factor(2); swap(fact[0].fct, fact.back().fct); } for (size_t divisor=3; divisor*divisor<=len; divisor+=2) while ((len%divisor)==0) { add_factor(divisor); len/=divisor; } if (len>1) add_factor(len); } size_t twsize() const { size_t twsize=0, l1=1; for (size_t k=0; k<fact.size(); ++k) { size_t ip=fact[k].fct, ido= length/(l1*ip); twsize+=(ip-1)*(ido-1); if (ip>11) twsize+=ip; l1*=ip; } return twsize; } void comp_twiddle() { sincos_2pibyn<T0> twid(length, false); auto twiddle = twid.cdata(); size_t l1=1; size_t memofs=0; for (size_t k=0; k<fact.size(); ++k) { size_t ip=fact[k].fct, ido=length/(l1*ip); fact[k].tw=mem.data()+memofs; memofs+=(ip-1)*(ido-1); for (size_t j=1; j<ip; ++j) for (size_t i=1; i<ido; ++i) fact[k].tw[(j-1)*(ido-1)+i-1] = twiddle[j*l1*i]; if (ip>11) { fact[k].tws=mem.data()+memofs; memofs+=ip; for (size_t j=0; j<ip; ++j) fact[k].tws[j] = twiddle[j*l1*ido]; } l1*=ip; } } public: POCKETFFT_NOINLINE cfftp(size_t length_) : length(length_) { if (length==0) throw runtime_error("zero length FFT requested"); if (length==1) return; factorize(); mem.resize(twsize()); comp_twiddle(); } }; // // real-valued FFTPACK transforms // template<typename T0> class rfftp { private: struct fctdata { size_t fct; T0 *tw, *tws; }; size_t length; arr<T0> mem; vector<fctdata> fact; void add_factor(size_t factor) { fact.push_back({factor, nullptr, nullptr}); } template<typename T> inline void PM(T &a, T &b, T c, T d) { a=c+d; b=c-d; } /* (a+ib) = conj(c+id) * (e+if) */ template<typename T1, typename T2, typename T3> inline void MULPM (T1 &a, T1 &b, T2 c, T2 d, T3 e, T3 f) { a=c*e+d*f; b=c*f-d*e; } template<typename T> void radf2 (size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=2; auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,l1](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+l1*c)]; }; auto CH = [ch,ido,cdim](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+cdim*c)]; }; for (size_t k=0; k<l1; k++) PM (CH(0,0,k),CH(ido-1,1,k),CC(0,k,0),CC(0,k,1)); if ((ido&1)==0) for (size_t k=0; k<l1; k++) { CH( 0,1,k) = -CC(ido-1,k,1); CH(ido-1,0,k) = CC(ido-1,k,0); } if (ido<=2) return; for (size_t k=0; k<l1; k++) for (size_t i=2; i<ido; i+=2) { size_t ic=ido-i; T tr2, ti2; MULPM (tr2,ti2,WA(0,i-2),WA(0,i-1),CC(i-1,k,1),CC(i,k,1)); PM (CH(i-1,0,k),CH(ic-1,1,k),CC(i-1,k,0),tr2); PM (CH(i ,0,k),CH(ic ,1,k),ti2,CC(i ,k,0)); } } // a2=a+b; b2=i*(b-a); #define POCKETFFT_REARRANGE(rx, ix, ry, iy) \ {\ auto t1=rx+ry, t2=ry-rx, t3=ix+iy, t4=ix-iy; \ rx=t1; ix=t3; ry=t4; iy=t2; \ } template<typename T> void radf3(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=3; constexpr T0 taur=-0.5, taui=T0(0.8660254037844386467637231707529362L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,l1](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+l1*c)]; }; auto CH = [ch,ido,cdim](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+cdim*c)]; }; for (size_t k=0; k<l1; k++) { T cr2=CC(0,k,1)+CC(0,k,2); CH(0,0,k) = CC(0,k,0)+cr2; CH(0,2,k) = taui*(CC(0,k,2)-CC(0,k,1)); CH(ido-1,1,k) = CC(0,k,0)+taur*cr2; } if (ido==1) return; for (size_t k=0; k<l1; k++) for (size_t i=2; i<ido; i+=2) { size_t ic=ido-i; T di2, di3, dr2, dr3; MULPM (dr2,di2,WA(0,i-2),WA(0,i-1),CC(i-1,k,1),CC(i,k,1)); // d2=conj(WA0)*CC1 MULPM (dr3,di3,WA(1,i-2),WA(1,i-1),CC(i-1,k,2),CC(i,k,2)); // d3=conj(WA1)*CC2 POCKETFFT_REARRANGE(dr2, di2, dr3, di3); CH(i-1,0,k) = CC(i-1,k,0)+dr2; // c add CH(i ,0,k) = CC(i ,k,0)+di2; T tr2 = CC(i-1,k,0)+taur*dr2; // c add T ti2 = CC(i ,k,0)+taur*di2; T tr3 = taui*dr3; // t3 = taui*i*(d3-d2)? T ti3 = taui*di3; PM(CH(i-1,2,k),CH(ic-1,1,k),tr2,tr3); // PM(i) = t2+t3 PM(CH(i ,2,k),CH(ic ,1,k),ti3,ti2); // PM(ic) = conj(t2-t3) } } template<typename T> void radf4(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=4; constexpr T0 hsqt2=T0(0.707106781186547524400844362104849L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,l1](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+l1*c)]; }; auto CH = [ch,ido,cdim](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+cdim*c)]; }; for (size_t k=0; k<l1; k++) { T tr1,tr2; PM (tr1,CH(0,2,k),CC(0,k,3),CC(0,k,1)); PM (tr2,CH(ido-1,1,k),CC(0,k,0),CC(0,k,2)); PM (CH(0,0,k),CH(ido-1,3,k),tr2,tr1); } if ((ido&1)==0) for (size_t k=0; k<l1; k++) { T ti1=-hsqt2*(CC(ido-1,k,1)+CC(ido-1,k,3)); T tr1= hsqt2*(CC(ido-1,k,1)-CC(ido-1,k,3)); PM (CH(ido-1,0,k),CH(ido-1,2,k),CC(ido-1,k,0),tr1); PM (CH( 0,3,k),CH( 0,1,k),ti1,CC(ido-1,k,2)); } if (ido<=2) return; for (size_t k=0; k<l1; k++) for (size_t i=2; i<ido; i+=2) { size_t ic=ido-i; T ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; MULPM(cr2,ci2,WA(0,i-2),WA(0,i-1),CC(i-1,k,1),CC(i,k,1)); MULPM(cr3,ci3,WA(1,i-2),WA(1,i-1),CC(i-1,k,2),CC(i,k,2)); MULPM(cr4,ci4,WA(2,i-2),WA(2,i-1),CC(i-1,k,3),CC(i,k,3)); PM(tr1,tr4,cr4,cr2); PM(ti1,ti4,ci2,ci4); PM(tr2,tr3,CC(i-1,k,0),cr3); PM(ti2,ti3,CC(i ,k,0),ci3); PM(CH(i-1,0,k),CH(ic-1,3,k),tr2,tr1); PM(CH(i ,0,k),CH(ic ,3,k),ti1,ti2); PM(CH(i-1,2,k),CH(ic-1,1,k),tr3,ti4); PM(CH(i ,2,k),CH(ic ,1,k),tr4,ti3); } } template<typename T> void radf5(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=5; constexpr T0 tr11= T0(0.3090169943749474241022934171828191L), ti11= T0(0.9510565162951535721164393333793821L), tr12= T0(-0.8090169943749474241022934171828191L), ti12= T0(0.5877852522924731291687059546390728L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,l1](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+l1*c)]; }; auto CH = [ch,ido,cdim](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+cdim*c)]; }; for (size_t k=0; k<l1; k++) { T cr2, cr3, ci4, ci5; PM (cr2,ci5,CC(0,k,4),CC(0,k,1)); PM (cr3,ci4,CC(0,k,3),CC(0,k,2)); CH(0,0,k)=CC(0,k,0)+cr2+cr3; CH(ido-1,1,k)=CC(0,k,0)+tr11*cr2+tr12*cr3; CH(0,2,k)=ti11*ci5+ti12*ci4; CH(ido-1,3,k)=CC(0,k,0)+tr12*cr2+tr11*cr3; CH(0,4,k)=ti12*ci5-ti11*ci4; } if (ido==1) return; for (size_t k=0; k<l1;++k) for (size_t i=2, ic=ido-2; i<ido; i+=2, ic-=2) { T di2, di3, di4, di5, dr2, dr3, dr4, dr5; MULPM (dr2,di2,WA(0,i-2),WA(0,i-1),CC(i-1,k,1),CC(i,k,1)); MULPM (dr3,di3,WA(1,i-2),WA(1,i-1),CC(i-1,k,2),CC(i,k,2)); MULPM (dr4,di4,WA(2,i-2),WA(2,i-1),CC(i-1,k,3),CC(i,k,3)); MULPM (dr5,di5,WA(3,i-2),WA(3,i-1),CC(i-1,k,4),CC(i,k,4)); POCKETFFT_REARRANGE(dr2, di2, dr5, di5); POCKETFFT_REARRANGE(dr3, di3, dr4, di4); CH(i-1,0,k)=CC(i-1,k,0)+dr2+dr3; CH(i ,0,k)=CC(i ,k,0)+di2+di3; T tr2=CC(i-1,k,0)+tr11*dr2+tr12*dr3; T ti2=CC(i ,k,0)+tr11*di2+tr12*di3; T tr3=CC(i-1,k,0)+tr12*dr2+tr11*dr3; T ti3=CC(i ,k,0)+tr12*di2+tr11*di3; T tr5 = ti11*dr5 + ti12*dr4; T ti5 = ti11*di5 + ti12*di4; T tr4 = ti12*dr5 - ti11*dr4; T ti4 = ti12*di5 - ti11*di4; PM(CH(i-1,2,k),CH(ic-1,1,k),tr2,tr5); PM(CH(i ,2,k),CH(ic ,1,k),ti5,ti2); PM(CH(i-1,4,k),CH(ic-1,3,k),tr3,tr4); PM(CH(i ,4,k),CH(ic ,3,k),ti4,ti3); } } #undef POCKETFFT_REARRANGE template<typename T> void radfg(size_t ido, size_t ip, size_t l1, T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa, const T0 * POCKETFFT_RESTRICT csarr) { const size_t cdim=ip; size_t ipph=(ip+1)/2; size_t idl1 = ido*l1; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> const T& { return ch[a+ido*(b+l1*c)]; }; auto C1 = [cc,ido,l1] (size_t a, size_t b, size_t c) -> T& { return cc[a+ido*(b+l1*c)]; }; auto C2 = [cc,idl1] (size_t a, size_t b) -> T& { return cc[a+idl1*b]; }; auto CH2 = [ch,idl1] (size_t a, size_t b) -> T& { return ch[a+idl1*b]; }; if (ido>1) { for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 114 { size_t is=(j-1)*(ido-1), is2=(jc-1)*(ido-1); for (size_t k=0; k<l1; ++k) // 113 { size_t idij=is; size_t idij2=is2; for (size_t i=1; i<=ido-2; i+=2) // 112 { T t1=C1(i,k,j ), t2=C1(i+1,k,j ), t3=C1(i,k,jc), t4=C1(i+1,k,jc); T x1=wa[idij]*t1 + wa[idij+1]*t2, x2=wa[idij]*t2 - wa[idij+1]*t1, x3=wa[idij2]*t3 + wa[idij2+1]*t4, x4=wa[idij2]*t4 - wa[idij2+1]*t3; C1(i ,k,j ) = x1+x3; C1(i ,k,jc) = x2-x4; C1(i+1,k,j ) = x2+x4; C1(i+1,k,jc) = x3-x1; idij+=2; idij2+=2; } } } } for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 123 for (size_t k=0; k<l1; ++k) // 122 { T t1=C1(0,k,j), t2=C1(0,k,jc); C1(0,k,j ) = t1+t2; C1(0,k,jc) = t2-t1; } //everything in C //memset(ch,0,ip*l1*ido*sizeof(double)); for (size_t l=1,lc=ip-1; l<ipph; ++l,--lc) // 127 { for (size_t ik=0; ik<idl1; ++ik) // 124 { CH2(ik,l ) = C2(ik,0)+csarr[2*l]*C2(ik,1)+csarr[4*l]*C2(ik,2); CH2(ik,lc) = csarr[2*l+1]*C2(ik,ip-1)+csarr[4*l+1]*C2(ik,ip-2); } size_t iang = 2*l; size_t j=3, jc=ip-3; for (; j<ipph-3; j+=4,jc-=4) // 126 { iang+=l; if (iang>=ip) iang-=ip; T0 ar1=csarr[2*iang], ai1=csarr[2*iang+1]; iang+=l; if (iang>=ip) iang-=ip; T0 ar2=csarr[2*iang], ai2=csarr[2*iang+1]; iang+=l; if (iang>=ip) iang-=ip; T0 ar3=csarr[2*iang], ai3=csarr[2*iang+1]; iang+=l; if (iang>=ip) iang-=ip; T0 ar4=csarr[2*iang], ai4=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) // 125 { CH2(ik,l ) += ar1*C2(ik,j )+ar2*C2(ik,j +1) +ar3*C2(ik,j +2)+ar4*C2(ik,j +3); CH2(ik,lc) += ai1*C2(ik,jc)+ai2*C2(ik,jc-1) +ai3*C2(ik,jc-2)+ai4*C2(ik,jc-3); } } for (; j<ipph-1; j+=2,jc-=2) // 126 { iang+=l; if (iang>=ip) iang-=ip; T0 ar1=csarr[2*iang], ai1=csarr[2*iang+1]; iang+=l; if (iang>=ip) iang-=ip; T0 ar2=csarr[2*iang], ai2=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) // 125 { CH2(ik,l ) += ar1*C2(ik,j )+ar2*C2(ik,j +1); CH2(ik,lc) += ai1*C2(ik,jc)+ai2*C2(ik,jc-1); } } for (; j<ipph; ++j,--jc) // 126 { iang+=l; if (iang>=ip) iang-=ip; T0 ar=csarr[2*iang], ai=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) // 125 { CH2(ik,l ) += ar*C2(ik,j ); CH2(ik,lc) += ai*C2(ik,jc); } } } for (size_t ik=0; ik<idl1; ++ik) // 101 CH2(ik,0) = C2(ik,0); for (size_t j=1; j<ipph; ++j) // 129 for (size_t ik=0; ik<idl1; ++ik) // 128 CH2(ik,0) += C2(ik,j); // everything in CH at this point! //memset(cc,0,ip*l1*ido*sizeof(double)); for (size_t k=0; k<l1; ++k) // 131 for (size_t i=0; i<ido; ++i) // 130 CC(i,0,k) = CH(i,k,0); for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 137 { size_t j2=2*j-1; for (size_t k=0; k<l1; ++k) // 136 { CC(ido-1,j2,k) = CH(0,k,j); CC(0,j2+1,k) = CH(0,k,jc); } } if (ido==1) return; for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 140 { size_t j2=2*j-1; for(size_t k=0; k<l1; ++k) // 139 for(size_t i=1, ic=ido-i-2; i<=ido-2; i+=2, ic-=2) // 138 { CC(i ,j2+1,k) = CH(i ,k,j )+CH(i ,k,jc); CC(ic ,j2 ,k) = CH(i ,k,j )-CH(i ,k,jc); CC(i+1 ,j2+1,k) = CH(i+1,k,j )+CH(i+1,k,jc); CC(ic+1,j2 ,k) = CH(i+1,k,jc)-CH(i+1,k,j ); } } } template<typename T> void radb2(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=2; auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; for (size_t k=0; k<l1; k++) PM (CH(0,k,0),CH(0,k,1),CC(0,0,k),CC(ido-1,1,k)); if ((ido&1)==0) for (size_t k=0; k<l1; k++) { CH(ido-1,k,0) = 2*CC(ido-1,0,k); CH(ido-1,k,1) =-2*CC(0 ,1,k); } if (ido<=2) return; for (size_t k=0; k<l1;++k) for (size_t i=2; i<ido; i+=2) { size_t ic=ido-i; T ti2, tr2; PM (CH(i-1,k,0),tr2,CC(i-1,0,k),CC(ic-1,1,k)); PM (ti2,CH(i ,k,0),CC(i ,0,k),CC(ic ,1,k)); MULPM (CH(i,k,1),CH(i-1,k,1),WA(0,i-2),WA(0,i-1),ti2,tr2); } } template<typename T> void radb3(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=3; constexpr T0 taur=-0.5, taui=T0(0.8660254037844386467637231707529362L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; for (size_t k=0; k<l1; k++) { T tr2=2*CC(ido-1,1,k); T cr2=CC(0,0,k)+taur*tr2; CH(0,k,0)=CC(0,0,k)+tr2; T ci3=2*taui*CC(0,2,k); PM (CH(0,k,2),CH(0,k,1),cr2,ci3); } if (ido==1) return; for (size_t k=0; k<l1; k++) for (size_t i=2, ic=ido-2; i<ido; i+=2, ic-=2) { T tr2=CC(i-1,2,k)+CC(ic-1,1,k); // t2=CC(I) + conj(CC(ic)) T ti2=CC(i ,2,k)-CC(ic ,1,k); T cr2=CC(i-1,0,k)+taur*tr2; // c2=CC +taur*t2 T ci2=CC(i ,0,k)+taur*ti2; CH(i-1,k,0)=CC(i-1,0,k)+tr2; // CH=CC+t2 CH(i ,k,0)=CC(i ,0,k)+ti2; T cr3=taui*(CC(i-1,2,k)-CC(ic-1,1,k));// c3=taui*(CC(i)-conj(CC(ic))) T ci3=taui*(CC(i ,2,k)+CC(ic ,1,k)); T di2, di3, dr2, dr3; PM(dr3,dr2,cr2,ci3); // d2= (cr2-ci3, ci2+cr3) = c2+i*c3 PM(di2,di3,ci2,cr3); // d3= (cr2+ci3, ci2-cr3) = c2-i*c3 MULPM(CH(i,k,1),CH(i-1,k,1),WA(0,i-2),WA(0,i-1),di2,dr2); // ch = WA*d2 MULPM(CH(i,k,2),CH(i-1,k,2),WA(1,i-2),WA(1,i-1),di3,dr3); } } template<typename T> void radb4(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=4; constexpr T0 sqrt2=T0(1.414213562373095048801688724209698L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; for (size_t k=0; k<l1; k++) { T tr1, tr2; PM (tr2,tr1,CC(0,0,k),CC(ido-1,3,k)); T tr3=2*CC(ido-1,1,k); T tr4=2*CC(0,2,k); PM (CH(0,k,0),CH(0,k,2),tr2,tr3); PM (CH(0,k,3),CH(0,k,1),tr1,tr4); } if ((ido&1)==0) for (size_t k=0; k<l1; k++) { T tr1,tr2,ti1,ti2; PM (ti1,ti2,CC(0 ,3,k),CC(0 ,1,k)); PM (tr2,tr1,CC(ido-1,0,k),CC(ido-1,2,k)); CH(ido-1,k,0)=tr2+tr2; CH(ido-1,k,1)=sqrt2*(tr1-ti1); CH(ido-1,k,2)=ti2+ti2; CH(ido-1,k,3)=-sqrt2*(tr1+ti1); } if (ido<=2) return; for (size_t k=0; k<l1;++k) for (size_t i=2; i<ido; i+=2) { T ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4; size_t ic=ido-i; PM (tr2,tr1,CC(i-1,0,k),CC(ic-1,3,k)); PM (ti1,ti2,CC(i ,0,k),CC(ic ,3,k)); PM (tr4,ti3,CC(i ,2,k),CC(ic ,1,k)); PM (tr3,ti4,CC(i-1,2,k),CC(ic-1,1,k)); PM (CH(i-1,k,0),cr3,tr2,tr3); PM (CH(i ,k,0),ci3,ti2,ti3); PM (cr4,cr2,tr1,tr4); PM (ci2,ci4,ti1,ti4); MULPM (CH(i,k,1),CH(i-1,k,1),WA(0,i-2),WA(0,i-1),ci2,cr2); MULPM (CH(i,k,2),CH(i-1,k,2),WA(1,i-2),WA(1,i-1),ci3,cr3); MULPM (CH(i,k,3),CH(i-1,k,3),WA(2,i-2),WA(2,i-1),ci4,cr4); } } template<typename T> void radb5(size_t ido, size_t l1, const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa) { constexpr size_t cdim=5; constexpr T0 tr11= T0(0.3090169943749474241022934171828191L), ti11= T0(0.9510565162951535721164393333793821L), tr12= T0(-0.8090169943749474241022934171828191L), ti12= T0(0.5877852522924731291687059546390728L); auto WA = [wa,ido](size_t x, size_t i) { return wa[i+x*(ido-1)]; }; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; for (size_t k=0; k<l1; k++) { T ti5=CC(0,2,k)+CC(0,2,k); T ti4=CC(0,4,k)+CC(0,4,k); T tr2=CC(ido-1,1,k)+CC(ido-1,1,k); T tr3=CC(ido-1,3,k)+CC(ido-1,3,k); CH(0,k,0)=CC(0,0,k)+tr2+tr3; T cr2=CC(0,0,k)+tr11*tr2+tr12*tr3; T cr3=CC(0,0,k)+tr12*tr2+tr11*tr3; T ci4, ci5; MULPM(ci5,ci4,ti5,ti4,ti11,ti12); PM(CH(0,k,4),CH(0,k,1),cr2,ci5); PM(CH(0,k,3),CH(0,k,2),cr3,ci4); } if (ido==1) return; for (size_t k=0; k<l1;++k) for (size_t i=2, ic=ido-2; i<ido; i+=2, ic-=2) { T tr2, tr3, tr4, tr5, ti2, ti3, ti4, ti5; PM(tr2,tr5,CC(i-1,2,k),CC(ic-1,1,k)); PM(ti5,ti2,CC(i ,2,k),CC(ic ,1,k)); PM(tr3,tr4,CC(i-1,4,k),CC(ic-1,3,k)); PM(ti4,ti3,CC(i ,4,k),CC(ic ,3,k)); CH(i-1,k,0)=CC(i-1,0,k)+tr2+tr3; CH(i ,k,0)=CC(i ,0,k)+ti2+ti3; T cr2=CC(i-1,0,k)+tr11*tr2+tr12*tr3; T ci2=CC(i ,0,k)+tr11*ti2+tr12*ti3; T cr3=CC(i-1,0,k)+tr12*tr2+tr11*tr3; T ci3=CC(i ,0,k)+tr12*ti2+tr11*ti3; T ci4, ci5, cr5, cr4; MULPM(cr5,cr4,tr5,tr4,ti11,ti12); MULPM(ci5,ci4,ti5,ti4,ti11,ti12); T dr2, dr3, dr4, dr5, di2, di3, di4, di5; PM(dr4,dr3,cr3,ci4); PM(di3,di4,ci3,cr4); PM(dr5,dr2,cr2,ci5); PM(di2,di5,ci2,cr5); MULPM(CH(i,k,1),CH(i-1,k,1),WA(0,i-2),WA(0,i-1),di2,dr2); MULPM(CH(i,k,2),CH(i-1,k,2),WA(1,i-2),WA(1,i-1),di3,dr3); MULPM(CH(i,k,3),CH(i-1,k,3),WA(2,i-2),WA(2,i-1),di4,dr4); MULPM(CH(i,k,4),CH(i-1,k,4),WA(3,i-2),WA(3,i-1),di5,dr5); } } template<typename T> void radbg(size_t ido, size_t ip, size_t l1, T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch, const T0 * POCKETFFT_RESTRICT wa, const T0 * POCKETFFT_RESTRICT csarr) { const size_t cdim=ip; size_t ipph=(ip+1)/ 2; size_t idl1 = ido*l1; auto CC = [cc,ido,cdim](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+cdim*c)]; }; auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T& { return ch[a+ido*(b+l1*c)]; }; auto C1 = [cc,ido,l1](size_t a, size_t b, size_t c) -> const T& { return cc[a+ido*(b+l1*c)]; }; auto C2 = [cc,idl1](size_t a, size_t b) -> T& { return cc[a+idl1*b]; }; auto CH2 = [ch,idl1](size_t a, size_t b) -> T& { return ch[a+idl1*b]; }; for (size_t k=0; k<l1; ++k) // 102 for (size_t i=0; i<ido; ++i) // 101 CH(i,k,0) = CC(i,0,k); for (size_t j=1, jc=ip-1; j<ipph; ++j, --jc) // 108 { size_t j2=2*j-1; for (size_t k=0; k<l1; ++k) { CH(0,k,j ) = 2*CC(ido-1,j2,k); CH(0,k,jc) = 2*CC(0,j2+1,k); } } if (ido!=1) { for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 111 { size_t j2=2*j-1; for (size_t k=0; k<l1; ++k) for (size_t i=1, ic=ido-i-2; i<=ido-2; i+=2, ic-=2) // 109 { CH(i ,k,j ) = CC(i ,j2+1,k)+CC(ic ,j2,k); CH(i ,k,jc) = CC(i ,j2+1,k)-CC(ic ,j2,k); CH(i+1,k,j ) = CC(i+1,j2+1,k)-CC(ic+1,j2,k); CH(i+1,k,jc) = CC(i+1,j2+1,k)+CC(ic+1,j2,k); } } } for (size_t l=1,lc=ip-1; l<ipph; ++l,--lc) { for (size_t ik=0; ik<idl1; ++ik) { C2(ik,l ) = CH2(ik,0)+csarr[2*l]*CH2(ik,1)+csarr[4*l]*CH2(ik,2); C2(ik,lc) = csarr[2*l+1]*CH2(ik,ip-1)+csarr[4*l+1]*CH2(ik,ip-2); } size_t iang=2*l; size_t j=3,jc=ip-3; for(; j<ipph-3; j+=4,jc-=4) { iang+=l; if(iang>ip) iang-=ip; T0 ar1=csarr[2*iang], ai1=csarr[2*iang+1]; iang+=l; if(iang>ip) iang-=ip; T0 ar2=csarr[2*iang], ai2=csarr[2*iang+1]; iang+=l; if(iang>ip) iang-=ip; T0 ar3=csarr[2*iang], ai3=csarr[2*iang+1]; iang+=l; if(iang>ip) iang-=ip; T0 ar4=csarr[2*iang], ai4=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) { C2(ik,l ) += ar1*CH2(ik,j )+ar2*CH2(ik,j +1) +ar3*CH2(ik,j +2)+ar4*CH2(ik,j +3); C2(ik,lc) += ai1*CH2(ik,jc)+ai2*CH2(ik,jc-1) +ai3*CH2(ik,jc-2)+ai4*CH2(ik,jc-3); } } for(; j<ipph-1; j+=2,jc-=2) { iang+=l; if(iang>ip) iang-=ip; T0 ar1=csarr[2*iang], ai1=csarr[2*iang+1]; iang+=l; if(iang>ip) iang-=ip; T0 ar2=csarr[2*iang], ai2=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) { C2(ik,l ) += ar1*CH2(ik,j )+ar2*CH2(ik,j +1); C2(ik,lc) += ai1*CH2(ik,jc)+ai2*CH2(ik,jc-1); } } for(; j<ipph; ++j,--jc) { iang+=l; if(iang>ip) iang-=ip; T0 war=csarr[2*iang], wai=csarr[2*iang+1]; for (size_t ik=0; ik<idl1; ++ik) { C2(ik,l ) += war*CH2(ik,j ); C2(ik,lc) += wai*CH2(ik,jc); } } } for (size_t j=1; j<ipph; ++j) for (size_t ik=0; ik<idl1; ++ik) CH2(ik,0) += CH2(ik,j); for (size_t j=1, jc=ip-1; j<ipph; ++j,--jc) // 124 for (size_t k=0; k<l1; ++k) { CH(0,k,j ) = C1(0,k,j)-C1(0,k,jc); CH(0,k,jc) = C1(0,k,j)+C1(0,k,jc); } if (ido==1) return; for (size_t j=1, jc=ip-1; j<ipph; ++j, --jc) // 127 for (size_t k=0; k<l1; ++k) for (size_t i=1; i<=ido-2; i+=2) { CH(i ,k,j ) = C1(i ,k,j)-C1(i+1,k,jc); CH(i ,k,jc) = C1(i ,k,j)+C1(i+1,k,jc); CH(i+1,k,j ) = C1(i+1,k,j)+C1(i ,k,jc); CH(i+1,k,jc) = C1(i+1,k,j)-C1(i ,k,jc); } // All in CH for (size_t j=1; j<ip; ++j) { size_t is = (j-1)*(ido-1); for (size_t k=0; k<l1; ++k) { size_t idij = is; for (size_t i=1; i<=ido-2; i+=2) { T t1=CH(i,k,j), t2=CH(i+1,k,j); CH(i ,k,j) = wa[idij]*t1-wa[idij+1]*t2; CH(i+1,k,j) = wa[idij]*t2+wa[idij+1]*t1; idij+=2; } } } } template<typename T> void copy_and_norm(T *c, T *p1, size_t n, T0 fct) { if (p1!=c) { if (fct!=1.) for (size_t i=0; i<n; ++i) c[i] = fct*p1[i]; else memcpy (c,p1,n*sizeof(T)); } else if (fct!=1.) for (size_t i=0; i<n; ++i) c[i] *= fct; } public: template<typename T> void forward(T c[], T0 fct) { if (length==1) { c[0]*=fct; return; } size_t n=length; size_t l1=n, nf=fact.size(); arr<T> ch(n); T *p1=c, *p2=ch.data(); for(size_t k1=0; k1<nf;++k1) { size_t k=nf-k1-1; size_t ip=fact[k].fct; size_t ido=n / l1; l1 /= ip; if(ip==4) radf4(ido, l1, p1, p2, fact[k].tw); else if(ip==2) radf2(ido, l1, p1, p2, fact[k].tw); else if(ip==3) radf3(ido, l1, p1, p2, fact[k].tw); else if(ip==5) radf5(ido, l1, p1, p2, fact[k].tw); else { radfg(ido, ip, l1, p1, p2, fact[k].tw, fact[k].tws); swap (p1,p2); } swap (p1,p2); } copy_and_norm(c,p1,n,fct); } template<typename T> void backward(T c[], T0 fct) { if (length==1) { c[0]*=fct; return; } size_t n=length; size_t l1=1, nf=fact.size(); arr<T> ch(n); T *p1=c, *p2=ch.data(); for(size_t k=0; k<nf; k++) { size_t ip = fact[k].fct, ido= n/(ip*l1); if(ip==4) radb4(ido, l1, p1, p2, fact[k].tw); else if(ip==2) radb2(ido, l1, p1, p2, fact[k].tw); else if(ip==3) radb3(ido, l1, p1, p2, fact[k].tw); else if(ip==5) radb5(ido, l1, p1, p2, fact[k].tw); else radbg(ido, ip, l1, p1, p2, fact[k].tw, fact[k].tws); swap (p1,p2); l1*=ip; } copy_and_norm(c,p1,n,fct); } private: void factorize() { size_t len=length; while ((len%4)==0) { add_factor(4); len>>=2; } if ((len%2)==0) { len>>=1; // factor 2 should be at the front of the factor list add_factor(2); swap(fact[0].fct, fact.back().fct); } for (size_t divisor=3; divisor*divisor<=len; divisor+=2) while ((len%divisor)==0) { add_factor(divisor); len/=divisor; } if (len>1) add_factor(len); } size_t twsize() const { size_t twsz=0, l1=1; for (size_t k=0; k<fact.size(); ++k) { size_t ip=fact[k].fct, ido=length/(l1*ip); twsz+=(ip-1)*(ido-1); if (ip>5) twsz+=2*ip; l1*=ip; } return twsz; } void comp_twiddle() { sincos_2pibyn<T0> twid(length, true); size_t l1=1; T0 *ptr=mem.data(); for (size_t k=0; k<fact.size(); ++k) { size_t ip=fact[k].fct, ido=length/(l1*ip); if (k<fact.size()-1) // last factor doesn't need twiddles { fact[k].tw=ptr; ptr+=(ip-1)*(ido-1); for (size_t j=1; j<ip; ++j) for (size_t i=1; i<=(ido-1)/2; ++i) { fact[k].tw[(j-1)*(ido-1)+2*i-2] = twid[2*j*l1*i]; fact[k].tw[(j-1)*(ido-1)+2*i-1] = twid[2*j*l1*i+1]; } } if (ip>5) // special factors required by *g functions { fact[k].tws=ptr; ptr+=2*ip; fact[k].tws[0] = 1.; fact[k].tws[1] = 0.; for (size_t i=2, ic=2*ip-2; i<=ic; i+=2, ic-=2) { fact[k].tws[i ] = twid[i*(length/ip)]; fact[k].tws[i+1] = twid[i*(length/ip)+1]; fact[k].tws[ic] = twid[i*(length/ip)]; fact[k].tws[ic+1] = -twid[i*(length/ip)+1]; } } l1*=ip; } } public: POCKETFFT_NOINLINE rfftp(size_t length_) : length(length_) { if (length==0) throw runtime_error("zero-sized FFT"); if (length==1) return; factorize(); mem.resize(twsize()); comp_twiddle(); } }; // // complex Bluestein transforms // template<typename T0> class fftblue { private: size_t n, n2; cfftp<T0> plan; arr<cmplx<T0>> mem; cmplx<T0> *bk, *bkf; template<bool fwd, typename T> void fft(cmplx<T> c[], T0 fct) { arr<cmplx<T>> akf(n2); /* initialize a_k and FFT it */ for (size_t m=0; m<n; ++m) akf[m] = c[m].template special_mul<fwd>(bk[m]); auto zero = akf[0]*T0(0); for (size_t m=n; m<n2; ++m) akf[m]=zero; plan.forward (akf.data(),1.); /* do the convolution */ for (size_t m=0; m<n2; ++m) akf[m] = akf[m].template special_mul<!fwd>(bkf[m]); /* inverse FFT */ plan.backward (akf.data(),1.); /* multiply by b_k */ for (size_t m=0; m<n; ++m) c[m] = akf[m].template special_mul<fwd>(bk[m])*fct; } public: POCKETFFT_NOINLINE fftblue(size_t length) : n(length), n2(util::good_size(n*2-1)), plan(n2), mem(n+n2), bk(mem.data()), bkf(mem.data()+n) { /* initialize b_k */ sincos_2pibyn<T0> tmp_(2*n, false); auto tmp = tmp_.cdata(); bk[0].Set(1, 0); size_t coeff=0; for (size_t m=1; m<n; ++m) { coeff+=2*m-1; if (coeff>=2*n) coeff-=2*n; bk[m] = tmp[coeff]; } /* initialize the zero-padded, Fourier transformed b_k. Add normalisation. */ T0 xn2 = T0(1)/T0(n2); bkf[0] = bk[0]*xn2; for (size_t m=1; m<n; ++m) bkf[m] = bkf[n2-m] = bk[m]*xn2; for (size_t m=n;m<=(n2-n);++m) bkf[m].Set(0.,0.); plan.forward(bkf,1.); } template<typename T> void backward(cmplx<T> c[], T0 fct) { fft<false>(c,fct); } template<typename T> void forward(cmplx<T> c[], T0 fct) { fft<true>(c,fct); } template<typename T> void backward_r(T c[], T0 fct) { arr<cmplx<T>> tmp(n); tmp[0].Set(c[0],c[0]*0); memcpy (reinterpret_cast<void *>(tmp.data()+1), reinterpret_cast<void *>(c+1), (n-1)*sizeof(T)); if ((n&1)==0) tmp[n/2].i=T0(0)*c[0]; for (size_t m=1; 2*m<n; ++m) tmp[n-m].Set(tmp[m].r, -tmp[m].i); fft<false>(tmp.data(),fct); for (size_t m=0; m<n; ++m) c[m] = tmp[m].r; } template<typename T> void forward_r(T c[], T0 fct) { arr<cmplx<T>> tmp(n); auto zero = T0(0)*c[0]; for (size_t m=0; m<n; ++m) tmp[m].Set(c[m], zero); fft<true>(tmp.data(),fct); c[0] = tmp[0].r; memcpy (c+1, tmp.data()+1, (n-1)*sizeof(T)); } }; // // flexible (FFTPACK/Bluestein) complex 1D transform // template<typename T0> class pocketfft_c { private: unique_ptr<cfftp<T0>> packplan; unique_ptr<fftblue<T0>> blueplan; size_t len; public: POCKETFFT_NOINLINE pocketfft_c(size_t length) : len(length) { if (length==0) throw runtime_error("zero-length FFT requested"); size_t tmp = (length<50) ? 0 : util::largest_prime_factor(length); if (tmp*tmp <= length) { packplan=unique_ptr<cfftp<T0>>(new cfftp<T0>(length)); return; } double comp1 = util::cost_guess(length); double comp2 = 2*util::cost_guess(util::good_size(2*length-1)); comp2*=1.5; /* fudge factor that appears to give good overall performance */ if (comp2<comp1) // use Bluestein blueplan=unique_ptr<fftblue<T0>>(new fftblue<T0>(length)); else packplan=unique_ptr<cfftp<T0>>(new cfftp<T0>(length)); } template<typename T> POCKETFFT_NOINLINE void backward(cmplx<T> c[], T0 fct) { packplan ? packplan->backward(c,fct) : blueplan->backward(c,fct); } template<typename T> POCKETFFT_NOINLINE void forward(cmplx<T> c[], T0 fct) { packplan ? packplan->forward(c,fct) : blueplan->forward(c,fct); } size_t length() const { return len; } }; // // flexible (FFTPACK/Bluestein) real-valued 1D transform // template<typename T0> class pocketfft_r { private: unique_ptr<rfftp<T0>> packplan; unique_ptr<fftblue<T0>> blueplan; size_t len; public: POCKETFFT_NOINLINE pocketfft_r(size_t length) : len(length) { if (length==0) throw runtime_error("zero-length FFT requested"); size_t tmp = (length<50) ? 0 : util::largest_prime_factor(length); if (tmp*tmp <= length) { packplan=unique_ptr<rfftp<T0>>(new rfftp<T0>(length)); return; } double comp1 = 0.5*util::cost_guess(length); double comp2 = 2*util::cost_guess(util::good_size(2*length-1)); comp2*=1.5; /* fudge factor that appears to give good overall performance */ if (comp2<comp1) // use Bluestein blueplan=unique_ptr<fftblue<T0>>(new fftblue<T0>(length)); else packplan=unique_ptr<rfftp<T0>>(new rfftp<T0>(length)); } template<typename T> POCKETFFT_NOINLINE void backward(T c[], T0 fct) { packplan ? packplan->backward(c,fct) : blueplan->backward_r(c,fct); } template<typename T> POCKETFFT_NOINLINE void forward(T c[], T0 fct) { packplan ? packplan->forward(c,fct) : blueplan->forward_r(c,fct); } size_t length() const { return len; } }; // // multi-D infrastructure // template<typename T> shared_ptr<T> get_plan(size_t length) { #if POCKETFFT_CACHE_SIZE==0 return make_shared<T>(length); #else constexpr size_t nmax=POCKETFFT_CACHE_SIZE; static array<shared_ptr<T>, nmax> cache; static array<size_t, nmax> last_access{{0}}; static size_t access_counter = 0; static mutex mut; auto find_in_cache = [&]() -> shared_ptr<T> { for (size_t i=0; i<nmax; ++i) if (cache[i] && (cache[i]->length()==length)) { // no need to update if this is already the most recent entry if (last_access[i]!=access_counter) { last_access[i] = ++access_counter; // Guard against overflow if (access_counter == 0) last_access.fill(0); } return cache[i]; } return nullptr; }; { lock_guard<mutex> lock(mut); auto p = find_in_cache(); if (p) return p; } auto plan = make_shared<T>(length); { lock_guard<mutex> lock(mut); auto p = find_in_cache(); if (p) return p; size_t lru = 0; for (size_t i=1; i<nmax; ++i) if (last_access[i] < last_access[lru]) lru = i; cache[lru] = plan; last_access[lru] = ++access_counter; } return plan; #endif } class arr_info { protected: shape_t shp; stride_t str; public: arr_info(const shape_t &shape_, const stride_t &stride_) : shp(shape_), str(stride_) {} size_t ndim() const { return shp.size(); } size_t size() const { return util::prod(shp); } const shape_t &shape() const { return shp; } size_t shape(size_t i) const { return shp[i]; } const stride_t &stride() const { return str; } const ptrdiff_t &stride(size_t i) const { return str[i]; } }; template<typename T> class cndarr: public arr_info { protected: const char *d; public: cndarr(const void *data_, const shape_t &shape_, const stride_t &stride_) : arr_info(shape_, stride_), d(reinterpret_cast<const char *>(data_)) {} const T &operator[](ptrdiff_t ofs) const { return *reinterpret_cast<const T *>(d+ofs); } }; template<typename T> class ndarr: public cndarr<T> { public: ndarr(void *data_, const shape_t &shape_, const stride_t &stride_) : cndarr<T>::cndarr(const_cast<const void *>(data_), shape_, stride_) {} T &operator[](ptrdiff_t ofs) { return *reinterpret_cast<T *>(const_cast<char *>(cndarr<T>::d+ofs)); } }; template<size_t N> class multi_iter { private: shape_t pos; const arr_info &iarr, &oarr; ptrdiff_t p_ii, p_i[N], str_i, p_oi, p_o[N], str_o; size_t idim, rem; void advance_i() { for (int i_=int(pos.size())-1; i_>=0; --i_) { auto i = size_t(i_); if (i==idim) continue; p_ii += iarr.stride(i); p_oi += oarr.stride(i); if (++pos[i] < iarr.shape(i)) return; pos[i] = 0; p_ii -= ptrdiff_t(iarr.shape(i))*iarr.stride(i); p_oi -= ptrdiff_t(oarr.shape(i))*oarr.stride(i); } } public: multi_iter(const arr_info &iarr_, const arr_info &oarr_, size_t idim_) : pos(iarr_.ndim(), 0), iarr(iarr_), oarr(oarr_), p_ii(0), str_i(iarr.stride(idim_)), p_oi(0), str_o(oarr.stride(idim_)), idim(idim_), rem(iarr.size()/iarr.shape(idim)) { auto nshares = util::nthreads(); if (nshares==1) return; if (nshares==0) throw runtime_error("can't run with zero threads"); auto myshare = util::thread_num(); if (myshare>=nshares) throw runtime_error("impossible share requested"); size_t nbase = rem/nshares; size_t additional = rem%nshares; size_t lo = myshare*nbase + ((myshare<additional) ? myshare : additional); size_t hi = lo+nbase+(myshare<additional); size_t todo = hi-lo; size_t chunk = rem; for (size_t i=0; i<pos.size(); ++i) { if (i==idim) continue; chunk /= iarr.shape(i); size_t n_advance = lo/chunk; pos[i] += n_advance; p_ii += ptrdiff_t(n_advance)*iarr.stride(i); p_oi += ptrdiff_t(n_advance)*oarr.stride(i); lo -= n_advance*chunk; } rem = todo; } void advance(size_t n) { if (rem<n) throw runtime_error("underrun"); for (size_t i=0; i<n; ++i) { p_i[i] = p_ii; p_o[i] = p_oi; advance_i(); } rem -= n; } ptrdiff_t iofs(size_t i) const { return p_i[0] + ptrdiff_t(i)*str_i; } ptrdiff_t iofs(size_t j, size_t i) const { return p_i[j] + ptrdiff_t(i)*str_i; } ptrdiff_t oofs(size_t i) const { return p_o[0] + ptrdiff_t(i)*str_o; } ptrdiff_t oofs(size_t j, size_t i) const { return p_o[j] + ptrdiff_t(i)*str_o; } size_t length_in() const { return iarr.shape(idim); } size_t length_out() const { return oarr.shape(idim); } ptrdiff_t stride_in() const { return str_i; } ptrdiff_t stride_out() const { return str_o; } size_t remaining() const { return rem; } }; class simple_iter { private: shape_t pos; const arr_info &arr; ptrdiff_t p; size_t rem; public: simple_iter(const arr_info &arr_) : pos(arr_.ndim(), 0), arr(arr_), p(0), rem(arr_.size()) {} void advance() { --rem; for (int i_=int(pos.size())-1; i_>=0; --i_) { auto i = size_t(i_); p += arr.stride(i); if (++pos[i] < arr.shape(i)) return; pos[i] = 0; p -= ptrdiff_t(arr.shape(i))*arr.stride(i); } } ptrdiff_t ofs() const { return p; } size_t remaining() const { return rem; } }; class rev_iter { private: shape_t pos; const arr_info &arr; vector<char> rev_axis; vector<char> rev_jump; size_t last_axis, last_size; shape_t shp; ptrdiff_t p, rp; size_t rem; public: rev_iter(const arr_info &arr_, const shape_t &axes) : pos(arr_.ndim(), 0), arr(arr_), rev_axis(arr_.ndim(), 0), rev_jump(arr_.ndim(), 1), p(0), rp(0) { for (auto ax: axes) rev_axis[ax]=1; last_axis = axes.back(); last_size = arr.shape(last_axis)/2 + 1; shp = arr.shape(); shp[last_axis] = last_size; rem=1; for (auto i: shp) rem *= i; } void advance() { --rem; for (int i_=int(pos.size())-1; i_>=0; --i_) { auto i = size_t(i_); p += arr.stride(i); if (!rev_axis[i]) rp += arr.stride(i); else { rp -= arr.stride(i); if (rev_jump[i]) { rp += ptrdiff_t(arr.shape(i))*arr.stride(i); rev_jump[i] = 0; } } if (++pos[i] < shp[i]) return; pos[i] = 0; p -= ptrdiff_t(shp[i])*arr.stride(i); if (rev_axis[i]) { rp -= ptrdiff_t(arr.shape(i)-shp[i])*arr.stride(i); rev_jump[i] = 1; } else rp -= ptrdiff_t(shp[i])*arr.stride(i); } } ptrdiff_t ofs() const { return p; } ptrdiff_t rev_ofs() const { return rp; } size_t remaining() const { return rem; } }; #ifndef POCKETFFT_NO_VECTORS template<typename T> struct VTYPE {}; template<> struct VTYPE<float> { using type = float __attribute__ ((vector_size (VLEN<float>::val*sizeof(float)))); }; template<> struct VTYPE<double> { using type = double __attribute__ ((vector_size (VLEN<double>::val*sizeof(double)))); }; template<> struct VTYPE<long double> { using type = long double __attribute__ ((vector_size (VLEN<long double>::val*sizeof(long double)))); }; #endif template<typename T> arr<char> alloc_tmp(const shape_t &shape, size_t axsize, size_t elemsize) { auto othersize = util::prod(shape)/axsize; auto tmpsize = axsize*((othersize>=VLEN<T>::val) ? VLEN<T>::val : 1); return arr<char>(tmpsize*elemsize); } template<typename T> arr<char> alloc_tmp(const shape_t &shape, const shape_t &axes, size_t elemsize) { size_t fullsize=util::prod(shape); size_t tmpsize=0; for (size_t i=0; i<axes.size(); ++i) { auto axsize = shape[axes[i]]; auto othersize = fullsize/axsize; auto sz = axsize*((othersize>=VLEN<T>::val) ? VLEN<T>::val : 1); if (sz>tmpsize) tmpsize=sz; } return arr<char>(tmpsize*elemsize); } #ifdef POCKETFFT_OPENMP #define POCKETFFT_NTHREADS nthreads #else #define POCKETFFT_NTHREADS #endif template<typename T> POCKETFFT_NOINLINE void general_c( const cndarr<cmplx<T>> &in, ndarr<cmplx<T>> &out, const shape_t &axes, bool forward, T fct, size_t POCKETFFT_NTHREADS) { shared_ptr<pocketfft_c<T>> plan; for (size_t iax=0; iax<axes.size(); ++iax) { constexpr auto vlen = VLEN<T>::val; size_t len=in.shape(axes[iax]); if ((!plan) || (len!=plan->length())) plan = get_plan<pocketfft_c<T>>(len); #ifdef POCKETFFT_OPENMP #pragma omp parallel num_threads(util::thread_count(nthreads, in.shape(), axes[iax])) #endif { auto storage = alloc_tmp<T>(in.shape(), len, sizeof(cmplx<T>)); const auto &tin(iax==0? in : out); multi_iter<vlen> it(tin, out, axes[iax]); #ifndef POCKETFFT_NO_VECTORS if (vlen>1) while (it.remaining()>=vlen) { using vtype = typename VTYPE<T>::type; it.advance(vlen); auto tdatav = reinterpret_cast<cmplx<vtype> *>(storage.data()); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) { tdatav[i].r[j] = tin[it.iofs(j,i)].r; tdatav[i].i[j] = tin[it.iofs(j,i)].i; } forward ? plan->forward (tdatav, fct) : plan->backward(tdatav, fct); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,i)].Set(tdatav[i].r[j],tdatav[i].i[j]); } #endif while (it.remaining()>0) { it.advance(1); auto tdata = reinterpret_cast<cmplx<T> *>(storage.data()); if ((&tin[0]==&out[0]) && (it.stride_out()==sizeof(cmplx<T>))) // fully in-place forward ? plan->forward (&out[it.oofs(0)], fct) : plan->backward(&out[it.oofs(0)], fct); else if (it.stride_out()==sizeof(cmplx<T>)) // compute FFT in output location { for (size_t i=0; i<len; ++i) out[it.oofs(i)] = tin[it.iofs(i)]; forward ? plan->forward (&out[it.oofs(0)], fct) : plan->backward(&out[it.oofs(0)], fct); } else { for (size_t i=0; i<len; ++i) tdata[i] = tin[it.iofs(i)]; forward ? plan->forward (tdata, fct) : plan->backward(tdata, fct); for (size_t i=0; i<len; ++i) out[it.oofs(i)] = tdata[i]; } } } // end of parallel region fct = T(1); // factor has been applied, use 1 for remaining axes } } template<typename T> POCKETFFT_NOINLINE void general_hartley( const cndarr<T> &in, ndarr<T> &out, const shape_t &axes, T fct, size_t POCKETFFT_NTHREADS) { shared_ptr<pocketfft_r<T>> plan; for (size_t iax=0; iax<axes.size(); ++iax) { constexpr auto vlen = VLEN<T>::val; size_t len=in.shape(axes[iax]); if ((!plan) || (len!=plan->length())) plan = get_plan<pocketfft_r<T>>(len); #ifdef POCKETFFT_OPENMP #pragma omp parallel num_threads(util::thread_count(nthreads, in.shape(), axes[iax])) #endif { auto storage = alloc_tmp<T>(in.shape(), len, sizeof(T)); const auto &tin(iax==0 ? in : out); multi_iter<vlen> it(tin, out, axes[iax]); #ifndef POCKETFFT_NO_VECTORS if (vlen>1) while (it.remaining()>=vlen) { using vtype = typename VTYPE<T>::type; it.advance(vlen); auto tdatav = reinterpret_cast<vtype *>(storage.data()); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = tin[it.iofs(j,i)]; plan->forward(tdatav, fct); for (size_t j=0; j<vlen; ++j) out[it.oofs(j,0)] = tdatav[0][j]; size_t i=1, i1=1, i2=len-1; for (i=1; i<len-1; i+=2, ++i1, --i2) for (size_t j=0; j<vlen; ++j) { out[it.oofs(j,i1)] = tdatav[i][j]+tdatav[i+1][j]; out[it.oofs(j,i2)] = tdatav[i][j]-tdatav[i+1][j]; } if (i<len) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,i1)] = tdatav[i][j]; } #endif while (it.remaining()>0) { it.advance(1); auto tdata = reinterpret_cast<T *>(storage.data()); for (size_t i=0; i<len; ++i) tdata[i] = tin[it.iofs(i)]; plan->forward(tdata, fct); // Hartley order out[it.oofs(0)] = tdata[0]; size_t i=1, i1=1, i2=len-1; for (i=1; i<len-1; i+=2, ++i1, --i2) { out[it.oofs(i1)] = tdata[i]+tdata[i+1]; out[it.oofs(i2)] = tdata[i]-tdata[i+1]; } if (i<len) out[it.oofs(i1)] = tdata[i]; } } // end of parallel region fct = T(1); // factor has been applied, use 1 for remaining axes } } template<typename T> POCKETFFT_NOINLINE void general_r2c( const cndarr<T> &in, ndarr<cmplx<T>> &out, size_t axis, bool forward, T fct, size_t POCKETFFT_NTHREADS) { auto plan = get_plan<pocketfft_r<T>>(in.shape(axis)); constexpr auto vlen = VLEN<T>::val; size_t len=in.shape(axis); #ifdef POCKETFFT_OPENMP #pragma omp parallel num_threads(util::thread_count(nthreads, in.shape(), axis)) #endif { auto storage = alloc_tmp<T>(in.shape(), len, sizeof(T)); multi_iter<vlen> it(in, out, axis); #ifndef POCKETFFT_NO_VECTORS if (vlen>1) while (it.remaining()>=vlen) { using vtype = typename VTYPE<T>::type; it.advance(vlen); auto tdatav = reinterpret_cast<vtype *>(storage.data()); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = in[it.iofs(j,i)]; plan->forward(tdatav, fct); for (size_t j=0; j<vlen; ++j) out[it.oofs(j,0)].Set(tdatav[0][j]); size_t i=1, ii=1; if (forward) for (; i<len-1; i+=2, ++ii) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,ii)].Set(tdatav[i][j], tdatav[i+1][j]); else for (; i<len-1; i+=2, ++ii) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,ii)].Set(tdatav[i][j], -tdatav[i+1][j]); if (i<len) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,ii)].Set(tdatav[i][j]); } #endif while (it.remaining()>0) { it.advance(1); auto tdata = reinterpret_cast<T *>(storage.data()); for (size_t i=0; i<len; ++i) tdata[i] = in[it.iofs(i)]; plan->forward(tdata, fct); out[it.oofs(0)].Set(tdata[0]); size_t i=1, ii=1; if (forward) for (; i<len-1; i+=2, ++ii) out[it.oofs(ii)].Set(tdata[i], tdata[i+1]); else for (; i<len-1; i+=2, ++ii) out[it.oofs(ii)].Set(tdata[i], -tdata[i+1]); if (i<len) out[it.oofs(ii)].Set(tdata[i]); } } // end of parallel region } template<typename T> POCKETFFT_NOINLINE void general_c2r( const cndarr<cmplx<T>> &in, ndarr<T> &out, size_t axis, bool forward, T fct, size_t POCKETFFT_NTHREADS) { auto plan = get_plan<pocketfft_r<T>>(out.shape(axis)); constexpr auto vlen = VLEN<T>::val; size_t len=out.shape(axis); #ifdef POCKETFFT_OPENMP #pragma omp parallel num_threads(util::thread_count(nthreads, in.shape(), axis)) #endif { auto storage = alloc_tmp<T>(out.shape(), len, sizeof(T)); multi_iter<vlen> it(in, out, axis); #ifndef POCKETFFT_NO_VECTORS if (vlen>1) while (it.remaining()>=vlen) { using vtype = typename VTYPE<T>::type; it.advance(vlen); auto tdatav = reinterpret_cast<vtype *>(storage.data()); for (size_t j=0; j<vlen; ++j) tdatav[0][j]=in[it.iofs(j,0)].r; { size_t i=1, ii=1; if (forward) for (; i<len-1; i+=2, ++ii) for (size_t j=0; j<vlen; ++j) { tdatav[i ][j] = in[it.iofs(j,ii)].r; tdatav[i+1][j] = -in[it.iofs(j,ii)].i; } else for (; i<len-1; i+=2, ++ii) for (size_t j=0; j<vlen; ++j) { tdatav[i ][j] = in[it.iofs(j,ii)].r; tdatav[i+1][j] = in[it.iofs(j,ii)].i; } if (i<len) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = in[it.iofs(j,ii)].r; } plan->backward(tdatav, fct); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,i)] = tdatav[i][j]; } #endif while (it.remaining()>0) { it.advance(1); auto tdata = reinterpret_cast<T *>(storage.data()); tdata[0]=in[it.iofs(0)].r; { size_t i=1, ii=1; if (forward) for (; i<len-1; i+=2, ++ii) { tdata[i ] = in[it.iofs(ii)].r; tdata[i+1] = -in[it.iofs(ii)].i; } else for (; i<len-1; i+=2, ++ii) { tdata[i ] = in[it.iofs(ii)].r; tdata[i+1] = in[it.iofs(ii)].i; } if (i<len) tdata[i] = in[it.iofs(ii)].r; } plan->backward(tdata, fct); for (size_t i=0; i<len; ++i) out[it.oofs(i)] = tdata[i]; } } // end of parallel region } template<typename T> POCKETFFT_NOINLINE void general_r( const cndarr<T> &in, ndarr<T> &out, const shape_t &axes, bool r2c, bool forward, T fct, size_t POCKETFFT_NTHREADS) { shared_ptr<pocketfft_r<T>> plan; for (size_t iax=0; iax<axes.size(); ++iax) { constexpr auto vlen = VLEN<T>::val; size_t len=in.shape(axes[iax]); if ((!plan) || (len!=plan->length())) plan = get_plan<pocketfft_r<T>>(len); #ifdef POCKETFFT_OPENMP #pragma omp parallel num_threads(util::thread_count(nthreads, in.shape(), axes[iax])) #endif { auto storage = alloc_tmp<T>(in.shape(), len, sizeof(T)); const auto &tin(iax==0 ? in : out); multi_iter<vlen> it(tin, out, axes[iax]); #ifndef POCKETFFT_NO_VECTORS if (vlen>1) while (it.remaining()>=vlen) { using vtype = typename VTYPE<T>::type; it.advance(vlen); auto tdatav = reinterpret_cast<vtype *>(storage.data()); for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = tin[it.iofs(j,i)]; if ((!r2c) && forward) for (size_t i=2; i<len; i+=2) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = -tdatav[i][j]; forward ? plan->forward (tdatav, fct) : plan->backward(tdatav, fct); if (r2c && (!forward)) for (size_t i=2; i<len; i+=2) for (size_t j=0; j<vlen; ++j) tdatav[i][j] = -tdatav[i][j]; for (size_t i=0; i<len; ++i) for (size_t j=0; j<vlen; ++j) out[it.oofs(j,i)] = tdatav[i][j]; } #endif while (it.remaining()>0) { it.advance(1); auto tdata = reinterpret_cast<T *>(storage.data()); if ((&tin[0]==&out[0]) && (it.stride_out()==sizeof(T))) // fully in-place { if ((!r2c) && forward) for (size_t i=2; i<len; i+=2) out[it.oofs(i)] = -out[it.oofs(i)]; forward ? plan->forward (&out[it.oofs(0)], fct) : plan->backward(&out[it.oofs(0)], fct); if (r2c && (!forward)) for (size_t i=2; i<len; i+=2) out[it.oofs(i)] = -out[it.oofs(i)]; } else if (it.stride_out()==sizeof(T)) // compute FFT in output location { for (size_t i=0; i<len; ++i) out[it.oofs(i)] = tin[it.iofs(i)]; if ((!r2c) && forward) for (size_t i=2; i<len; i+=2) out[it.oofs(i)] = -out[it.oofs(i)]; forward ? plan->forward (&out[it.oofs(0)], fct) : plan->backward(&out[it.oofs(0)], fct); if (r2c && (!forward)) for (size_t i=2; i<len; i+=2) out[it.oofs(i)] = -out[it.oofs(i)]; } else { for (size_t i=0; i<len; ++i) tdata[i] = tin[it.iofs(i)]; if ((!r2c) && forward) for (size_t i=2; i<len; i+=2) tdata[i] = -tdata[i]; forward ? plan->forward (tdata, fct) : plan->backward(tdata, fct); if (r2c && (!forward)) for (size_t i=2; i<len; i+=2) tdata[i] = -tdata[i]; for (size_t i=0; i<len; ++i) out[it.oofs(i)] = tdata[i]; } } } // end of parallel region fct = T(1); // factor has been applied, use 1 for remaining axes } } #undef POCKETFFT_NTHREADS template<typename T> void c2c(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, bool forward, const complex<T> *data_in, complex<T> *data_out, T fct, size_t nthreads=1) { if (util::prod(shape)==0) return; util::sanity_check(shape, stride_in, stride_out, data_in==data_out, axes); cndarr<cmplx<T>> ain(data_in, shape, stride_in); ndarr<cmplx<T>> aout(data_out, shape, stride_out); general_c(ain, aout, axes, forward, fct, nthreads); } template<typename T> void r2c(const shape_t &shape_in, const stride_t &stride_in, const stride_t &stride_out, size_t axis, bool forward, const T *data_in, complex<T> *data_out, T fct, size_t nthreads=1) { if (util::prod(shape_in)==0) return; util::sanity_check(shape_in, stride_in, stride_out, false, axis); cndarr<T> ain(data_in, shape_in, stride_in); shape_t shape_out(shape_in); shape_out[axis] = shape_in[axis]/2 + 1; ndarr<cmplx<T>> aout(data_out, shape_out, stride_out); general_r2c(ain, aout, axis, forward, fct, nthreads); } template<typename T> void r2c(const shape_t &shape_in, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, bool forward, const T *data_in, complex<T> *data_out, T fct, size_t nthreads=1) { if (util::prod(shape_in)==0) return; util::sanity_check(shape_in, stride_in, stride_out, false, axes); r2c(shape_in, stride_in, stride_out, axes.back(), forward, data_in, data_out, fct, nthreads); if (axes.size()==1) return; shape_t shape_out(shape_in); shape_out[axes.back()] = shape_in[axes.back()]/2 + 1; auto newaxes = shape_t{axes.begin(), --axes.end()}; c2c(shape_out, stride_out, stride_out, newaxes, forward, data_out, data_out, T(1), nthreads); } template<typename T> void c2r(const shape_t &shape_out, const stride_t &stride_in, const stride_t &stride_out, size_t axis, bool forward, const complex<T> *data_in, T *data_out, T fct, size_t nthreads=1) { if (util::prod(shape_out)==0) return; util::sanity_check(shape_out, stride_in, stride_out, false, axis); shape_t shape_in(shape_out); shape_in[axis] = shape_out[axis]/2 + 1; cndarr<cmplx<T>> ain(data_in, shape_in, stride_in); ndarr<T> aout(data_out, shape_out, stride_out); general_c2r(ain, aout, axis, forward, fct, nthreads); } template<typename T> void c2r(const shape_t &shape_out, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, bool forward, const complex<T> *data_in, T *data_out, T fct, size_t nthreads=1) { if (util::prod(shape_out)==0) return; if (axes.size()==1) return c2r(shape_out, stride_in, stride_out, axes[0], forward, data_in, data_out, fct, nthreads); util::sanity_check(shape_out, stride_in, stride_out, false, axes); auto shape_in = shape_out; shape_in[axes.back()] = shape_out[axes.back()]/2 + 1; auto nval = util::prod(shape_in); stride_t stride_inter(shape_in.size()); stride_inter.back() = sizeof(cmplx<T>); for (int i=int(shape_in.size())-2; i>=0; --i) stride_inter[size_t(i)] = stride_inter[size_t(i+1)]*ptrdiff_t(shape_in[size_t(i+1)]); arr<complex<T>> tmp(nval); auto newaxes = shape_t({axes.begin(), --axes.end()}); c2c(shape_in, stride_in, stride_inter, newaxes, forward, data_in, tmp.data(), T(1), nthreads); c2r(shape_out, stride_inter, stride_out, axes.back(), forward, tmp.data(), data_out, fct, nthreads); } template<typename T> void r2r_fftpack(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, bool real2hermitian, bool forward, const T *data_in, T *data_out, T fct, size_t nthreads=1) { if (util::prod(shape)==0) return; util::sanity_check(shape, stride_in, stride_out, data_in==data_out, axes); cndarr<T> ain(data_in, shape, stride_in); ndarr<T> aout(data_out, shape, stride_out); general_r(ain, aout, axes, real2hermitian, forward, fct, nthreads); } template<typename T> void r2r_separable_hartley(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, const T *data_in, T *data_out, T fct, size_t nthreads=1) { if (util::prod(shape)==0) return; util::sanity_check(shape, stride_in, stride_out, data_in==data_out, axes); cndarr<T> ain(data_in, shape, stride_in); ndarr<T> aout(data_out, shape, stride_out); general_hartley(ain, aout, axes, fct, nthreads); } } // namespace detail using detail::FORWARD; using detail::BACKWARD; using detail::shape_t; using detail::stride_t; using detail::c2c; using detail::c2r; using detail::r2c; using detail::r2r_fftpack; using detail::r2r_separable_hartley; } // namespace pocketfft #undef POCKETFFT_NOINLINE #undef POCKETFFT_RESTRICT #endif // POCKETFFT_HDRONLY_H
for_simple.c
/* PMSIS includes */ #include "pmsis.h" #include "omp.h" #define NB_CORES (8) static int32_t core_iterations[NB_CORES] = { 0 }; static uint32_t errors = 0; /* Cluster main entry, executed by core 0. */ void cluster_delegate(void *arg) { printf("Cluster master core entry\n"); #pragma omp parallel num_threads(NB_CORES) { printf("[%d %d] Fork entry\n", pi_cluster_id(), omp_get_thread_num() ); #pragma omp for for (int i=0; i<64; i++) { int32_t core_id = omp_get_thread_num(); if (core_id > NB_CORES) { errors++; } else { core_iterations[core_id]++; } printf("[%d %d] for entry index %d\n", pi_cluster_id(), omp_get_thread_num(), i ); } } for (int i = 0; i < NB_CORES; i++) { if (core_iterations[i] == 0) { errors++; printf("Core #%d has no iteration\n", i); } } printf("Cluster master core exit\n"); } void helloworld(void) { printf("Entering main controller\n"); uint32_t errors = 0; uint32_t core_id = pi_core_id(), cluster_id = pi_cluster_id(); printf("[%d %d] Hello World!\n", cluster_id, core_id); struct pi_device cluster_dev; struct pi_cluster_conf cl_conf; /* Init cluster configuration structure. */ pi_cluster_conf_init(&cl_conf); cl_conf.id = 0; /* Set cluster ID. */ /* Configure & open cluster. */ pi_open_from_conf(&cluster_dev, &cl_conf); if (pi_cluster_open(&cluster_dev)) { printf("Cluster open failed !\n"); pmsis_exit(-1); } /* Prepare cluster task and send it to cluster. */ struct pi_cluster_task cl_task; pi_cluster_task(&cl_task, cluster_delegate, NULL); pi_cluster_send_task_to_cl(&cluster_dev, &cl_task); pi_cluster_close(&cluster_dev); if (errors) { printf("Test failed!\n"); } else { printf("Test success!\n"); } pmsis_exit(errors); } /* Program Entry. */ int main(void) { printf("\n\n\t *** PMSIS HelloWorld ***\n\n"); return pmsis_kickoff((void *) helloworld); }
axpy_ompacc3.c
// Experimental test input for Accelerator directives // simplest scalar*vector operations // Testing extensions for multiple devices // Liao 2/2/2015 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <omp.h> #if 0 double time_stamp() { struct timeval t; double time; gettimeofday(&t, NULL); time = t.tv_sec + 1.0e-6*t.tv_usec; return time; } #endif /* in second */ #define read_timer() omp_get_wtime() //#define read_timer() time_stamp() /* change this to do saxpy or daxpy : single precision or double precision*/ #define REAL double #define VEC_LEN 1024000 //use a fixed number for now /* zero out the entire vector */ void zero(REAL *A, int n) { int i; for (i = 0; i < n; i++) { A[i] = 0.0; } } /* initialize a vector with random floating point numbers */ void init(REAL *A, int n) { int i; for (i = 0; i < n; i++) { A[i] = (double)drand48(); } } REAL check(REAL*A, REAL*B, int n) { int i; REAL sum = 0.0; for (i = 0; i < n; i++) { sum += A[i] - B[i]; } return sum; } // reference CPU version void axpy_omp(REAL* x, REAL* y, long n, REAL a) { int i; #pragma omp parallel for shared(x, y, n, a) private(i) for (i = 0; i < n; ++i) { y[i] += a * x[i]; } } // GPU version void axpy_ompacc(REAL* x, REAL* y, int n, REAL a) { int i; #pragma omp target device (gpu0) map(tofrom: y[0:n] dist_data(block) ) map(to: x[0:n] dist_data(block),a,n) #pragma omp parallel for shared(x, y, n, a) private(i) for (i = 0; i < n; ++i) y[i] += a * x[i]; } int main(int argc, char *argv[]) { int n; REAL *y_omp, *y_ompacc, *x; REAL a = 123.456; n = VEC_LEN; y_omp = (REAL *) malloc(n * sizeof(REAL)); y_ompacc = (REAL *) malloc(n * sizeof(REAL)); x = (REAL *) malloc(n * sizeof(REAL)); srand48(1<<12); init(x, n); init(y_ompacc, n); memcpy(y_ompacc, y_omp, n*sizeof(REAL)); int num_threads; #pragma omp parallel shared (num_threads) { if (omp_get_thread_num() == 0) num_threads = omp_get_num_threads(); } /* CPU threading version*/ double omp_time = read_timer(); axpy_omp(x, y_omp, n, a); omp_time = read_timer() - omp_time; /* openmp acc version */ double ompacc_time = read_timer(); axpy_ompacc(x, y_ompacc, n, a); ompacc_time = read_timer() - ompacc_time; printf("axpy(%d): checksum: %g; time(s):\tOMP(%d threads)\tOMPACC\n", n, check(y_omp, y_ompacc, n),num_threads); printf("\t\t\t\t\t\t%4f\t%4f\n", omp_time, ompacc_time); free(y_omp); free(y_ompacc); free(x); return 0; }
GB_bitmap_assign_M_row_template.c
//------------------------------------------------------------------------------ // GB_bitmap_assign_M_row_template: traverse M for GB_ROW_ASSIGN //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // M is a 1-by-(C->vdim) hypersparse or sparse matrix, not a vector, for // GrB_Row_assign (if C is CSC) or GrB_Col_assign (if C is CSR). // C is bitmap/full. M is sparse/hyper, and can be jumbled. { ASSERT (mvlen == 1) ; int64_t iC = I [0] ; int tid ; #pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1) \ reduction(+:cnvals) for (tid = 0 ; tid < M_ntasks ; tid++) { int64_t kfirst = kfirst_Mslice [tid] ; int64_t klast = klast_Mslice [tid] ; int64_t task_cnvals = 0 ; //---------------------------------------------------------------------- // traverse over M (0,kfirst:klast) //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of M(0,k) for this task //------------------------------------------------------------------ int64_t jM = GBH (Mh, k) ; int64_t pM_start, pM_end ; GB_get_pA (&pM_start, &pM_end, tid, k, kfirst, klast, pstart_Mslice, Mp, mvlen) ; //------------------------------------------------------------------ // traverse over M(0,jM), the kth vector of M //------------------------------------------------------------------ // for row_assign: M is a single row, iC = I [0] // It has either 0 or 1 entry. int64_t pM = pM_start ; if (pM < pM_end) { bool mij = GB_mcast (Mx, pM, msize) ; if (mij) { int64_t jC = jM ; int64_t pC = iC + jC * cvlen ; GB_MASK_WORK (pC) ; } } } cnvals += task_cnvals ; } }
GB_unop__identity_uint8_int32.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_int32) // op(A') function: GB (_unop_tran__identity_uint8_int32) // C type: uint8_t // A type: int32_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint8_t z = (uint8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_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_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint8_int32) ( uint8_t *Cx, // Cx and Ax may be aliased const int32_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++) { int32_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 ; int32_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_int32) ( 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
omp_alloc_def_fb.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <omp.h> int main() { omp_alloctrait_t at[2]; omp_allocator_handle_t a; void *p[2]; at[0].key = OMP_ATK_POOL_SIZE; at[0].value = 2 * 1024 * 1024; at[1].key = OMP_ATK_FALLBACK; at[1].value = OMP_ATV_DEFAULT_MEM_FB; a = omp_init_allocator(omp_large_cap_mem_space, 2, at); printf("allocator large created: %p\n", a); #pragma omp parallel num_threads(2) { int i = omp_get_thread_num(); p[i] = omp_alloc(1024 * 1024, a); #pragma omp barrier printf("th %d, ptr %p\n", i, p[i]); omp_free(p[i], a); } // Both pointers should be non-NULL if (p[0] != NULL && p[1] != NULL) { printf("passed\n"); return 0; } else { printf("failed: pointers %p %p\n", p[0], p[1]); return 1; } }
LAGraph_Sort1.c
//------------------------------------------------------------------------------ // LAGraph_Sort1: sort a list of integers //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // Contributed by Tim Davis, Texas A&M University. //------------------------------------------------------------------------------ // A parallel mergesort of an array of n integers. #define LAGRAPH_FREE_ALL LAGraph_Free ((void **) &W, W_size) ; #include "LG_internal.h" //------------------------------------------------------------------------------ // prototype only needed for LAGraph_Sort1 //------------------------------------------------------------------------------ void LG_msort_1b_create_merge_tasks ( // output: int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed // input: const int t0, // first task tid to create const int ntasks, // # of tasks to create const int64_t pS_start, // merge into S [pS_start...] const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1] const int64_t pL_start, const int64_t pL_end, const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1] const int64_t pR_start, const int64_t pR_end ) ; //------------------------------------------------------------------------------ // LG_msort_1b_binary_search: binary search for the pivot //------------------------------------------------------------------------------ // The Pivot value is Y [pivot], and a binary search for the Pivot is made in // the array X [p_pstart...p_end-1], which is sorted in non-decreasing order on // input. The return value is pleft, where // // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. // // pleft is returned in the range p_start to p_end. If pleft is p_start, then // the Pivot is smaller than all entries in X [p_start...p_end-1], and the left // list X [p_start...pleft-1] is empty. If pleft is p_end, then the Pivot is // larger than all entries in X [p_start...p_end-1], and the right list X // [pleft...p_end-1] is empty. static int64_t LG_msort_1b_binary_search // return pleft ( const int64_t *LG_RESTRICT Y_0, // Pivot is Y [pivot] const int64_t pivot, const int64_t *LG_RESTRICT X_0, // search in X [p_start..p_end_-1] const int64_t p_start, const int64_t p_end ) { //-------------------------------------------------------------------------- // find where the Pivot appears in X //-------------------------------------------------------------------------- // binary search of X [p_start...p_end-1] for the Pivot int64_t pleft = p_start ; int64_t pright = p_end - 1 ; while (pleft < pright) { int64_t pmiddle = (pleft + pright) >> 1 ; // less = (X [pmiddle] < Pivot) bool less = LG_lt_1 (X_0, pmiddle, Y_0, pivot) ; pleft = less ? (pmiddle+1) : pleft ; pright = less ? pright : pmiddle ; } // binary search is narrowed down to a single item // or it has found the list is empty: ASSERT (pleft == pright || pleft == pright + 1) ; // If found is true then X [pleft == pright] == Pivot. If duplicates // appear then X [pleft] is any one of the entries equal to the Pivot // in the list. If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft+1 ... p_end-1] > Pivot holds. // The value X [pleft] may be either < or > Pivot. bool found = (pleft == pright) && LG_eq_1 (X_0, pleft, Y_0, pivot) ; // Modify pleft and pright: if (!found && (pleft == pright)) { if (LG_lt_1 (X_0, pleft, Y_0, pivot)) { pleft++ ; } else { // pright++ ; // (not needed) } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- // If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] > Pivot holds, // and pleft-1 == pright // If X has no duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] >= Pivot holds. // If X has duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. return (pleft) ; } //------------------------------------------------------------------------------ // LG_msort_1b_create_merge_tasks //------------------------------------------------------------------------------ // Recursively constructs ntasks tasks to merge two arrays, Left and Right, // into Sresult, where Left is L [pL_start...pL_end-1], Right is R // [pR_start...pR_end-1], and Sresult is S [pS_start...pS_start+total_work-1], // and where total_work is the total size of Left and Right. // // Task tid will merge L [L_task [tid] ... L_task [tid] + L_len [tid] - 1] and // R [R_task [tid] ... R_task [tid] + R_len [tid] -1] into the merged output // array S [S_task [tid] ... ]. The task tids created are t0 to // t0+ntasks-1. void LG_msort_1b_create_merge_tasks ( // output: int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed // input: const int t0, // first task tid to create const int ntasks, // # of tasks to create const int64_t pS_start, // merge into S [pS_start...] const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1] const int64_t pL_start, const int64_t pL_end, const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1] const int64_t pR_start, const int64_t pR_end ) { //-------------------------------------------------------------------------- // get problem size //-------------------------------------------------------------------------- int64_t nleft = pL_end - pL_start ; // size of Left array int64_t nright = pR_end - pR_start ; // size of Right array int64_t total_work = nleft + nright ; // total work to do ASSERT (ntasks >= 1) ; ASSERT (total_work > 0) ; //-------------------------------------------------------------------------- // create the tasks //-------------------------------------------------------------------------- if (ntasks == 1) { //---------------------------------------------------------------------- // a single task will merge all of Left and Right into Sresult //---------------------------------------------------------------------- L_task [t0] = pL_start ; L_len [t0] = nleft ; R_task [t0] = pR_start ; R_len [t0] = nright ; S_task [t0] = pS_start ; } else { //---------------------------------------------------------------------- // partition the Left and Right arrays for multiple merge tasks //---------------------------------------------------------------------- int64_t pleft, pright ; if (nleft >= nright) { // split Left in half, and search for its pivot in Right pleft = (pL_end + pL_start) >> 1 ; pright = LG_msort_1b_binary_search ( L_0, pleft, R_0, pR_start, pR_end) ; } else { // split Right in half, and search for its pivot in Left pright = (pR_end + pR_start) >> 1 ; pleft = LG_msort_1b_binary_search ( R_0, pright, L_0, pL_start, pL_end) ; } //---------------------------------------------------------------------- // partition the tasks according to the work of each partition //---------------------------------------------------------------------- // work0 is the total work in the first partition int64_t work0 = (pleft - pL_start) + (pright - pR_start) ; int ntasks0 = (int) round ((double) ntasks * (((double) work0) / ((double) total_work))) ; // ensure at least one task is assigned to each partition ntasks0 = LAGraph_MAX (ntasks0, 1) ; ntasks0 = LAGraph_MIN (ntasks0, ntasks-1) ; int ntasks1 = ntasks - ntasks0 ; //---------------------------------------------------------------------- // assign ntasks0 to the first half //---------------------------------------------------------------------- // ntasks0 tasks merge L [pL_start...pleft-1] and R [pR_start..pright-1] // into the result S [pS_start...work0-1]. LG_msort_1b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t0, ntasks0, pS_start, L_0, pL_start, pleft, R_0, pR_start, pright) ; //---------------------------------------------------------------------- // assign ntasks1 to the second half //---------------------------------------------------------------------- // ntasks1 tasks merge L [pleft...pL_end-1] and R [pright...pR_end-1] // into the result S [pS_start+work0...pS_start+total_work]. int t1 = t0 + ntasks0 ; // first task id of the second set of tasks int64_t pS_start1 = pS_start + work0 ; // 2nd set starts here in S LG_msort_1b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t1, ntasks1, pS_start1, L_0, pleft, pL_end, R_0, pright, pR_end) ; } } //------------------------------------------------------------------------------ // LG_msort_1b_merge: merge two sorted lists via a single thread //------------------------------------------------------------------------------ // merge Left [0..nleft-1] and Right [0..nright-1] into S [0..nleft+nright-1] */ static void LG_msort_1b_merge ( int64_t *LG_RESTRICT S_0, // output of length nleft + nright const int64_t *LG_RESTRICT Left_0, // left input of length nleft const int64_t nleft, const int64_t *LG_RESTRICT Right_0, // right input of length nright const int64_t nright ) { int64_t p, pleft, pright ; // merge the two inputs, Left and Right, while both inputs exist for (p = 0, pleft = 0, pright = 0 ; pleft < nleft && pright < nright ; p++) { if (LG_lt_1 (Left_0, pleft, Right_0, pright)) { // S [p] = Left [pleft++] S_0 [p] = Left_0 [pleft] ; pleft++ ; } else { // S [p] = Right [pright++] S_0 [p] = Right_0 [pright] ; pright++ ; } } // either input is exhausted; copy the remaining list into S if (pleft < nleft) { int64_t nremaining = (nleft - pleft) ; memcpy (S_0 + p, Left_0 + pleft, nremaining * sizeof (int64_t)) ; } else if (pright < nright) { int64_t nremaining = (nright - pright) ; memcpy (S_0 + p, Right_0 + pright, nremaining * sizeof (int64_t)) ; } } //------------------------------------------------------------------------------ // LAGraph_Sort1: parallel mergesort //------------------------------------------------------------------------------ int LAGraph_Sort1 // sort array A of size n ( int64_t *LG_RESTRICT A_0, // size n array const int64_t n, int nthreads, // # of threads to use char *msg ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- LG_CLEAR_MSG ; int64_t *LG_RESTRICT W = NULL ; size_t W_size = 0 ; LG_CHECK (A_0 == NULL, -1, "A_0 is NULL") ; //-------------------------------------------------------------------------- // handle small problems with a single thread //-------------------------------------------------------------------------- if (nthreads <= 1 || n <= LG_BASECASE) { // sequential quicksort LG_qsort_1a (A_0, n) ; return (0) ; } //-------------------------------------------------------------------------- // determine # of tasks //-------------------------------------------------------------------------- // determine the number of levels to create, which must always be an // even number. The # of levels is chosen to ensure that the # of leaves // of the task tree is between 4*nthreads and 16*nthreads. // 2 to 4 threads: 4 levels, 16 qsort leaves // 5 to 16 threads: 6 levels, 64 qsort leaves // 17 to 64 threads: 8 levels, 256 qsort leaves // 65 to 256 threads: 10 levels, 1024 qsort leaves // 256 to 1024 threads: 12 levels, 4096 qsort leaves // ... int k = (int) (2 + 2 * ceil (log2 ((double) nthreads) / 2)) ; int ntasks = 1 << k ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- W = LAGraph_Malloc (n + 6*ntasks + 1, sizeof (int64_t), &W_size) ; LG_CHECK (W == NULL, -1, "out of memory") ; int64_t *T = W ; int64_t *LG_RESTRICT W_0 = T ; T += n ; int64_t *LG_RESTRICT L_task = T ; T += ntasks ; int64_t *LG_RESTRICT L_len = T ; T += ntasks ; int64_t *LG_RESTRICT R_task = T ; T += ntasks ; int64_t *LG_RESTRICT R_len = T ; T += ntasks ; int64_t *LG_RESTRICT S_task = T ; T += ntasks ; int64_t *LG_RESTRICT Slice = T ; T += (ntasks+1) ; //-------------------------------------------------------------------------- // partition and sort the leaves //-------------------------------------------------------------------------- LG_eslice (Slice, n, ntasks) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t leaf = Slice [tid] ; int64_t leafsize = Slice [tid+1] - leaf ; LG_qsort_1a (A_0 + leaf, leafsize) ; } //-------------------------------------------------------------------------- // merge each level //-------------------------------------------------------------------------- int nt = 1 ; for ( ; k >= 2 ; k -= 2) { //---------------------------------------------------------------------- // merge level k into level k-1, from A into W //---------------------------------------------------------------------- // TODO: skip k and k-1 for each group of 4 sublists of A if they are // already sorted with respect to each other. // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two A sublists into one W sublist LG_msort_1b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], A_0, Slice [tid], Slice [tid+nt], A_0, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; LG_msort_1b_merge ( W_0 + pS, A_0 + pL, nL, A_0 + pR, nR) ; } nt = 2*nt ; //---------------------------------------------------------------------- // merge level k-1 into level k-2, from W into A //---------------------------------------------------------------------- // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two W sublists into one A sublist LG_msort_1b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], W_0, Slice [tid], Slice [tid+nt], W_0, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; LG_msort_1b_merge ( A_0 + pS, W_0 + pL, nL, W_0 + pR, nR) ; } nt = 2*nt ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- LAGRAPH_FREE_ALL ; return (0) ; }
GB_unop__atan_fc64_fc64.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__atan_fc64_fc64 // op(A') function: GB_unop_tran__atan_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = catan (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 = catan (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] = catan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ATAN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__atan_fc64_fc64 ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catan (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__atan_fc64_fc64 ( 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
otbSampleAugmentation.h
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbSampleAugmentation_h #define otbSampleAugmentation_h #ifdef _OPENMP # include <omp.h> #endif #include <vector> #include <algorithm> #include <random> #include <ctime> #include <cassert> namespace otb { namespace sampleAugmentation { using SampleType = std::vector<double>; using SampleVectorType = std::vector<SampleType>; /** Estimate standard deviations of the components in one pass using Welford's algorithm */ SampleType EstimateStds(const SampleVectorType& samples) { const auto nbSamples = samples.size(); const auto nbComponents = samples[0].size(); SampleType stds(nbComponents, 0.0); SampleType means(nbComponents, 0.0); for(size_t i=0; i<nbSamples; ++i) { auto norm_factor = 1.0/(i+1); #ifdef _OPENMP #pragma omp parallel for #endif for(size_t j=0; j<nbComponents; ++j) { const auto mu = means[j]; const auto x = samples[i][j]; auto muNew = mu+(x-mu)*norm_factor; stds[j] += (x-mu)*(x-muNew); means[j] = muNew; } } #ifdef _OPENMP #pragma omp parallel for #endif for(size_t j=0; j<nbComponents; ++j) { stds[j] = std::sqrt(stds[j]/nbSamples); } return stds; } /** Create new samples by replicating input samples. We loop through * the input samples and add them to the new data set until nbSamples * are added. The elements of newSamples are removed before proceeding. */ void ReplicateSamples(const SampleVectorType& inSamples, const size_t nbSamples, SampleVectorType& newSamples) { newSamples.resize(nbSamples); size_t imod{0}; #ifdef _OPENMP #pragma omp parallel for #endif for(size_t i=0; i<nbSamples; ++i) { if (imod == inSamples.size()) imod = 0; newSamples[i] = inSamples[imod++]; } } /** Create new samples by adding noise to existing samples. Gaussian * noise is added to randomly selected samples. The standard deviation * of the noise added to each component is the same as the one of the * input variables divided by stdFactor (defaults to 10). The * elements of newSamples are removed before proceeding. */ void JitterSamples(const SampleVectorType& inSamples, const size_t nbSamples, SampleVectorType& newSamples, float stdFactor=10, const int seed = std::time(nullptr)) { newSamples.resize(nbSamples); const auto nbComponents = inSamples[0].size(); std::random_device rd; std::mt19937 gen(rd()); // The input samples are selected randomly with replacement std::srand(seed); // We use one gaussian distribution per component since they may // have different stds auto stds = EstimateStds(inSamples); std::vector<std::normal_distribution<double>> gaussDis(nbComponents); #ifdef _OPENMP #pragma omp parallel for #endif for(size_t i=0; i<nbComponents; ++i) gaussDis[i] = std::normal_distribution<double>{0.0, stds[i]/stdFactor}; for(size_t i=0; i<nbSamples; ++i) { newSamples[i] = inSamples[std::rand()%inSamples.size()]; #ifdef _OPENMP #pragma omp parallel for #endif for(size_t j=0; j<nbComponents; ++j) newSamples[i][j] += gaussDis[j](gen); } } struct NeighborType { size_t index; double distance; }; struct NeighborSorter { constexpr bool operator ()(const NeighborType& a, const NeighborType& b) const { return b.distance > a.distance; } }; double ComputeSquareDistance(const SampleType& x, const SampleType& y) { assert(x.size()==y.size()); double dist{0}; for(size_t i=0; i<x.size(); ++i) { dist += (x[i]-y[i])*(x[i]-y[i]); } return dist/(x.size()*x.size()); } using NNIndicesType = std::vector<NeighborType>; using NNVectorType = std::vector<NNIndicesType>; /** Returns the indices of the nearest neighbors for each input sample */ void FindKNNIndices(const SampleVectorType& inSamples, const size_t nbNeighbors, NNVectorType& nnVector) { const auto nbSamples = inSamples.size(); nnVector.resize(nbSamples); #ifdef _OPENMP #pragma omp parallel for #endif for(size_t sampleIdx=0; sampleIdx<nbSamples; ++sampleIdx) { NNIndicesType nns; for(size_t neighborIdx=0; neighborIdx<nbSamples; ++neighborIdx) { if(sampleIdx!=neighborIdx) nns.push_back({neighborIdx, ComputeSquareDistance(inSamples[sampleIdx], inSamples[neighborIdx])}); } std::partial_sort(nns.begin(), nns.begin()+nbNeighbors, nns.end(), NeighborSorter{}); nns.resize(nbNeighbors); nnVector[sampleIdx] = std::move(nns); } } /** Generate the new sample in the line linking s1 and s2 */ SampleType SmoteCombine(const SampleType& s1, const SampleType& s2, double position) { auto result = s1; for(size_t i=0; i<s1.size(); ++i) result[i] = s1[i]+(s2[i]-s1[i])*position; return result; } /** Create new samples using the SMOTE algorithm Chawla, N. V., Bowyer, K. W., Hall, L. O., & Kegelmeyer, W. P., Smote: synthetic minority over-sampling technique, Journal of artificial intelligence research, 16(), 321–357 (2002). http://dx.doi.org/10.1613/jair.953 */ void Smote(const SampleVectorType& inSamples, const size_t nbSamples, SampleVectorType& newSamples, const int nbNeighbors, const int seed = std::time(nullptr)) { newSamples.resize(nbSamples); NNVectorType nnVector; FindKNNIndices(inSamples, nbNeighbors, nnVector); // The input samples are selected randomly with replacement std::srand(seed); #ifdef _OPENMP #pragma omp parallel for #endif for(size_t i=0; i<nbSamples; ++i) { const auto sampleIdx = std::rand()%(inSamples.size()); const auto sample = inSamples[sampleIdx]; const auto neighborIdx = nnVector[sampleIdx][std::rand()%nbNeighbors].index; const auto neighbor = inSamples[neighborIdx]; newSamples[i] = SmoteCombine(sample, neighbor, std::rand()/double{RAND_MAX}); } } }//end namespaces sampleAugmentation }//end namespace otb #endif
backprop.c
/* libdeep - a library for deep learning Copyright (C) 2013-2017 Bob Mottram <bob@freedombone.net> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "backprop.h" /** * @brief Initialise a backprop neural net * @param net Backprop neural net object * @param no_of_inputs The number of input units * @param no_of_hiddens The number of units in each hidden layer * @param hidden_layers The number of hidden layers * @param no_of_outputs The number of output units * @param random_seed The random number generator seed * @returns zero on success */ int bp_init(bp * net, int no_of_inputs, int no_of_hiddens, int hidden_layers, int no_of_outputs, unsigned int * random_seed) { bp_neuron * n; net->learning_rate = 0.2f; net->noise = 0.0f; net->random_seed = *random_seed; net->backprop_error = DEEPLEARN_UNKNOWN_ERROR; net->backprop_error_average = DEEPLEARN_UNKNOWN_ERROR; net->backprop_error_total = DEEPLEARN_UNKNOWN_ERROR; net->itterations = 0; net->pruning_cycle = 0; net->pruning_rate = 0.1f; net->dropout_percent = 20; net->no_of_inputs = no_of_inputs; NEURON_ARRAY_ALLOC(net->inputs, no_of_inputs); if (!net->inputs) return -1; net->no_of_hiddens = no_of_hiddens; net->no_of_outputs = no_of_outputs; net->hidden_layers = hidden_layers; NEURON_LAYERS_ALLOC(net->hiddens, hidden_layers); if (!net->hiddens) return -2; COUNTDOWN(l, hidden_layers) { NEURON_ARRAY_ALLOC(net->hiddens[l], HIDDENS_IN_LAYER(net,l)); if (!net->hiddens[l]) return -3; } NEURON_ARRAY_ALLOC(net->outputs, no_of_outputs); if (!net->outputs) return -4; /* create inputs */ COUNTDOWN(i, net->no_of_inputs) { NEURONALLOC(net->inputs[i]); if (!net->inputs[i]) return -5; if (bp_neuron_init(net->inputs[i], 1, random_seed) != 0) return -6; } /* create hiddens */ COUNTUP(l, hidden_layers) { COUNTUP(i, HIDDENS_IN_LAYER(net,l)) { net->hiddens[l][i] = (bp_neuron*)malloc(sizeof(bp_neuron)); if (!net->hiddens[l][i]) return -7; n = net->hiddens[l][i]; if (l == 0) { if (bp_neuron_init(n, no_of_inputs, random_seed) != 0) return -8; /* connect to input layer */ COUNTDOWN(j, net->no_of_inputs) bp_neuron_add_connection(n, j, net->inputs[j]); } else { if (bp_neuron_init(n, HIDDENS_IN_LAYER(net,l-1), random_seed) != 0) return -9; /* connect to previous hidden layer */ COUNTDOWN(j, HIDDENS_IN_LAYER(net,l-1)) bp_neuron_add_connection(n, j, net->hiddens[l-1][j]); } } } /* create outputs */ COUNTDOWN(i, net->no_of_outputs) { NEURONALLOC(net->outputs[i]); if (!net->outputs[i]) return -10; n = net->outputs[i]; if (bp_neuron_init(n, HIDDENS_IN_LAYER(net,hidden_layers-1), random_seed) != 0) return -11; COUNTDOWN(j, HIDDENS_IN_LAYER(net,hidden_layers-1)) bp_neuron_add_connection(n, j, net->hiddens[hidden_layers-1][j]); } return 0; } /** * @brief Deallocate the memory for a backprop neural net object * @param net Backprop neural net object */ void bp_free(bp * net) { COUNTDOWN(i, net->no_of_inputs) { bp_neuron_free(net->inputs[i]); free(net->inputs[i]); net->inputs[i] = 0; } free(net->inputs); COUNTDOWN(l, net->hidden_layers) { COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) { bp_neuron_free(net->hiddens[l][i]); free(net->hiddens[l][i]); net->hiddens[l][i] = 0; } free(net->hiddens[l]); net->hiddens[l] = 0; } free(net->hiddens); COUNTDOWN(i, net->no_of_outputs) { bp_neuron_free(net->outputs[i]); free(net->outputs[i]); net->outputs[i] = 0; } free(net->outputs); } /** * @brief Propagates the current inputs through the layers of the network * @param net Backprop neural net object * @param learning Non-zero if learning */ void bp_feed_forward(bp * net, int learning) { unsigned int drop_percent = 0; if (learning != 0) drop_percent = (unsigned int)(net->dropout_percent*100); /* for each hidden layer */ COUNTUP(l, net->hidden_layers) { /* For each unit within the layer */ #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) bp_neuron_feedForward(net->hiddens[l][i], net->noise, drop_percent, &net->random_seed); } /* for each unit in the output layer */ COUNTDOWN(i, net->no_of_outputs) bp_neuron_feedForward(net->outputs[i], net->noise, drop_percent, &net->random_seed); } /** * @brief Propagates the current inputs through a given number of * layers of the network * @param net Backprop neural net object * @param layers The number of layers to propagate through */ void bp_feed_forward_layers(bp * net, int layers) { unsigned int drop_percent = (unsigned int)(net->dropout_percent*100); /* for each hidden layer */ COUNTUP(l, layers) { /* if this layer is a hidden layer */ if (l < net->hidden_layers) { /* For each unit within the layer */ #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) bp_neuron_feedForward(net->hiddens[l][i], net->noise, drop_percent, &net->random_seed); } else { /* For each unit within the output layer */ #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, net->no_of_outputs) bp_neuron_feedForward(net->outputs[i], net->noise, drop_percent, &net->random_seed); } } } /** * @brief back-propogate errors from the output layer towards the input layer * @param net Backprop neural net object */ void bp_backprop(bp * net, int current_hidden_layer) { int neuron_count=0; int start_hidden_layer = current_hidden_layer-1; float errorPercent=0; /* clear all previous backprop errors */ COUNTDOWN(i, net->no_of_inputs) net->inputs[i]->backprop_error = 0; /* for every hidden layer */ if (start_hidden_layer < 0) start_hidden_layer = 0; FOR(l, start_hidden_layer, net->hidden_layers) { /* For each unit within the layer */ COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) net->hiddens[l][i]->backprop_error = 0; } /* now back-propogate the error from the output units */ net->backprop_error_total = 0; /* for every output unit */ #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, net->no_of_outputs) { bp_neuron_backprop(net->outputs[i]); } COUNTDOWN(i, net->no_of_outputs) { /* update the total error which is used to assess network performance */ net->backprop_error_total += net->outputs[i]->backprop_error; errorPercent += fabs(net->outputs[i]->backprop_error); } neuron_count += net->no_of_outputs; /* convert summed error to an overall percentage */ errorPercent = errorPercent * 100 / (NEURON_RANGE*net->no_of_outputs); /* error on the output units */ net->backprop_error = fabs(net->backprop_error_total / net->no_of_outputs); /* update the running average */ if (net->backprop_error_average == DEEPLEARN_UNKNOWN_ERROR) { net->backprop_error_average = net->backprop_error; net->backprop_error_percent = errorPercent; } else { net->backprop_error_average = (net->backprop_error_average*0.999f) + (net->backprop_error*0.001f); net->backprop_error_percent = (net->backprop_error_percent*0.999f) + (errorPercent*0.001f); } /* back-propogate through the hidden layers */ for (int l = net->hidden_layers-1; l >= start_hidden_layer; l--) { /* for every unit in the hidden layer */ #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) { bp_neuron_backprop(net->hiddens[l][i]); } COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) { /* update the total error which is used to assess network performance */ net->backprop_error_total += net->hiddens[l][i]->backprop_error; } neuron_count += HIDDENS_IN_LAYER(net,l); } /* overall average error */ net->backprop_error_total = fabs(net->backprop_error_total / neuron_count); /* increment the number of training itterations */ if (net->itterations < UINT_MAX) net->itterations++; } /** * @brief Reprojects the input layer from a given hidden layer neuron * This is like feedforward in reverse, and allows you * to visualise what a hidden layer neuron is representing * @param layer The hidden layer within which the neuron resides * @param neuron_index The hidden layer index of the neuron to be reprojected */ void bp_reproject(bp * net, int layer, int neuron_index) { bp_neuron * n; /* clear all previous backprop errors */ COUNTDOWN(i, net->no_of_inputs) net->inputs[i]->value_reprojected = 0; /* for every hidden layer */ COUNTDOWN(l, layer) { /* For each unit within the layer */ COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) net->hiddens[l][i]->value_reprojected = 0; } /* set the neuron active */ n = net->hiddens[layer][neuron_index]; n->value_reprojected = NEURON_HIGH; bp_neuron_reproject(n); if (layer > 0) { /* apply the sigmoid function in the previous layer, as with feedforward */ COUNTDOWN(i, HIDDENS_IN_LAYER(net,layer-1)) { n = net->hiddens[layer-1][i]; n->value_reprojected = AF(n->value_reprojected); } } /* reproject through the hidden layers */ for (int l = layer-1; l > 0; l--) { /* for every unit in the hidden layer */ COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) bp_neuron_reproject(net->hiddens[l][i]); /* apply the sigmoid function in the previous layer, as with feedforward */ COUNTDOWN(i, HIDDENS_IN_LAYER(net,l-1)) { n = net->hiddens[l-1][i]; n->value_reprojected = AF(n->value_reprojected); } } } /** * @brief Adjust connection weights and bias values * @param net Backprop neural net object * @param current_hidden_layer The hidden layer currently being trained */ void bp_learn(bp * net, int current_hidden_layer) { int start_hidden_layer = current_hidden_layer-1; /* for each hidden layers */ if (start_hidden_layer < 0) start_hidden_layer = 0; FOR(l, start_hidden_layer, net->hidden_layers) { #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) bp_neuron_learn(net->hiddens[l][i], net->learning_rate); } #pragma omp parallel for schedule(static) num_threads(DEEPLEARN_THREADS) COUNTDOWN(i, net->no_of_outputs) bp_neuron_learn(net->outputs[i], net->learning_rate); /* perform periodic pruning of weights so that there is a cycle of growth and pruning */ if (net->pruning_cycle != 0) { if (net->itterations % net->pruning_cycle == 0) { if (net->itterations > 0) { bp_prune_weights(net, net->pruning_rate); } } } } /** * @brief Set the value of an input * @param net Backprop neural net object * @param index The index number of the input unit * @param value The value to set the unit to in the range 0.0 to 1.0 */ void bp_set_input(bp * net, int index, float value) { net->inputs[index]->value = value; } /** * @brief Normalises the input values * @param net Backprop neural net object */ void bp_normalise_inputs(bp * net) { float max = 0, min = 1; COUNTDOWN(i, net->no_of_inputs) { if (net->inputs[i]->value > max) max = net->inputs[i]->value; if (net->inputs[i]->value < min) min = net->inputs[i]->value; } float range = max - min; if (range > 0.00001f) { COUNTDOWN(i, net->no_of_inputs) net->inputs[i]->value = NEURON_LOW + ((net->inputs[i]->value-min)*NEURON_RANGE/range); } } /** * @brief Sets the inputs to a text string * @param net Backprop neural net object * @param text The text string */ void bp_set_input_text(bp * net, char * text) { enc_text_to_binary(text, net->inputs, net->no_of_inputs, 0, strlen(text)); } /** * @brief Set the inputs of the network from a patch within an image. * It is assumed that the image is mono (1 byte per pixel) * @param net Backprop neural net object * @param img Array storing the image * @param image_width Width of the image in pixels * @param image_height Height of the image in pixels * @param tx Top left x coordinate of the patch within the image * @param ty Top left y coordinate of the patch within the image * @returns zero on success */ int bp_inputs_from_image_patch(bp * net, unsigned char img[], int image_width, int image_height, int tx, int ty) { int i = 0, idx; /* The patch size is calculated from the number of inputs of the neural net. It's assumed to be square. */ int patch_size = (int)sqrt(net->no_of_inputs); /* make sure that the patch fits within the number of inputs */ if (patch_size*patch_size > net->no_of_inputs) return 1; /* set the inputs from the patch */ FOR(py, ty, ty+patch_size) { if (py >= image_height) break; FOR(px, tx, tx+patch_size) { if (px >= image_width) break; /* array index within the image */ idx = (py*image_width) + px; /* set the input value within the range */ bp_set_input(net, i, NEURON_LOW + (img[idx]*NEURON_RANGE/255.0f)); i++; } } return 0; } /** * @brief Set the inputs of the network from an image. * It is assumed that the image is mono (1 byte per pixel) * @param net Backprop neural net object * @param img Array storing the image * @param image_width Width of the image in pixels * @param image_height Height of the image in pixels * @returns zero on success */ int bp_inputs_from_image(bp * net, unsigned char img[], int image_width, int image_height) { /* check that the number of inputs is the same as the number of pixels */ if (net->no_of_inputs != image_width*image_height) return 1; /* set the input values within the range */ COUNTDOWN(i, image_width*image_height) bp_set_input(net, i, NEURON_LOW + (img[i]*NEURON_RANGE/255.0f)); return 0; } /** * @brief Plots weight matrices within an image * @param net Backprop neural net object * @param filename Filename of the image to save as * @param image_width Width of the image in pixels * @param image_height Height of the image in pixels * @param input_image_width When displaying all inputs as an image this is the number of inputs across. Set this to zero for the inputs image to be square. */ int bp_plot_weights(bp * net, char * filename, int image_width, int image_height, int input_image_width) { int neurons_x, neurons_y, ty, by, h, ix, iy; int wx, wy, inputs_x, inputs_y, n, i, unit, no_of_neurons; int no_of_weights,wdth, max_unit; float neuronx, neurony, dw, db, min_bias, max_bias; float min_activation, max_activation, da; bp_neuron ** neurons, * curr_neuron; unsigned char * img; /* allocate memory for the image */ UCHARALLOC(img, image_width*image_height*3); if (!img) return -1; /* clear the image with a white background */ memset((void*)img, '\255', image_width*image_height*3*sizeof(unsigned char)); /* dimension of the neurons matrix for each layer */ neurons_x = (int)sqrt(net->no_of_hiddens); neurons_y = (net->no_of_hiddens/neurons_x); /* dimensions of the weight matrix */ if (input_image_width <= 0) inputs_x = (int)sqrt(net->no_of_inputs); else inputs_x = input_image_width; inputs_y = (net->no_of_inputs/inputs_x); no_of_weights = net->no_of_inputs; /* plot the inputs */ ty = 0; by = image_height/(net->hidden_layers+3); h = (by-ty)*95/100; wdth = h; if (wdth>=image_width) wdth=image_width; COUNTUP(y, h) { iy = y*inputs_y/h; COUNTUP(x, wdth) { ix = x*inputs_x/wdth; unit = (iy*inputs_x) + ix; if (unit < net->no_of_inputs) { n = (y*image_width + x)*3; img[n] = (unsigned char)(net->inputs[unit]->value*255); img[n+1] = img[n]; img[n+2] = img[n]; } } } COUNTUP(layer, net->hidden_layers+1) { /* vertical top and bottom coordinates */ ty = (layer+1)*image_height/(net->hidden_layers+3); by = (layer+2)*image_height/(net->hidden_layers+3); h = (by-ty)*95/100; /* reset ranges */ min_bias = 9999999.0f; max_bias = -9999999.0f; min_activation = 9999999.0f; max_activation = -9999999.0f; /* number of patches across and down for the final layer */ if (layer == net->hidden_layers) { neurons_x = (int)sqrt(net->no_of_outputs); neurons_y = (net->no_of_outputs/neurons_x); neurons = net->outputs; no_of_neurons = net->no_of_outputs; max_unit = net->no_of_outputs; } else { neurons_x = (int)sqrt(HIDDENS_IN_LAYER(net,layer)); neurons_y = (HIDDENS_IN_LAYER(net,layer)/neurons_x); neurons = net->hiddens[layer]; no_of_neurons = HIDDENS_IN_LAYER(net,layer); max_unit = HIDDENS_IN_LAYER(net,layer); } /* get the bias range within this layer */ COUNTUP(y, max_unit) { if (neurons[y]->bias < min_bias) min_bias = neurons[y]->bias; if (neurons[y]->bias > max_bias) max_bias = neurons[y]->bias; if (neurons[y]->value < min_activation) min_activation = neurons[y]->value; if (neurons[y]->value > max_activation) max_activation = neurons[y]->value; } /* update ranges */ db = max_bias - min_bias; da = max_activation - min_activation; /* for every pixel within the region */ FOR(y, ty, by) { neurony = (y-ty)*neurons_y/(float)h; /* y coordinate within the weights */ wy = (neurony - (int)neurony)*inputs_y; COUNTUP(x, image_width) { neuronx = x*neurons_x/(float)image_width; /* x coordinate within the weights */ wx = (neuronx - (int)neuronx)*inputs_x; /* coordinate within the image */ n = ((y * image_width) + x)*3; /* weight index */ i = (wy*inputs_x) + wx; if (i < no_of_weights) { /* neuron index */ unit = ((int)neurony*neurons_x) + (int)neuronx; if (unit < no_of_neurons) { curr_neuron = neurons[unit]; dw = curr_neuron->max_weight - curr_neuron->min_weight; if (dw > 0.0001f) { img[n] = (int)((curr_neuron->weights[i] - curr_neuron->min_weight)*255/dw); img[n+1] = (int)((curr_neuron->bias - min_bias)*255/db); img[n+2] = (int)((curr_neuron->value - min_activation)* 255/da); } else { img[n] = (int)(curr_neuron->weights[i]*255); img[n+1] = img[n]; img[n+2] = img[n]; } } } } } if (layer < net->hidden_layers) { /* dimensions of the weight matrix for the next layer */ inputs_x = (int)sqrt(HIDDENS_IN_LAYER(net,layer)); inputs_y = (HIDDENS_IN_LAYER(net,layer)/inputs_x); no_of_weights = HIDDENS_IN_LAYER(net,layer); } } ty = (net->hidden_layers+2)*image_height/(net->hidden_layers+3); by = (net->hidden_layers+3)*image_height/(net->hidden_layers+3); h = (by-ty)*95/100; inputs_x = (int)sqrt(net->no_of_outputs); inputs_y = (net->no_of_outputs/inputs_x); wdth = h; if (wdth >= image_width) wdth = image_width; COUNTUP(y, h) { iy = y*inputs_y/h; COUNTUP(x, wdth) { ix = x*inputs_x/wdth; unit = (iy*inputs_x) + ix; if (unit < net->no_of_outputs) { n = ((ty+y)*image_width + x)*3; img[n] = (unsigned char)(net->outputs[unit]->value*255); img[n+1] = img[n]; img[n+2] = img[n]; } } } /* write the image to file */ deeplearn_write_png_file(filename, (unsigned int)image_width, (unsigned int)image_height, 24, img); /* free the image memory */ free(img); return 0; } /** * @brief Returns the value of one of the input units * @param net Backprop neural net object * @param index Index of the input unit * @return value in the range 0.0 to 1.0 */ float bp_get_input(bp * net, int index) { return net->inputs[index]->value; } /** * @brief Sets the value of one of the output units * @param net Backprop neural net object * @param index Index of the output unit * @param value The value to set the output to in the range 0.0 to 1.0 */ void bp_set_output(bp * net, int index, float value) { net->outputs[index]->desired_value = value; } /** * @brief Gets the value of one of the hidden units * @param net Backprop neural net object * @param layer Index number of the hidden layer * @param index Index of the unit within the given hidden layer * @return value in the range 0.0 to 1.0 */ float bp_get_hidden(bp * net, int layer, int index) { return net->hiddens[layer][index]->value; } /** * @brief Gets the value of one of the output units * @param net Backprop neural net object * @param index Index of the unit within the output layer * @return value in the range 0.0 to 1.0 */ float bp_get_output(bp * net, int index) { return net->outputs[index]->value; } /** * @brief Gets the desired value of one of the output units * @param net Backprop neural net object * @param index Index of the unit within the output layer * @return Desired value in the range 0.0 to 1.0 */ float bp_get_desired(bp * net, int index) { return net->outputs[index]->desired_value; } /** * @brief Exclusion flags indicate that a unit has temporarily dropped out. * This clears the all the exclusion flags * @param net Backprop neural net object */ static void bp_clear_dropouts(bp * net) { /* if no dropouts then don't continue */ if (net->dropout_percent == 0) return; /* for every hidden layer */ COUNTDOWN(l, net->hidden_layers) { COUNTDOWN(i, HIDDENS_IN_LAYER(net,l)) net->hiddens[l][i]->excluded = 0; } } /** * @brief Returns the average weight change for a given layer * @param net Backprop neural net object * @param layer_index Index of the layer * @returns average weight change */ float bp_weight_gradient_mean(bp * net, int layer_index) { float total_weight_change = 0; int no_of_neurons = HIDDENS_IN_LAYER(net, layer_index); int inputs = net->hiddens[layer_index][0]->no_of_inputs; COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[layer_index][i]; COUNTDOWN(w, inputs) total_weight_change += fabs(n->last_weight_change[w]); } return total_weight_change * 10000000 / (float)(inputs * no_of_neurons); } /** * @brief Returns a weight histogram with values in the range 0 -> 1000 * @param net Backprop neural net object * @param histogram Histogram array * @param buckets Number of histogram buckets * @param max_value The maximum weight magnitude */ void bp_weight_histogram(bp * net, unsigned int histogram[], int buckets, float max_value) { UINTCLEAR(histogram, buckets); COUNTDOWN(l, net->hidden_layers) { int no_of_neurons = HIDDENS_IN_LAYER(net, l); int inputs = net->hiddens[l][0]->no_of_inputs; COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[l][i]; COUNTDOWN(w, inputs) { float value = fabs(n->weights[w]); if (value < max_value) { histogram[(int)(value * buckets / max_value)]++; } } } } /* normalize */ unsigned int max = 1; COUNTDOWN(i, buckets) { if (histogram[i] > max) max = histogram[i]; } COUNTDOWN(i, buckets) { histogram[i] = histogram[i] * 1000 / max; } } /** * @brief Sets small weights to zero * @param net Backprop neural net object * @param threshold Pruning threshold in the range 0.0 -> 1.0 * @returns The percent of weights pruned */ int bp_prune_weights(bp * net, float threshold) { float mean = 0; unsigned int hits = 0; unsigned int pruned = 0; COUNTDOWN(l, net->hidden_layers) { int no_of_neurons = HIDDENS_IN_LAYER(net, l); int inputs = net->hiddens[l][0]->no_of_inputs; hits += no_of_neurons*inputs; COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[l][i]; COUNTDOWN(w, inputs) { mean += fabs(n->weights[w]); } } } COUNTDOWN(i, net->no_of_outputs) { bp_neuron * n = net->outputs[i]; COUNTDOWN(w, n->no_of_inputs) { mean += fabs(n->weights[w]); hits++; } } if (hits == 0) return 0; mean /= (float)hits; threshold = mean * threshold; /* set weights to zero if they are below the pruning threshold */ COUNTDOWN(l, net->hidden_layers) { int no_of_neurons = HIDDENS_IN_LAYER(net, l); int inputs = net->hiddens[l][0]->no_of_inputs; COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[l][i]; COUNTDOWN(w, inputs) { if (fabs(n->weights[w]) < threshold) { n->weights[w] = 0; pruned++; } } } } COUNTDOWN(i, net->no_of_outputs) { bp_neuron * n = net->outputs[i]; COUNTDOWN(w, n->no_of_inputs) { if (fabs(n->weights[w]) < threshold) { n->weights[w] = 0; pruned++; } } } return (int)(pruned * 100 / hits); } /** * @brief Returns the standard deviation of the weight change for a given layer * @param net Backprop neural net object * @param layer_index Index of the layer * @returns standard deviation of weight change */ float bp_weight_gradient_std(bp * net, int layer_index) { float mean_weight_change = 0; float total_deviation = 0; int no_of_neurons = HIDDENS_IN_LAYER(net, layer_index); int inputs = net->hiddens[layer_index][0]->no_of_inputs; /* calculate the average weight magnitude */ COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[layer_index][i]; COUNTDOWN(w, inputs) { mean_weight_change += n->last_weight_change[w]; } } mean_weight_change /= (no_of_neurons * inputs); /* sum of percentage deviation from the average weight magnitude */ if (fabs(mean_weight_change) > 0.0000000001f) { COUNTDOWN(i, no_of_neurons) { bp_neuron * n = net->hiddens[layer_index][i]; COUNTDOWN(w, inputs) { total_deviation += fabs((n->last_weight_change[w] - mean_weight_change)/mean_weight_change); } } } return total_deviation * 100 / (no_of_neurons * inputs); } /** * @brief Randomly sets exclusion flags to cause units to drop out * @param net Backprop neural net object */ static void bp_dropouts(bp * net) { int no_of_dropouts, hidden_units=0; if (net->dropout_percent == 0) return; /* total number of hidden units */ COUNTDOWN(l, net->hidden_layers) hidden_units += HIDDENS_IN_LAYER(net,l); /* total number of dropouts */ no_of_dropouts = net->dropout_percent*hidden_units/100; /* set the exclusion flags */ COUNTDOWN(n, no_of_dropouts) { int l = rand_num(&net->random_seed)%net->hidden_layers; int i = rand_num(&net->random_seed)%HIDDENS_IN_LAYER(net,l); net->hiddens[l][i]->excluded = 1; } } /** * @brief Update the neural net during training * @param net Backprop neural net object */ void bp_update(bp * net, int current_hidden_layer) { bp_dropouts(net); bp_feed_forward(net, 1); bp_backprop(net, current_hidden_layer); bp_learn(net, current_hidden_layer); bp_clear_dropouts(net); } /** * @brief Save a neural network to file * @brief fp File pointer * @param net Backprop neural net object * @return zero on success */ int bp_save(FILE * fp, bp * net) { if (UINTWRITE(net->itterations) == 0) return -1; if (UINTWRITE(net->pruning_cycle) == 0) return -2; if (FLOATWRITE(net->pruning_rate) == 0) return -3; if (INTWRITE(net->no_of_inputs) == 0) return -4; if (INTWRITE(net->no_of_hiddens) == 0) return -5; if (INTWRITE(net->no_of_outputs) == 0) return -6; if (INTWRITE(net->hidden_layers) == 0) return -7; if (FLOATWRITE(net->learning_rate) == 0) return -8; if (FLOATWRITE(net->noise) == 0) return -9; if (FLOATWRITE(net->backprop_error_average) == 0) return -10; if (FLOATWRITE(net->dropout_percent) == 0) return -11; if (UINTWRITE(net->random_seed) == 0) return -12; COUNTUP(l, net->hidden_layers) { COUNTUP(i, HIDDENS_IN_LAYER(net,l)) bp_neuron_save(fp,net->hiddens[l][i]); } COUNTUP(i, net->no_of_outputs) bp_neuron_save(fp,net->outputs[i]); return 0; } /** * @brief Load a network from file * @brief fp File pointer * @param net Backprop neural net object * @returns zero on success */ int bp_load(FILE * fp, bp * net) { int no_of_inputs=0, no_of_hiddens=0, no_of_outputs=0; int hidden_layers=0; float learning_rate=0, noise=0, backprop_error_average=0; float dropout_percent=0,pruning_rate=0; unsigned int itterations=0; unsigned int pruning_cycle=0; unsigned int random_seed=0; if (UINTREAD(itterations) == 0) return -1; if (UINTREAD(pruning_cycle) == 0) return -2; if (FLOATREAD(pruning_rate) == 0) return -3; if (INTREAD(no_of_inputs) == 0) return -4; if (INTREAD(no_of_hiddens) == 0) return -5; if (INTREAD(no_of_outputs) == 0) return -6; if (INTREAD(hidden_layers) == 0) return -7; if (FLOATREAD(learning_rate) == 0) return -8; if (FLOATREAD(noise) == 0) return -9; if (FLOATREAD(backprop_error_average) == 0) return -10; if (FLOATREAD(dropout_percent) == 0) return -11; if (UINTREAD(random_seed) == 0) return -12; if (bp_init(net, no_of_inputs, no_of_hiddens, hidden_layers, no_of_outputs, &random_seed) != 0) return -13; COUNTUP(l, net->hidden_layers) { COUNTUP(i, HIDDENS_IN_LAYER(net,l)) { if (bp_neuron_load(fp,net->hiddens[l][i]) != 0) return -14; } } COUNTUP(i, net->no_of_outputs) { if (bp_neuron_load(fp,net->outputs[i]) != 0) return -15; } net->learning_rate = learning_rate; net->noise = noise; net->backprop_error_average = backprop_error_average; net->backprop_error = backprop_error_average; net->backprop_error_total = backprop_error_average; net->itterations = itterations; net->dropout_percent = dropout_percent; net->pruning_cycle = pruning_cycle; net->pruning_rate = pruning_rate; return 0; } /** * @brief compares two networks and returns a greater than * zero value if they are the same * @param net1 The first backprop neural net object * @param net2 The second backprop neural net object */ int bp_compare(bp * net1, bp * net2) { int retval; if (net1->no_of_inputs != net2->no_of_inputs) return -1; if (net1->no_of_hiddens != net2->no_of_hiddens) return -2; if (net1->no_of_outputs != net2->no_of_outputs) return -3; if (net1->hidden_layers != net2->hidden_layers) return -4; if (net1->learning_rate != net2->learning_rate) return -5; if (net1->pruning_cycle != net2->pruning_cycle) return -6; if (net1->pruning_rate != net2->pruning_rate) return -7; if (net1->noise != net2->noise) return -8; COUNTDOWN(l, net1->hidden_layers) { COUNTDOWN(i, HIDDENS_IN_LAYER(net1,l)) { retval = bp_neuron_compare(net1->hiddens[l][i], net2->hiddens[l][i]); if (retval == 0) return -9; } } COUNTDOWN(i, net1->no_of_outputs) { retval = bp_neuron_compare(net1->outputs[i], net2->outputs[i]); if (retval == 0) return -10; } if (net1->itterations != net2->itterations) return -11; if (net1->backprop_error_average != net2->backprop_error_average) return -12; if (net1->dropout_percent!= net2->dropout_percent) return -13; return 1; } /** * @brief Extract the classification string from the filename. * This assumes a filename of the type class.instance.extension * @param filename The filename to examine * @param classification The returned classification */ void bp_get_classification_from_filename(char * filename, char * classification) { int j, start=0; /* start with an empty classification string */ classification[0] = 0; /* find the last separator */ COUNTUP(i, strlen(filename)) { if (filename[i] == '/') start = i+1; } /* find the first full stop */ for (j = start; j < strlen(filename); j++) { if ((filename[j] == '.') || (filename[j] == '-') || (filename[j] == '_')) break; classification[j-start] = filename[j]; } /* add a string terminator */ classification[j-start] = 0; } /** * @brief Takes a set of classification text descriptions (labels) for * each instance within a training or test set and produces an * array of classification numbers corresponding to the text * descriptions. It's easier for the system to deal with * classification numbers rather than text descriptions. * @param no_of_instances The number of instances in the training or test set * @param instance_classification Text Description for each instance * @param numbers Array of numbers corresponding to each instance */ int bp_classifications_to_numbers(int no_of_instances, char ** instance_classification, int * numbers) { int j; int unique_ctr = 0; char ** unique_classification; /* allocate memory for a list of unique descriptions (labels) */ CHARPTRALLOC(unique_classification, no_of_instances); if (!unique_classification) return -1; /* create a list of unique classification names */ COUNTUP(i, no_of_instances) { /* for every class number assigned so far */ for (j = 0; j < unique_ctr; j++) { /* is this instance description (label) the same as a previous instance description ? */ if (strcmp(instance_classification[i], unique_classification[j])==0) { /* assign the same class number and finish the search */ numbers[i] = j; break; } } /* if this instance has a description which has not been used before */ if (j == unique_ctr) { /* store the description */ CHARALLOC(unique_classification[unique_ctr], 1+strlen(instance_classification[i])); if (!unique_classification[unique_ctr]) { COUNTDOWN(i, unique_ctr) free(unique_classification[i]); free(unique_classification); return -2; } sprintf(unique_classification[unique_ctr], "%s", instance_classification[i]); /* store the classification number */ numbers[i] = unique_ctr; /* increment the number of classes */ unique_ctr++; } } /* free memory which was used to store descriptions */ COUNTDOWN(i, unique_ctr) free(unique_classification[i]); free(unique_classification); return 0; }
semi_interp.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_struct_ls.h" /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ typedef struct { hypre_StructMatrix *P; HYPRE_Int P_stored_as_transpose; hypre_ComputePkg *compute_pkg; hypre_Index cindex; hypre_Index findex; hypre_Index stride; HYPRE_Int time_index; } hypre_SemiInterpData; /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void * hypre_SemiInterpCreate( ) { hypre_SemiInterpData *interp_data; interp_data = hypre_CTAlloc(hypre_SemiInterpData, 1); (interp_data -> time_index) = hypre_InitializeTiming("SemiInterp"); return (void *) interp_data; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SemiInterpSetup( void *interp_vdata, hypre_StructMatrix *P, HYPRE_Int P_stored_as_transpose, hypre_StructVector *xc, hypre_StructVector *e, hypre_Index cindex, hypre_Index findex, hypre_Index stride ) { hypre_SemiInterpData *interp_data = (hypre_SemiInterpData *)interp_vdata; hypre_StructGrid *grid; hypre_StructStencil *stencil; hypre_ComputeInfo *compute_info; hypre_ComputePkg *compute_pkg; /*---------------------------------------------------------- * Set up the compute package *----------------------------------------------------------*/ grid = hypre_StructVectorGrid(e); stencil = hypre_StructMatrixStencil(P); hypre_CreateComputeInfo(grid, stencil, &compute_info); hypre_ComputeInfoProjectSend(compute_info, cindex, stride); hypre_ComputeInfoProjectRecv(compute_info, cindex, stride); hypre_ComputeInfoProjectComp(compute_info, findex, stride); hypre_ComputePkgCreate(compute_info, hypre_StructVectorDataSpace(e), 1, grid, &compute_pkg); /*---------------------------------------------------------- * Set up the interp data structure *----------------------------------------------------------*/ (interp_data -> P) = hypre_StructMatrixRef(P); (interp_data -> P_stored_as_transpose) = P_stored_as_transpose; (interp_data -> compute_pkg) = compute_pkg; hypre_CopyIndex(cindex, (interp_data -> cindex)); hypre_CopyIndex(findex, (interp_data -> findex)); hypre_CopyIndex(stride, (interp_data -> stride)); return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SemiInterp( void *interp_vdata, hypre_StructMatrix *P, hypre_StructVector *xc, hypre_StructVector *e ) { hypre_SemiInterpData *interp_data = (hypre_SemiInterpData *)interp_vdata; HYPRE_Int P_stored_as_transpose; hypre_ComputePkg *compute_pkg; hypre_IndexRef cindex; hypre_IndexRef findex; hypre_IndexRef stride; hypre_StructGrid *fgrid; HYPRE_Int *fgrid_ids; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; HYPRE_Int *cgrid_ids; hypre_CommHandle *comm_handle; hypre_BoxArrayArray *compute_box_aa; hypre_BoxArray *compute_box_a; hypre_Box *compute_box; hypre_Box *P_dbox; hypre_Box *xc_dbox; hypre_Box *e_dbox; HYPRE_Int Pi; HYPRE_Int xci; HYPRE_Int ei; HYPRE_Int constant_coefficient; HYPRE_Real *Pp0, *Pp1; HYPRE_Real *xcp; HYPRE_Real *ep, *ep0, *ep1; hypre_Index loop_size; hypre_Index start; hypre_Index startc; hypre_Index stridec; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int compute_i, fi, ci, j; /*----------------------------------------------------------------------- * Initialize some things *-----------------------------------------------------------------------*/ hypre_BeginTiming(interp_data -> time_index); P_stored_as_transpose = (interp_data -> P_stored_as_transpose); compute_pkg = (interp_data -> compute_pkg); cindex = (interp_data -> cindex); findex = (interp_data -> findex); stride = (interp_data -> stride); stencil = hypre_StructMatrixStencil(P); stencil_shape = hypre_StructStencilShape(stencil); constant_coefficient = hypre_StructMatrixConstantCoefficient(P); hypre_assert( constant_coefficient==0 || constant_coefficient==1 ); /* ... constant_coefficient==2 for P shouldn't happen, see hypre_PFMGCreateInterpOp in pfmg_setup_interp.c */ if (constant_coefficient) hypre_StructVectorClearBoundGhostValues(e, 0); hypre_SetIndex3(stridec, 1, 1, 1); /*----------------------------------------------------------------------- * Compute e at coarse points (injection) *-----------------------------------------------------------------------*/ fgrid = hypre_StructVectorGrid(e); fgrid_ids = hypre_StructGridIDs(fgrid); cgrid = hypre_StructVectorGrid(xc); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_ids = hypre_StructGridIDs(cgrid); fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } compute_box = hypre_BoxArrayBox(cgrid_boxes, ci); hypre_CopyIndex(hypre_BoxIMin(compute_box), startc); hypre_StructMapCoarseToFine(startc, cindex, stride, start); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), fi); xc_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(xc), ci); ep = hypre_StructVectorBoxData(e, fi); xcp = hypre_StructVectorBoxData(xc, ci); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(P), loop_size, e_dbox, start, stride, ei, xc_dbox, startc, stridec, xci); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,xci) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(ei, xci) { ep[ei] = xcp[xci]; } hypre_BoxLoop2End(ei, xci); } /*----------------------------------------------------------------------- * Compute e at fine points *-----------------------------------------------------------------------*/ for (compute_i = 0; compute_i < 2; compute_i++) { switch(compute_i) { case 0: { ep = hypre_StructVectorData(e); hypre_InitializeIndtComputations(compute_pkg, ep, &comm_handle); compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg); } break; case 1: { hypre_FinalizeIndtComputations(comm_handle); compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg); } break; } hypre_ForBoxArrayI(fi, compute_box_aa) { compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), fi); if (P_stored_as_transpose) { if ( constant_coefficient ) { Pp0 = hypre_StructMatrixBoxData(P, fi, 1); Pp1 = hypre_StructMatrixBoxData(P, fi, 0) - hypre_CCBoxOffsetDistance(P_dbox, stencil_shape[0]); } else { Pp0 = hypre_StructMatrixBoxData(P, fi, 1); Pp1 = hypre_StructMatrixBoxData(P, fi, 0) - hypre_BoxOffsetDistance(P_dbox, stencil_shape[0]); } } else { Pp0 = hypre_StructMatrixBoxData(P, fi, 0); Pp1 = hypre_StructMatrixBoxData(P, fi, 1); } ep = hypre_StructVectorBoxData(e, fi); ep0 = ep + hypre_BoxOffsetDistance(e_dbox, stencil_shape[0]); ep1 = ep + hypre_BoxOffsetDistance(e_dbox, stencil_shape[1]); hypre_ForBoxI(j, compute_box_a) { compute_box = hypre_BoxArrayBox(compute_box_a, j); hypre_CopyIndex(hypre_BoxIMin(compute_box), start); hypre_StructMapFineToCoarse(start, findex, stride, startc); hypre_BoxGetStrideSize(compute_box, stride, loop_size); if ( constant_coefficient ) { Pi = hypre_CCBoxIndexRank( P_dbox, startc ); hypre_BoxLoop1Begin(hypre_StructMatrixNDim(P), loop_size, e_dbox, start, stride, ei); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop1For(ei) { ep[ei] = (Pp0[Pi] * ep0[ei] + Pp1[Pi] * ep1[ei]); } hypre_BoxLoop1End(ei); } else { hypre_BoxLoop2Begin(hypre_StructMatrixNDim(P), loop_size, P_dbox, startc, stridec, Pi, e_dbox, start, stride, ei); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,Pi,ei) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(Pi, ei) { ep[ei] = (Pp0[Pi] * ep0[ei] + Pp1[Pi] * ep1[ei]); } hypre_BoxLoop2End(Pi, ei); } } } } /*----------------------------------------------------------------------- * Return *-----------------------------------------------------------------------*/ hypre_IncFLOPCount(3*hypre_StructVectorGlobalSize(xc)); hypre_EndTiming(interp_data -> time_index); return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SemiInterpDestroy( void *interp_vdata ) { hypre_SemiInterpData *interp_data = (hypre_SemiInterpData *)interp_vdata; if (interp_data) { hypre_StructMatrixDestroy(interp_data -> P); hypre_ComputePkgDestroy(interp_data -> compute_pkg); hypre_FinalizeTiming(interp_data -> time_index); hypre_TFree(interp_data); } return hypre_error_flag; }
comparisonlib.h
#include "omp.h" #include <cstdio> #include <iostream> #include <numeric> #include <random> #include <CL/sycl.hpp> using namespace sycl; #include <chrono> #ifdef NOGPU static queue Q(cpu_selector{}); #else static queue Q(gpu_selector{}); #endif void flux( const double * __restrict__ Q, // Q[5+0], int normal, double * __restrict__ F // F[5], ) { constexpr double gamma = 1.4; const double irho = 1./Q[0]; #if Dimensions==3 const double p = (gamma-1) * (Q[4] - 0.5*irho*(Q[1]*Q[1]+Q[2]*Q[2]+Q[3]*Q[3])); #else const double p = (gamma-1) * (Q[4] - 0.5*irho*(Q[1]*Q[1]+Q[2]*Q[2])); #endif const double coeff = irho*Q[normal+1]; F[0] = coeff*Q[0]; F[1] = coeff*Q[1]; F[2] = coeff*Q[2]; F[3] = coeff*Q[3]; F[4] = coeff*Q[4]; F[normal+1] += p; F[4] += coeff*p; } double maxEigenvalue( const double * __restrict__ Q, int normal ) { constexpr double gamma = 1.4; const double irho = 1./Q[0]; #if Dimensions==3 const double p = (gamma-1) * (Q[4] - 0.5*irho*(Q[1]*Q[1]+Q[2]*Q[2]+Q[3]*Q[3])); #else const double p = (gamma-1) * (Q[4] - 0.5*irho*(Q[1]*Q[1]+Q[2]*Q[2])); #endif const double u_n = Q[normal + 1] * irho; const double c = std::sqrt(gamma * p * irho); double result = std::max( std::abs(u_n - c), std::abs(u_n + c) ); return result; } // 2D std::tuple<int, int> glob2loc(const int g, const int J) { return std::make_tuple(g/J,g%J); } // 3D std::tuple<int, int, int> glob2loc(const int g, const int J, const int K) { int i = g/J/K; return std::make_tuple(i, (g-i*J*K)/J, g%K); } template< int numVPAIP, int unknowns, int aux > void defaultcomputeparallel(const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout) { const size_t NPT=20000; #pragma omp parallel for collapse(4) for (int pidx=0;pidx<NPT;pidx++) for (int y=0; y < numVPAIP; y++) for (int x=0; x < numVPAIP; x++) { for (int i=0; i<unknowns+aux; i++) { double *reconstructedPatch = Qin + sourcePatchSize*pidx; int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; } } } template< int numVPAIP, int unknowns, int aux, int ncollapse > void computeparallelgpudist(const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout) { const size_t NPT=20000; #pragma omp target map(from:Qout[0:NPT*destPatchSize]) { #pragma omp teams distribute for (int pidx=0;pidx<NPT;pidx++) { #pragma omp parallel for collapse(ncollapse) for (int y=0; y < numVPAIP; y++) for (int x=0; x < numVPAIP; x++) for (int i=0; i<unknowns+aux; i++) { double *reconstructedPatch = Qin + sourcePatchSize*pidx; int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; } } } } // We like this one as it is fast on cpu and gpu template< size_t NPT, int numVPAIP, int unknowns, int aux > void fcompute3(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm, const size_t GX, const size_t GY, const size_t GZ) { Q.submit([&](handler &cgh) { cgh.parallel_for(nd_range<3>{{NPT, numVPAIP, numVPAIP}, {GX, GY, GZ}}, [=](nd_item<3> item) { const size_t pidx=item.get_global_id(0);//[0]; double *reconstructedPatch = Qin + sourcePatchSize*pidx; const size_t x=item.get_global_id(1); const size_t y=item.get_global_id(2); int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; for (int i=0; i<unknowns+aux; i++) { Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; } }); }).wait(); } template< int numVPAIP, int unknowns, int aux > void strider(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm) { const size_t NPT=20000; Q.submit([&](handler &cgh) { cgh.parallel_for(nd_range<3>{{NPT, numVPAIP, unknowns+aux}, {1,20,1}}, [=](nd_item<3> item) //cgh.parallel_for(nd_range<3>{{NPT, numVPAIP, unknowns+aux}, {1, numVPAIP, unknowns+aux}}, [=](nd_item<3> item) { const size_t pidx=item.get_global_id(0);//[0]; double *reconstructedPatch = Qin + sourcePatchSize*pidx; const size_t x=item.get_global_id(1); const size_t i=item.get_global_id(2); for (int y=0; y < numVPAIP; y++) { int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; } }); }).wait(); } template< size_t NPT, int numVPAIP, int unknowns, int aux > void strider2(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm, const size_t GX, const size_t GY, const size_t GZ) { Q.submit([&](handler &cgh) { cgh.parallel_for(nd_range<3>{{NPT, (unknowns+aux)*numVPAIP, numVPAIP}, {GX, GY, GZ}}, [=](nd_item<3> item) { const size_t pidx=item.get_global_id(0); double *reconstructedPatch = Qin + sourcePatchSize*pidx; const size_t y=item.get_global_id(2); auto [x,i] = glob2loc(item.get_global_id(1), (unknowns+aux)*numVPAIP); int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; }); }).wait(); } template< int numVPAIP, int unknowns, int aux > void strider4(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm) { const size_t NPT=20000; Q.submit([&](handler &cgh) { cgh.parallel_for(nd_range<3>{{NPT, numVPAIP, (unknowns+aux)*numVPAIP}, {1, 1, 100}}, [=](nd_item<3> item) { const size_t pidx=item.get_global_id(0); double *reconstructedPatch = Qin + sourcePatchSize*pidx; const size_t y=item.get_global_id(1); auto [x,i] = glob2loc(item.get_global_id(2), (unknowns+aux)*numVPAIP); int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; }); }).wait(); } //template< //int numVPAIP, //int unknowns, //int aux //> //void strider2(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm) //{ //const size_t NPT=20000; //Q.submit([&](handler &cgh) //{ //cgh.parallel_for(nd_range<3>{{NPT, numVPAIP, (unknowns+aux)*numVPAIP}, {1, 20, 10}}, [=](nd_item<3> item) //{ //const size_t pidx=item.get_global_id(0);//[0]; //double *reconstructedPatch = Qin + sourcePatchSize*pidx; //const size_t x=item.get_global_id(1); //auto [i,y] = glob2loc(item.get_global_id(2), numVPAIP); //int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; //int destinationIndex = y*numVPAIP + x; //Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; //}); //}).wait(); //} template< int numVPAIP, int unknowns, int aux > void strider3(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool skipSourceTerm) { const size_t NPT=20000; Q.submit([&](handler &cgh) { cgh.parallel_for(nd_range<2>{{NPT, numVPAIP*(unknowns+aux)*numVPAIP}, {1,100}}, [=](nd_item<2> item) { const size_t pidx=item.get_global_id(0);//[0]; double *reconstructedPatch = Qin + sourcePatchSize*pidx; auto [i,y,x] = glob2loc(item.get_global_id(1),numVPAIP,numVPAIP); int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; }); }).wait(); } template< int numVPAIP, int unknowns, int aux > void hcompute(queue& Q, const int haloSize, const int sourcePatchSize, const int destPatchSize, double * Qin, double * Qout, bool wtf) { const size_t NPT=20000; Q.submit([&](handler &cgh) { //cgh.parallel_for_work_group(range<3>{NPT, numVPAIP, numVPAIP}, {1,1,1}, [=](group<3> grp) cgh.parallel_for_work_group(range<3>{NPT, numVPAIP, numVPAIP}, [=](group<3> grp) { const size_t pidx=grp[0]; double *reconstructedPatch = Qin + sourcePatchSize*pidx; grp.parallel_for_work_item([&](auto idx) { const size_t y=idx.get_global_id(1); const size_t x=idx.get_global_id(2); int sourceIndex = (y+1)*(numVPAIP+ 3*haloSize) + x - y; int destinationIndex = y*numVPAIP + x; for (int i=0; i<unknowns+aux; i++) { Qout[pidx*destPatchSize + destinationIndex*(unknowns+aux)+i] = reconstructedPatch[sourceIndex*(unknowns+aux)+i]; } }); }); }).wait(); } //int main(int argc, char* argv[]) //{ //std::cout << " Using SYCL device: " << Q.get_device().get_info<sycl::info::device::name>() << std::endl; //Q.submit([&](handler &cgh) //{ //cgh.single_task([=]() {}); //}); //// https://stackoverflow.com/questions/2704521/generate-random-double-numbers-in-c //std::uniform_real_distribution<double> unif(0, 10); //std::default_random_engine re(time(NULL)); //const size_t NPT=20000; //const int numVPAIP = 20; //const int unknowns=5; //const int srcPS = (numVPAIP+2)*(numVPAIP+2)*unknowns; //const int destPS = numVPAIP*numVPAIP*unknowns; //auto Xin = malloc_shared<double>(srcPS*NPT, Q); //for (int i=0;i<srcPS*NPT;i++) Xin[i] = unif(re); //auto Xout = malloc_shared<double>(destPS*NPT, Q); ////defaultcomputeparallel<numVPAIP,unknowns,0>(1, srcPS, destPS ,Xin, Xout); ////std::cout << "sum should be: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; ////for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; ////computeparallelgpudist<numVPAIP,unknowns,0,2>(1, srcPS, destPS ,Xin, Xout); ////std::cout << "sum is gpu2: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; ////for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; ////computeparallelgpudist<numVPAIP,unknowns,0,3>(1, srcPS, destPS ,Xin, Xout); ////std::cout << "sum is gpu3: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //fcompute3<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //hcompute<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //strider<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //strider2<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //strider3<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //for (int i=0;i<destPS*NPT;i++) Xout[i] = 0; //strider4<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //std::cout << "sum: " << std::accumulate(Xout, Xout + destPS*NPT, 0) << "\n"; //auto start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //defaultcomputeparallel<numVPAIP,unknowns,0>(1, srcPS, destPS ,Xin, Xout); //auto end = std::chrono::steady_clock::now(); //std::cout << "OMP PARALLEL FOR on CPU (defaultcomputeparallel): " <<std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //fcompute3<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "NDRANGE<3> with loop (fcompute3): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //strider<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "NDRANGE<3> with loop but swap dimensions (strider): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //strider2<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "NDRANGE<3> without loop (strider2) : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //strider4<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "NDRANGE<3> without loop (strider4) : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //strider3<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "NDANGE<2> without loop (strider3) " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //start = std::chrono::steady_clock::now(); //for (int i=0;i<std::atoi(argv[1]);i++) //hcompute<numVPAIP,unknowns,0>(Q, 1, srcPS, destPS ,Xin, Xout, true); //end = std::chrono::steady_clock::now(); //std::cout << "Hierarchical parallelism (hcompute): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; ////start = std::chrono::steady_clock::now(); ////for (int i=0;i<std::atoi(argv[1]);i++) ////computeparallelgpudist<numVPAIP,unknowns,0,2>(1, srcPS, destPS ,Xin, Xout); ////end = std::chrono::steady_clock::now(); ////std::cout << "OpenMP collapse(2) (computeparallelgpudist) : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; ////start = std::chrono::steady_clock::now(); ////for (int i=0;i<std::atoi(argv[1]);i++) ////computeparallelgpudist<numVPAIP,unknowns,0,3>(1, srcPS, destPS ,Xin, Xout); ////end = std::chrono::steady_clock::now(); ////std::cout << "OpenMP collapse(3) (computeparallelgpudist) : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; //free(Xin, Q); //free(Xout, Q); //return 0; //}
1.race8.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 20 int main() { int A[N][N]; #pragma omp parallel for schedule(static, 4) for (int i = 1; i < N; i++) for (int j = 1; j < N; j++) A[i][j] = A[i - 1][j - 1]; } // CHECK: Data Race detected // END
ahuja_orlin_segment.h
// // Created by Jan Groschaft on 31.3.19. // /* * Parallel implementation of Ahuja-Orlin's algorithm, divides the network into multiple segments. */ #ifndef MAXFLOW_AHUJA_ORLIN_SEGMENT_H #define MAXFLOW_AHUJA_ORLIN_SEGMENT_H #include "../../common_types.h" #include "../../data_structures/linked_list.h" #include "../../data_structures/thread_local_buffer_pool.h" #include "partitioning.h" #include <memory> #include <cassert> #include <chrono> #include <cstring> #include <omp.h> #include <cmath> #include <algorithm> #include <atomic> #ifndef CACHE_LINE_SIZE #define CACHE_LINE_SIZE 64 #endif namespace ahuja_orlin_segment { template <template <class> typename vector, typename T, typename U> class max_flow_instance { struct alignas (CACHE_LINE_SIZE) vertex { vertex * next = nullptr; vertex * prev = nullptr; U excess { 0 }; T label; T original_label; std::atomic_flag discovered = ATOMIC_FLAG_INIT; }; struct label_info { data_structures::linked_list<vertex> active_vertices { }; data_structures::linked_list<vertex> inactive_vertices { }; void reset ( ) noexcept { active_vertices . clear (); inactive_vertices . clear (); } }; vector<vector<cached_edge<T, U>>> _residual_network; std::unique_ptr<label_info[]> _labels; std::unique_ptr<vertex[]> _vertices; data_structures::thread_local_buffer_pool<T> _pool; std::unique_ptr<T[]> _q; std::unique_ptr<label_info[]> _thread_local_labels; T _source, _sink, _highest_active { 0 }, _highest_vertex { 0 }; U _max_cap; std::size_t _thread_count, _original_relabel_threshold { 0 }; const std::size_t _max_thread_count; int64_t _min_cpu_time_per_phase { 0 }; std::atomic<std::size_t> _relabel_threshold { 0 }; public: max_flow_instance ( vector<vector<cached_edge<T, U>>> graph, T source, T sink, std::size_t thread_count = static_cast<size_t>(omp_get_max_threads ()) ) : _residual_network ( std::move ( graph ) ), _labels ( std::make_unique<label_info[]> ( _residual_network . size () + 1 ) ), _vertices ( std::make_unique<vertex[]> ( _residual_network . size () ) ), _pool ( data_structures::thread_local_buffer_pool<T> { thread_count, _residual_network . size () } ), _q ( std::make_unique<T[]> ( _residual_network . size () ) ), _thread_local_labels ( std::make_unique<label_info[]> ( thread_count ) ), _source ( source ), _sink ( sink ), _thread_count ( thread_count ), _max_thread_count ( thread_count ) { omp_set_num_threads ( static_cast<int> ( _max_thread_count ) ); init (); } U find_max_flow ( ) { global_relabel ( _max_cap ); auto K = static_cast<U> ( std::ceil ( std::log2 ( _max_cap ) )); for ( U k = 0; k <= K; ++k ) { auto delta = static_cast<U> ( std::pow ( 2, K - k )); set_active_inactive ( delta ); while ( _highest_active != 0 ) { parallel_phase ( delta ); if ( !is_any_active ( delta ) ) { set_original_labels (); break; } global_relabel ( delta ); } } return _vertices[_sink] . excess; } void preflow_to_flow ( ) { std::swap ( _source, _sink ); _highest_vertex = _residual_network . size (); find_max_flow (); std::swap ( _source, _sink ); #ifdef DEBUG for ( std::size_t i = 0; i < _residual_network . size(); ++i ) if ( i != _source && i != _sink ) if ( _vertices[i] . excess > 0 ) std::cerr << "Excess violation: vertex " << i << ", excess " << _vertices[i] . excess << '\n'; #endif } auto steal_network ( ) { return std::move ( _residual_network ); } private: static constexpr T ALPHA = 6, BETA = 12; static constexpr double GLOBAL_RELABEL_FREQ = 1; static constexpr T min_active_per_thread = 10; void init ( ) noexcept { _max_cap = 0; #pragma omp parallel for schedule(static) reduction(max:_max_cap) for ( std::size_t i = 0; i < _residual_network[_source] . size (); ++i ) { auto & edge = _residual_network[_source][i]; _max_cap = std::max ( _max_cap, edge . r_capacity ); _vertices[edge . dst_vertex] . excess = edge . r_capacity; edge . reverse_r_capacity += edge . r_capacity; _residual_network[edge . dst_vertex][edge . reverse_edge_index] . r_capacity += edge . r_capacity; _residual_network[edge . dst_vertex][edge . reverse_edge_index] . reverse_r_capacity -= edge . r_capacity; edge . r_capacity = 0; } std::size_t m = 0; for ( std::size_t i = 0; i < _residual_network . size (); ++i ) m += _residual_network[i] . size (); _original_relabel_threshold = ( _residual_network . size () * ALPHA + m / 2 ) * 1; } void set_active_inactive ( const U delta ) noexcept { for ( std::size_t i = 0; i <= _highest_vertex; ++i ) _labels[i] . reset (); omp_set_num_threads ( static_cast<int> ( _max_thread_count ) ); _highest_active = _highest_vertex = 0; const auto delta_half = delta / 2; for ( std::size_t i = 0; i < _residual_network . size (); ++i ) { if ( i == _source || i == _sink || _vertices[i] . label == _residual_network . size () ) continue; if ( _vertices[i] . excess > delta_half ) { _highest_active = std::max ( _highest_active, _vertices[i] . label ); _labels[_vertices[i] . label] . active_vertices . push ( &_vertices[i] ); } else _labels[_vertices[i] . label] . inactive_vertices . push ( &_vertices[i] ); _highest_vertex = std::max ( _highest_vertex, _vertices[i] . label ); } } bool is_any_active ( const U delta ) const noexcept { const auto delta_half = delta / 2; bool res = false; omp_set_num_threads ( _max_thread_count ); #pragma omp parallel for schedule(static) reduction(||:res) for ( std::size_t i = 0; i < _residual_network . size (); ++i ) if ( _vertices[i] . excess > delta_half && _vertices[i] . label < _residual_network . size () && i != _sink ) res = true; omp_set_num_threads ( _thread_count ); return res; } void set_original_labels ( ) noexcept { omp_set_num_threads ( static_cast<int> ( _max_thread_count ) ); #pragma omp parallel for schedule(static) for ( std::size_t i = 0; i < _residual_network . size (); ++i ) _vertices[i] . original_label = _vertices[i] . label; } struct thread_local_data { const U delta; int64_t & cpu_time; const T low; const T high; T lowest_active; T & highest_active; T & highest_vertex; T relabel_progress; }; void parallel_phase ( const U delta ) { for ( ;; ) { _relabel_threshold = _original_relabel_threshold; const auto partitions = partitioning::get_partitions ( _labels, _highest_active, _thread_count, min_active_per_thread ); const auto actual_thread_cnt = partitions . size () - 1; omp_set_num_threads ( static_cast<int> ( actual_thread_cnt ) ); int64_t cpu_time = 0; if ( actual_thread_cnt == 1 ) { push_relabel ( thread_local_data { delta, cpu_time, 0, static_cast<T> ( _residual_network . size () ), 1, _highest_active, _highest_vertex, 0 } ); _thread_count = std::min ( _thread_count * 2, _max_thread_count ); return; } T highest_active = 0, highest_vertex = 0; #pragma omp parallel for schedule(static) reduction(+:cpu_time) reduction(max:highest_active) reduction(max:highest_vertex) for ( std::size_t i = 0; i < actual_thread_cnt; ++i ) { T low = partitions[i], high = partitions[i + 1]; highest_active = highest_vertex = high - 1; push_relabel ( thread_local_data { delta, cpu_time, low, high, low, highest_active, highest_vertex, 0 } ); _relabel_threshold -= _original_relabel_threshold / actual_thread_cnt; //add back vertices that are still active but couldn't have been relabeled to higher partition _labels[high - 1] . active_vertices . append_list ( _thread_local_labels[omp_get_thread_num ()] . active_vertices ); if ( !_labels[high - 1] . active_vertices . empty () ) highest_active = highest_vertex = high - 1; } _highest_active = highest_active; _highest_vertex = std::max ( _highest_vertex, highest_vertex ); if ( cpu_time > _min_cpu_time_per_phase ) { _thread_count = std::min ( _thread_count * 2, _max_thread_count ); return; } _thread_count = std::max ( actual_thread_cnt / 2, std::size_t { 1 } ); set_original_labels (); } } void push_relabel ( thread_local_data data ) noexcept { auto start = std::chrono::high_resolution_clock::now (); while ( data . lowest_active <= data . highest_vertex ) { if ( _labels[data . lowest_active] . active_vertices . empty () || data . lowest_active == data . low ) { ++data . lowest_active; continue; } auto vertex = get_vertex_idx ( _labels[data . lowest_active] . active_vertices . front () ); process ( vertex, data . lowest_active, data ); if ( data . relabel_progress * GLOBAL_RELABEL_FREQ >= _relabel_threshold ) break; } auto end = std::chrono::high_resolution_clock::now (); data . cpu_time += std::chrono::duration_cast<std::chrono::milliseconds> ( end - start ) . count (); } inline T get_vertex_idx ( vertex * n ) const noexcept { return std::distance ( _vertices . get (), n ); } inline void process ( const T vertex, T label, thread_local_data & data ) noexcept { if ( push ( vertex, label, data ) ) return; relabel ( vertex, label, data ); } //original labels have to be set before the parallel phase starts and they don't change until the next one inline bool same_thread ( T original_label, T low, T high ) const noexcept { return original_label >= low && original_label < high; } inline bool push ( const T vertex, const T label, thread_local_data & data ) noexcept { const auto target_label = label - 1; for ( auto & edge : _residual_network[vertex] ) { if ( edge . r_capacity > 0 && same_thread ( _vertices[edge . dst_vertex] . original_label, data . low, data . high ) && _vertices[edge . dst_vertex] . label == target_label ) { const auto old_target_excess = _vertices[edge . dst_vertex] . excess; auto flow = std::min ( _vertices[vertex] . excess, edge . r_capacity ); if ( edge . dst_vertex != _sink && target_label != data . low ) flow = std::min ( flow, data . delta - _vertices[edge . dst_vertex] . excess ); _vertices[vertex] . excess -= flow; _vertices[edge . dst_vertex] . excess += flow; edge . r_capacity -= flow; edge . reverse_r_capacity += flow; _residual_network[edge . dst_vertex][edge . reverse_edge_index] . reverse_r_capacity -= flow; _residual_network[edge . dst_vertex][edge . reverse_edge_index] . r_capacity += flow; bool ret = false; if ( _vertices[vertex] . excess <= data . delta / 2 ) { _labels[label] . active_vertices . remove ( &_vertices[vertex] ); _labels[label] . inactive_vertices . push ( &_vertices[vertex] ); ret = true; } if ( edge . dst_vertex == _source || edge . dst_vertex == _sink ) { if ( ret ) return true; else continue; } //since we don't process vertices in data . low, we must ensure that we don't push them multiple times if ( _vertices[edge . dst_vertex] . excess > data . delta / 2 && old_target_excess <= data . delta / 2 ) { _labels[target_label] . inactive_vertices . remove ( &_vertices[edge . dst_vertex] ); _labels[target_label] . active_vertices . push ( &_vertices[edge . dst_vertex] ); --data . lowest_active; ret = true; } if ( ret ) return true; } } return false; } inline void relabel ( const T vertex, const T current_label, thread_local_data & data ) noexcept { data . relabel_progress += BETA; const auto new_label = calculate_new_label ( vertex, data ); _labels[current_label] . active_vertices . remove ( &_vertices[vertex] ); _vertices[vertex] . label = std::min ( new_label, data . high - 1 ); if ( new_label < data . high ) { data . highest_vertex = std::max ( data . highest_vertex, new_label ); data . highest_active = std::max ( data . highest_active, new_label ); _labels[new_label] . active_vertices . push ( &_vertices[vertex] ); } else if ( data . high < _residual_network . size () ) //vertex is still active, but we cannot relabel it to another partition, so we remember it and add it back to active vertices at the end of this phase _thread_local_labels[omp_get_thread_num ()] . active_vertices . push ( &_vertices[vertex] ); if ( _labels[current_label] . active_vertices . empty () && _labels[current_label] . inactive_vertices . empty () && current_label != data . high - 1 ) { gap_relabel ( current_label, data ); _vertices[vertex] . label = _residual_network . size (); } } inline T calculate_new_label ( const T vertex, thread_local_data & data ) noexcept { T increase_to = data . high - 1; for ( auto & edge : _residual_network[vertex] ) { if ( edge . r_capacity == 0 || !same_thread ( _vertices[edge . dst_vertex] . original_label, data . low, data . high ) ) continue; increase_to = std::min ( increase_to, _vertices[edge . dst_vertex] . label ); } data . relabel_progress += _residual_network[vertex] . size (); return increase_to + 1; } void global_relabel ( const U delta ) noexcept { auto start = std::chrono::high_resolution_clock::now (); omp_set_num_threads ( static_cast<int> ( _max_thread_count ) ); const auto not_reached = _residual_network . size (); #pragma omp parallel for schedule(static) for ( std::size_t i = 0; i < _residual_network . size (); ++i ) { _vertices[i] . discovered . clear ( std::memory_order_relaxed ); _vertices[i] . label = _vertices[i] . original_label = not_reached; } #pragma omp parallel for schedule(static) for ( std::size_t i = 0; i <= _highest_vertex; ++i ) _labels[i] . reset (); _vertices[_sink] . label = _vertices[_sink] . original_label = 0; _vertices[_sink] . discovered . test_and_set ( std::memory_order_relaxed ); _highest_active = 0; _q[0] = _sink; std::size_t current_queue_size = 1; T current_distance = 0; const auto delta_half = delta / 2; while ( current_queue_size > 0 ) { #pragma omp parallel for schedule(static) for ( std::size_t i = 0; i < current_queue_size; ++i ) { auto thr_id = omp_get_thread_num (); auto current_vertex = _q[i]; for ( auto edge : _residual_network[current_vertex] ) { if ( edge . reverse_r_capacity > 0 ) { if ( !_vertices[edge . dst_vertex] . discovered . test_and_set ( std::memory_order_relaxed ) ) { _vertices[edge . dst_vertex] . label = current_distance + 1; _vertices[edge . dst_vertex] . original_label = current_distance + 1; _pool . push_back ( edge . dst_vertex, static_cast<std::size_t>(thr_id) ); auto * node = &_vertices[edge . dst_vertex]; if ( _vertices[edge . dst_vertex] . excess > delta_half ) _thread_local_labels[thr_id] . active_vertices . push ( node ); else _thread_local_labels[thr_id] . inactive_vertices . push ( node ); } } } } current_queue_size = _pool . swap_data ( _q ); ++current_distance; for ( std::size_t i = 0; i < _max_thread_count; ++i ) //append together all thread_local info { _labels[current_distance] . active_vertices . append_list ( _thread_local_labels[i] . active_vertices ); _labels[current_distance] . inactive_vertices . append_list ( _thread_local_labels[i] . inactive_vertices ); } if ( !_labels[current_distance] . active_vertices . empty () ) _highest_active = current_distance; } _highest_vertex = current_distance - 1; omp_set_num_threads ( static_cast<int> ( _thread_count ) ); auto end = std::chrono::high_resolution_clock::now (); _min_cpu_time_per_phase = std::chrono::duration_cast<std::chrono::milliseconds> ( end - start ) . count (); } //gap heuristic restricted to single segment void gap_relabel ( const T gap_height, const thread_local_data & data ) noexcept { for ( auto current_height = gap_height + 1; current_height <= data . highest_vertex; ++current_height ) { while ( !_labels[current_height] . active_vertices . empty () ) { auto * ptr = _labels[current_height] . active_vertices . pop (); auto vertex_idx = get_vertex_idx ( ptr ); _vertices[vertex_idx] . label = _residual_network . size (); } while ( !_labels[current_height] . inactive_vertices . empty () ) { auto * ptr = _labels[current_height] . inactive_vertices . pop (); auto vertex_idx = get_vertex_idx ( ptr ); _vertices[vertex_idx] . label = _residual_network . size (); } } data . highest_vertex = data . highest_active = std::max ( gap_height - 1, data . low ); } }; } #endif //MAXFLOW_AHUJA_ORLIN_SEGMENT_H
7.norace1.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define M 20 #define N 20 #define O 20 int main() { double A[M][N], B[M][O], C[O][N]; #pragma omp parallel for for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { A[i][j] = 0.0; for (int k = 0; k < O; ++k) A[i][j] += B[i][k] * C[k][j]; } } // CHECK: Region is Data Race Free. // END
LAGraph_bfs_pushpull.c
//------------------------------------------------------------------------------ // LAGraph_bfs_pushpull: push-pull breadth-first search //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2020 LAGraph Contributors. (see Contributors.txt for a full list of Contributors; see ContributionInstructions.txt for information on how you can Contribute to this project). All Rights Reserved. NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. Released under a BSD license, please see the LICENSE file distributed with this Software or contact permission@sei.cmu.edu for full terms. Created, in part, with funding and support from the United States Government. (see Acknowledgments.txt file). This program includes and/or can make use of certain third party source code, object code, documentation and other files ("Third Party Software"). See LICENSE file for more details. */ //------------------------------------------------------------------------------ // LAGraph_bfs_pushpull: direction-optimized push/pull breadth first search, // contributed by Tim Davis, Texas A&M. // LAGraph_bfs_pushpull computes the BFS of a graph from a single given // starting node s. The result is a vector v where v(i)=k if node i was placed // at level k in the BFS. // Usage: // info = LAGraph_bfs_pushpull (&v, &pi, A, AT, s, max_level, vsparse) ; // GrB_Vector *v: a vector containing the result, created on output. // v(i) = k is the BFS level of node i in the graph, where // a source node s has v(s)=1. v(i) is implicitly zero if it is // unreachable from s. That is, GrB_Vector_nvals (&nreach,v) // is the size of the reachable set of s, for a single-source // BFS. v may be returned as sparse, or full. If full, v(i)=0 // indicates that node i was not reached. If sparse, the pattern of // v indicates the set of nodes reached. // GrB_Vector *pi: a vector containing the BFS tree, in 1-based indexing. // pi(s) = s+1 if s is the source node. pi(i) = p+1 if p is the // parent of i. If pi is sparse, and pi(i) is not present, then node // i has not been reached. Otherwise, if pi is full, then pi(i)=0 // indicates that node i was not reached. // GrB_Matrix A: a square matrix of any type. The values of A are not // accessed. The presence of the entry A(i,j) indicates the edge // (i,j). That is, an explicit entry A(i,j)=0 is treated as an edge. // GrB_Matrix AT: an optional matrix of any type. If NULL, the algorithm // is a conventional push-only BFS. If not NULL, AT must be the // transpose of A, and a push-pull algorithm is used (NOTE: this // assumes GraphBLAS stores its matrix in CSR form; see discussion // below). Results are undefined if AT is not NULL but not identical // to the transpose of A. // int64_t s: the source node for the BFS. // int64_t max_level: An optional limit on the levels searched for the // single-source BFS. If zero, then no limit is enforced. If > 0, // then only nodes with v(i) <= max_level will be visited. That is: // 1: just the source node s, 2: the source and its neighbors, 3: the // source s, its neighbors, and their neighbors, etc. // bool vsparse: if the result v may remain very sparse, then set this // parameter to true. If v might have many entries, set it false. If // you are unsure, then set it to true. This parameter speeds up // the handling of v. If you guess wrong, there is a slight // performance penalty. The results are not affected by this // parameter, just the performance. This parameter is used only for // the single-source BFS. // single-source BFS: // Given a graph A, a source node s, find all nodes reachable from node s. // v(s)=1, v(i)=2 if edge (s,i) appears in the graph, and so on. If node // i is not reachable from s, then implicitly v(i)=0. v is returned as a // sparse vector, and v(i) is not an entry in this vector. // This algorithm can use the push-pull strategy, which requires both A and // AT=A' to be passed in. If the graph is known to be symmetric, then the same // matrix A can be passed in for both arguments. Results are undefined if AT // is not the transpose of A. // If only A or AT is passed in, then only single strategy will be used: push // or pull, but not both. In general, push-only performs well. A pull-only // strategy is possible but it is exceedingly slow. Assuming A and AT are both // in CSR format, then: // LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest) // LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // push-only (good) // LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // pull-only (slow!) // If A and AT are both in CSC format, then: // LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest) // LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // push-only (good) // LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // pull-only (slow!) // Since the pull-only method is exceedingly slow, SuiteSparse:GraphBLAS // detects this case and refuses to do it. // The basic step of this algorithm computes A'*q where q is the 'queue' of // nodes in the current level. This can be done with GrB_vxm(q,A) = (q'*A)' = // A'*q, or by GrB_mxv(AT,q) = AT*q = A'*q. Both steps compute the same thing, // just in a different way. In GraphBLAS, unlike MATLAB, a GrB_Vector is // simultaneously a row and column vector, so q and q' are interchangeable. // To implement an efficient BFS using GraphBLAS, an assumption must be made in // LAGraph about how the matrix is stored, whether by row or by column (or // perhaps some other opaque data structure). The storage format has a huge // impact on the relative performance of vxm(q,A) and mxv(AT,q). // Storing A by row, if A(i,j) is the edge (i,j), means that A(i,:) is easily // accessible. In terms of the graph A, this means that the out-adjacency // list of node i can be traversed in time O(out-degree of node i). // If AT is stored by row, then AT(i,:) is the in-adjacency list of node i, // and traversing row i of AT can be done in O(in-degree of node i) time. // The CSR (Compressed Sparse Row) format is the default for // SuiteSparse:GraphBLAS, but no assumption can be made about any particular // GraphBLAS library implementation. // If A and AT are both stored by column instead, then A(i,:) is not easy to // access. Instead, A(:,i) is the easily-accessible in-adjacency of node i, // and AT(:,i) is the out-adjancency. // A push step requires the out-adjacencies of each node, where as // a pull step requires the in-adjacencies of each node. // vxm(q,A) = A'*q, with A stored by row: a push step // mxv(AT,q) = A'*q, with AT stored by row: a pull step // vxm(q,A) = A'*q, with A stored by col: a pull step // mxv(AT,q) = A'*q, with AT stored by col: a push step // The GraphBLAS data structure is opaque. An implementation may decide to // store the matrix A in both formats, internally, so that it easily traverse // both in- and out-adjacencies of each node (equivalently, A(i,:) and A(:,i) // can both be easily traversed). This would make a push-pull BFS easy to // implement using just the opaque GrB_Matrix A, but it doubles the storage. // Deciding which format to use automatically is not a simple task, // particularly since the decision must work well throughout GraphBLAS, not // just for the BFS. // MATLAB stores its sparse matrices in CSC format (Compressed Sparse Column). // As a result, the MATLAB expression x=AT*q is a push step, computed using a // saxpy-based algorithm internally, and x=A'*q is a pull step, computed using // a dot product. // SuiteSparse:GraphBLAS can store a matrix in either format, but this requires // an extension to the GraphBLAS C API (GxB_set (A, GxB_FORMAT, f)). where // f = GxB_BY_ROW (that is, CSR) or GxB_BY_COL (that is, CSC). The library // could be augmented in the future with f = Gxb_BY_BOTH. It currently does // not select the format automatically. As a result, if GxB_set is not used, // all its GrB_Matrix objects are stored by row (CSR). // SuiteSparse:GraphBLAS allows the user to query (via GxB_get) an set (via // GxB_set) the format, whether by row or by column. The hypersparsity of // A is selected automatically, with optional hints from the user application, // but a selection between hypersparsity vs standard CSR and CSC has no effect // on the push vs pull decision made here. // The push/pull and saxpy/dot connection can be described as follows. // Assume for these first two examples that MATLAB stores its matrices in CSR // format, where accessing A(i,:) is fast. // If A is stored by row, then x = vxm(q,A) = q'*A can be written in MATLAB // notation as: /* function x = vxm (q,A) % a push step: compute x = q'*A where q is a column vector x = sparse (1,n) for i = 1:n % a saxpy operation, using the ith row of A and the scalar q(i) x = x + q (i) * A (i,:) end */ // If AT is stored by row, then x = mvx(AT,q) = AT*q = A'*q becomes // a dot product: /* function x = mxv (AT,q) % a pull step: compute x = AT*q where q is a column vector for i = 1:n % a dot-product of the ith row of AT and the column vector q x (i) = AT (i,:) * q end */ // The above snippets describe how SuiteSparse:GraphBLAS computes vxm(q,A) and // mxv(AT,q) by default, where A and AT are stored by row by default. However, // they would be very slow in MATLAB, since it stores its sparse matrices in // CSC format. In that case, if A is stored by column and thus accessing // A(:,j) is efficient, then x = vxm(q,A) = q'*A becomes the dot product // instead. These two snippets assume the matrices are both in CSR for, and // thus make more efficient use of MATLAB: /* function x = vxm (q,A) % a pull step: compute x = q'*A where q is a column vector for j = 1:n % a dot product of the row vector q' and the jth column of A x (j) = q' * A (:,j) end */ // If AT is stored by column, then x = mvx(AT,q) is /* function x = mxv (AT,q) % a push step: compute x = AT*q where q is a column vector for j = 1:n % a saxpy operation, using the jth column of AT and the scalar q(i) x = x + AT (:,j) * q end */ // In MATLAB, if q is a sparse column vector and A is a sparse matrix, then // x=A*q does in fact use a saxpy-based method, internally, and x=A'*q uses a // dot product. You can view the code used internally in MATLAB for its sparse // matrix multiplication in the SuiteSparse/MATLAB_Tools/SSMULT and SFMULT // packages, at http://suitesparse.com. // This raises an interesting puzzle for LAGraph, which is intended on being a // graph library that can be run on any implementation of GraphBLAS. There are // no mechanisms in the GraphBLAS C API for LAGraph (or other external packages // or user applications) to provide hints to GraphBLAS. Likely, there are no // query mechanisms where LAGraph can ask GraphBLAS how its matrices might be // stored (LAGraphs asks, "Is A(i,:) fast? Or A(:,j)? Or both?"; the answer // from GraphBLAS is silence). The GraphBLAS data structure is opaque, and it // does not answer this query. // There are two solutions to this puzzle. The most elegant one is for // GraphBLAS to handle all this internally, and change formats as needed. It // could choose to store A in both CSR and CSC format, or use an entirely // different data structure, and it would make the decision between the push or // pull, at each step of the BFS. This is not a simple task since the API is // complex. Furthermore, the selection of the data structure for A has // implications on all other GraphBLAS operations (submatrix assignment and // extraction, for example). // However, if A were to be stored in both CSR and CSC format, inside the // opaque GraphBLAS GrB_Matrix data structure, then LAGraph_bfs_simple would // become a push-pull BFS. // The second solution is to allow the user application or library such as // LAGraph to provide hints and allow it to query the GraphBLAS library. // There are no such features in the GraphBLAS C API. // SuiteSparse:GraphBLAS takes the second approach: It adds two functions that // are extensions to the API: GxB_set changes the format (CSR or CSC), and // GxB_get can query the format. Even this this simplication, // SuiteSparse:GraphBLAS uses 24 different algorithmic variants inside GrB_mxm // (per semiring), and selects between them automatically. By default, all of // its matrices are stored in CSR format (either sparse or hypersparse, // selected automatically). So if no GxB_* extensions are used, all matrices // are in CSR format. // If a GraphBLAS library other than SuiteSparse:GraphBLAS is in use, this // particular function assumes that its input matrices are in CSR format, or at // least A(i,:) and AT(i,:) can be easily accessed. With this assumption, it // is the responsibilty of this function to select between using a push or a // pull, for each step in the BFS. // The following analysis assumes CSR format, and it assumes that dot-product // (a pull step) can terminate early via a short-circuit rule with the OR // monoid, as soon as it encounters a TRUE value. This cuts the time for the // dot-product. Not all GraphBLAS libraries may use this, but SuiteSparse: // GraphBLAS does (in version 2.3.0 and later). Early termination cannot be // done for the saxpy (push step) method. // The work done by the push method (saxpy) is very predictable. BFS uses a // complemented mask. There is no simple way to exploit a complemented mask, // and saxpy has no early termination rule. If the set of nodes in the current // level is q, the work is nnz(A(q,:)). If d = nnz(A)/n is the average degree, // this becomes d*nq where nq = length (q): // pushwork = d*nq // The work done by the pull (dot product) method is less predictable. It can // exploit the complemented mask, and so it only computes (n-nvisited) dot // products, if nvisited is the # of nodes visited so far (in all levels). // With no early-termination, the dot product will take d * log2 (nq) time, // assuming that q is large and a binary search is used internally. That is, // the dot product will scan through the d entries in A(i,:), and do a binary // search for each entry in q. To account for the higher constant of a binary // search, log2(nq) is replaced with (3*(1+log2(nq))). With early termination, // d is too high. If the nodes are randomly marked, the probability of each // node being marked is nvisited/n. The expected number of trials until // success, for a sequence of events with probabilty p, is 1/p. Thus, the // expected number of iterations in a dot product before an early termination // is 1/p = (n/nvisited+1), where +1 is added to avoid a divide by zero. // However, it cannot exceed d. Thus, the total work for the dot product // (pull) method can be estimated as: // per_dot = min (d, n / (nvisited+1)) // pullwork = (n-nvisited) * per_dot * (3 * (1 + log2 ((double) nq))) // The above expressions are valid for SuiteSparse:GraphBLAS v2.3.0 and later, // and may be reasonable for other GraphBLAS implementations. Push or pull // is selected as the one with the least work. // TODO: change the formula for v3.2.0 // The push/pull decision requires that both A and AT be passed in, but this // function can use just one or the other. If only A is passed in and AT is // NULL, then only vxm(q,A) will be used (a push step if A is CSR, or a pull // step if A is CSC). If only AT is passed in and A is NULL, then only // mxv(AT,q) will be used (a pull step if AT is CSR, or a push step if AT is // CSC). // In general, while a push-pull strategy is the fastest, a push-only BFS will // give good peformance. In particular, the time to compute AT=A' plus the // time for the push-pull BFS is typically higher than just a push-only BFS. // This why this function does not compute AT=A'. To take advantage of the // push-pull method, both A and AT must already be available, with the cost to // construct them amortized across other computations such as this one. // A pull-only strategy will be *exceeding* slow. // The input matrix A must be square. It can be non-binary, but best // performance will be obtained if it is GrB_BOOL. It can have explicit // entries equal to zero. These are safely ignored, and are treated as // non-edges. // SuiteSparse:GraphBLAS can detect the CSR vs CSC format of its inputs. // In this case, if both matrices are provided, they must be in the same // format (both GxB_BY_ROW or both GxB_BY_COL). If the matrices are in CSC // format, vxm(q,A) is the pull step and mxv(AT,q) is the push step. // If only A or AT are provided, and the result is a pull-only algorithm, // an error is returned. // References: // Carl Yang, Aydin Buluc, and John D. Owens. 2018. Implementing Push-Pull // Efficiently in GraphBLAS. In Proceedings of the 47th International // Conference on Parallel Processing (ICPP 2018). ACM, New York, NY, USA, // Article 89, 11 pages. DOI: https://doi.org/10.1145/3225058.3225122 // Scott Beamer, Krste Asanovic and David A. Patterson, // The GAP Benchmark Suite, http://arxiv.org/abs/1508.03619, 2015. // http://gap.cs.berkeley.edu/ #include "LAGraph_internal.h" #define LAGRAPH_FREE_ALL \ { \ GrB_free (&v) ; \ GrB_free (&t) ; \ GrB_free (&q) ; \ GrB_free (&pi) ; \ } GrB_Info LAGraph_bfs_pushpull // push-pull BFS, or push-only if AT = NULL ( GrB_Vector *v_output, // v(i) is the BFS level of node i in the graph GrB_Vector *pi_output, // pi(i) = p if p is the parent of node i. // if NULL, the parent is not computed. GrB_Matrix A, // input graph, treated as if boolean in semiring GrB_Matrix AT, // transpose of A (optional; push-only if NULL) int64_t s, // starting node of the BFS int64_t max_level, // optional limit of # levels to search bool vsparse // if true, v is expected to be very sparse ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GrB_Vector q = NULL ; // nodes visited at each level GrB_Vector v = NULL ; // result vector GrB_Vector t = NULL ; // temporary vector GrB_Vector pi = NULL ; // parent vector if (v_output == NULL || (A == NULL && AT == NULL)) { // required output argument is missing LAGRAPH_ERROR ("required arguments are NULL", GrB_NULL_POINTER) ; } (*v_output) = NULL ; bool compute_tree = (pi_output != NULL) ; #if defined ( GxB_SUITESPARSE_GRAPHBLAS ) \ && ( GxB_IMPLEMENTATION >= GxB_VERSION (3,2,0) ) GrB_Descriptor desc_s = GrB_DESC_S ; GrB_Descriptor desc_sc = GrB_DESC_SC ; GrB_Descriptor desc_rc = GrB_DESC_RC ; GrB_Descriptor desc_r = GrB_DESC_R ; #else GrB_Descriptor desc_s = NULL ; GrB_Descriptor desc_sc = LAGraph_desc_ooco ; GrB_Descriptor desc_rc = LAGraph_desc_oocr ; GrB_Descriptor desc_r = LAGraph_desc_ooor ; #endif bool use_vxm_with_A ; GrB_Index nrows, ncols, nvalA, ignore, nvals ; if (A == NULL) { // only AT is provided LAGRAPH_OK (GrB_Matrix_ncols (&nrows, AT)) ; LAGRAPH_OK (GrB_Matrix_nrows (&ncols, AT)) ; LAGRAPH_OK (GrB_Matrix_nvals (&nvalA, AT)) ; use_vxm_with_A = false ; } else { // A is provided. AT may or may not be provided LAGRAPH_OK (GrB_Matrix_nrows (&nrows, A)) ; LAGRAPH_OK (GrB_Matrix_ncols (&ncols, A)) ; LAGRAPH_OK (GrB_Matrix_nvals (&nvalA, A)) ; use_vxm_with_A = true ; } // push/pull requires both A and AT bool push_pull = (A != NULL && AT != NULL) ; if (nrows != ncols) { // A must be square LAGRAPH_ERROR ("A must be square", GrB_NULL_POINTER) ; } //-------------------------------------------------------------------------- // check the format of A and AT //-------------------------------------------------------------------------- bool csr = true ; // csr is true if A and AT are known (or assumed) to be in CSR format; if // false, they are known to be in CSC format. // This can be tested in SuiteSparse:GraphBLAS. Other libraries can use // this section for their own library-specific tests, if they have them. // LAGraph_bfs_pushpull will work just fine if nothing is changed or if the // following is disabled (even SuiteSparse:GraphBLAS). The push/pull // behaviour will be unpredicatble, however, unless the library's default // format is CSR. #ifdef GxB_SUITESPARSE_GRAPHBLAS // The CSR vs CSC status can be tested in SuiteSparse:GraphBLAS. // However, even with SuiteSparse:GraphBLAS, this step is optional. GxB_Format_Value A_format = -1, AT_format = -1 ; bool A_csr = true, AT_csr = true ; if (A != NULL) { // A_csr is true if accessing A(i,:) is fast LAGRAPH_OK (GxB_get (A , GxB_FORMAT, &A_format)) ; A_csr = (A_format == GxB_BY_ROW) ; } if (AT != NULL) { // AT_csr is true if accessing AT(i,:) is fast LAGRAPH_OK (GxB_get (AT, GxB_FORMAT, &AT_format)) ; AT_csr = (AT_format == GxB_BY_ROW) ; } // Assume CSR if A(i,:) and AT(i,:) are both fast. If csr is false, // then the algorithm below will reverse the use of vxm and mxv. csr = A_csr && AT_csr ; if (push_pull) { // both A and AT are provided. Require they have the same format. // Either both A(i,:) and AT(i,:) are efficient to accesss, or both // A(:,j) and AT(:,j) are efficient to access. if (A_csr != AT_csr) { LAGRAPH_ERROR ("A and AT must in the same format:\n" "both GxB_BY_ROW, or both GxB_BY_COL", GrB_INVALID_VALUE) ; } } else { // only A or AT are provided. Refuse to do the pull-only version. if (A != NULL && A_format == GxB_BY_COL) { // this would result in a pull-only BFS ... exceedingly slow LAGRAPH_ERROR ( "SuiteSparse: AT not provided, so A must be GxB_BY_ROW\n" "(or provide both A and AT, both in the same format,\n" "either both GxB_BY_COL or both GxB_BY_ROW)", GrB_INVALID_VALUE) ; } if (AT != NULL && AT_format == GxB_BY_ROW) { // this would result in a pull-only BFS ... exceedingly slow LAGRAPH_ERROR ( "SuiteSparse: A not provided, so AT must be GxB_BY_COL\n" "(or provide both A and AT, both in the same format,\n" "either both GxB_BY_COL or both GxB_BY_ROW)", GrB_INVALID_VALUE) ; } } #endif //-------------------------------------------------------------------------- // initializations //-------------------------------------------------------------------------- GrB_Index n = nrows ; int nthreads = LAGraph_get_nthreads ( ) ; nthreads = LAGRAPH_MIN (n / 4096, nthreads) ; nthreads = LAGRAPH_MAX (nthreads, 1) ; // just traverse from the source node s max_level = (max_level <= 0) ? n : LAGRAPH_MIN (n, max_level) ; // create an empty vector v GrB_Type int_type = (n > INT32_MAX) ? GrB_INT64 : GrB_INT32 ; LAGRAPH_OK (GrB_Vector_new (&v, int_type, n)) ; // make v dense if requested int64_t vlimit = LAGRAPH_MAX (256, sqrt ((double) n)) ; if (!vsparse) { // v is expected to have many entries, so convert v to dense, then // finish pending work. If the guess is wrong, v can be made dense // later on. LAGRAPH_OK (GrB_assign (v, NULL, NULL, 0, GrB_ALL, n, NULL)) ; LAGRAPH_OK (GrB_Vector_nvals (&ignore, v)) ; } GrB_Semiring first_semiring, second_semiring ; if (compute_tree) { // create an integer vector q, and set q(s) to s+1 LAGRAPH_OK (GrB_Vector_new (&q, int_type, n)) ; LAGRAPH_OK (GrB_Vector_setElement (q, s+1, s)) ; if (n > INT32_MAX) { // first_semiring = LAGraph_MIN_FIRST_INT64 ; // second_semiring = LAGraph_MIN_SECOND_INT64 ; first_semiring = GxB_ANY_FIRST_INT64 ; second_semiring = GxB_ANY_SECOND_INT64 ; } else { // first_semiring = LAGraph_MIN_FIRST_INT32 ; // second_semiring = LAGraph_MIN_SECOND_INT32 ; first_semiring = GxB_ANY_FIRST_INT32 ; second_semiring = GxB_ANY_SECOND_INT32 ; } // create the empty parent vector LAGRAPH_OK (GrB_Vector_new (&pi, int_type, n)) ; if (!vsparse) { // make pi a dense vector of all 0's LAGRAPH_OK (GrB_assign (pi, NULL, NULL, 0, GrB_ALL, n, NULL)) ; LAGRAPH_OK (GrB_Vector_nvals (&ignore, pi)) ; } // pi (s) = s+1 denotes a root of the BFS tree GrB_Index root = (GrB_Index) s ; LAGRAPH_OK (GrB_assign (pi, NULL, NULL, s+1, &root, 1, NULL)) ; } else { // create a boolean vector q, and set q(s) to true LAGRAPH_OK (GrB_Vector_new (&q, GrB_BOOL, n)) ; LAGRAPH_OK (GrB_Vector_setElement (q, true, s)) ; first_semiring = LAGraph_LOR_FIRST_BOOL ; second_semiring = LAGraph_LOR_SECOND_BOOL ; } // average node degree double d = (n == 0) ? 0 : (((double) nvalA) / (double) n) ; int64_t nvisited = 0 ; // # nodes visited so far GrB_Index nq = 1 ; // number of nodes in the current level //-------------------------------------------------------------------------- // BFS traversal and label the nodes //-------------------------------------------------------------------------- for (int64_t level = 1 ; ; level++) { //---------------------------------------------------------------------- // set v to the current level, for all nodes in q //---------------------------------------------------------------------- // v<q> = level: set v(i) = level for all nodes i in q LAGRAPH_OK (GrB_assign (v, q, NULL, level, GrB_ALL, n, desc_s)) ; //---------------------------------------------------------------------- // check if done //---------------------------------------------------------------------- nvisited += nq ; if (nq == 0 || nvisited == n || level >= max_level) break ; //---------------------------------------------------------------------- // check if v should be converted to dense //---------------------------------------------------------------------- if (vsparse && nvisited > vlimit) { // Convert v from sparse to dense to speed up the rest of the work. // If this case is triggered, it would have been faster to pass in // vsparse = false on input. // v <!v> = 0 LAGRAPH_OK (GrB_assign (v, v, NULL, 0, GrB_ALL, n, desc_sc)) ; LAGRAPH_OK (GrB_Vector_nvals (&ignore, v)) ; if (compute_tree) { // Convert pi from sparse to dense, to speed up the work. // pi<!pi> = 0 LAGRAPH_OK (GrB_assign (pi, pi, NULL, 0, GrB_ALL, n, desc_sc)) ; LAGRAPH_OK (GrB_Vector_nvals (&ignore, pi)) ; } vsparse = false ; } //---------------------------------------------------------------------- // select push vs pull //---------------------------------------------------------------------- if (push_pull) { double pushwork = d * nq ; double expected = (double) n / (double) (nvisited+1) ; double per_dot = LAGRAPH_MIN (d, expected) ; double binarysearch = (3 * (1 + log2 ((double) nq))) ; double pullwork = (n-nvisited) * per_dot * binarysearch ; use_vxm_with_A = (pushwork < pullwork) ; if (!csr) { // Neither A(i,:) nor AT(i,:) is efficient. Instead, both // A(:,j) and AT(:,j) is fast (that is, the two matrices // are in CSC format). Swap the use_vxm_with_A = !use_vxm_with_A ; } } //---------------------------------------------------------------------- // q = next level of the BFS //---------------------------------------------------------------------- if (use_vxm_with_A) { // q'<!v> = q'*A // this is a push step if A is in CSR format; pull if CSC LAGRAPH_OK (GrB_vxm (q, v, NULL, first_semiring, q, A, desc_rc)) ; } else { // q<!v> = AT*q // this is a pull step if AT is in CSR format; push if CSC LAGRAPH_OK (GrB_mxv (q, v, NULL, second_semiring, AT, q, desc_rc)) ; } //---------------------------------------------------------------------- // move to next level //---------------------------------------------------------------------- if (compute_tree) { //------------------------------------------------------------------ // assign parents //------------------------------------------------------------------ // q(i) currently contains the parent of node i in tree (off by one // so it won't have any zero values, for valued mask). // pi<q> = q LAGRAPH_OK (GrB_assign (pi, q, NULL, q, GrB_ALL, n, desc_s)) ; //------------------------------------------------------------------ // replace q with current node numbers //------------------------------------------------------------------ // q(i) = i+1 for all entries in q. #ifdef GxB_SUITESPARSE_GRAPHBLAS GrB_Index *qi ; if (n > INT32_MAX) { int64_t *qx ; LAGRAPH_OK (GxB_Vector_export (&q, &int_type, &n, &nq, &qi, (void **) (&qx), NULL)) ; int nth = LAGRAPH_MIN (nq / (64*1024), nthreads) ; nth = LAGRAPH_MAX (nth, 1) ; #pragma omp parallel for num_threads(nth) schedule(static) for (int64_t k = 0 ; k < nq ; k++) { qx [k] = qi [k] + 1 ; } LAGRAPH_OK (GxB_Vector_import (&q, int_type, n, nq, &qi, (void **) (&qx), NULL)) ; } else { int32_t *qx ; LAGRAPH_OK (GxB_Vector_export (&q, &int_type, &n, &nq, &qi, (void **) (&qx), NULL)) ; int nth = LAGRAPH_MIN (nq / (64*1024), nthreads) ; nth = LAGRAPH_MAX (nth, 1) ; #pragma omp parallel for num_threads(nth) schedule(static) for (int32_t k = 0 ; k < nq ; k++) { qx [k] = qi [k] + 1 ; } LAGRAPH_OK (GxB_Vector_import (&q, int_type, n, nq, &qi, (void **) (&qx), NULL)) ; } #else // TODO: use extractTuples and build instead fprintf (stderr, "TODO: use extractTuples here\n") ; abort ( ) ; #endif } else { //------------------------------------------------------------------ // count the nodes in the current level //------------------------------------------------------------------ LAGr_Vector_nvals (&nq, q) ; } } //-------------------------------------------------------------------------- // return the parent vector, if computed //-------------------------------------------------------------------------- if (compute_tree) { (*pi_output) = pi ; pi = NULL ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- (*v_output) = v ; // return result v = NULL ; // set to NULL so LAGRAPH_FREE_ALL doesn't free it LAGRAPH_FREE_ALL ; // free all workspace (except for result v) return (GrB_SUCCESS) ; }
kdtree_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. *************************************************************************/ #ifndef RTABMAP_FLANN_KDTREE_INDEX_H_ #define RTABMAP_FLANN_KDTREE_INDEX_H_ #include <algorithm> #include <map> #include <cassert> #include <cstring> #include <stdarg.h> #include <cmath> #include "rtflann/general.h" #include "rtflann/algorithms/nn_index.h" #include "rtflann/util/dynamic_bitset.h" #include "rtflann/util/matrix.h" #include "rtflann/util/result_set.h" #include "rtflann/util/heap.h" #include "rtflann/util/allocator.h" #include "rtflann/util/random.h" #include "rtflann/util/saving.h" namespace rtflann { struct KDTreeIndexParams : public IndexParams { KDTreeIndexParams(int trees = 4) { (*this)["algorithm"] = FLANN_INDEX_KDTREE; (*this)["trees"] = trees; } }; /** * 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 KDTreeIndex : public NNIndex<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; typedef NNIndex<Distance> BaseClass; typedef bool needs_kdtree_distance; private: /*--------------------- Internal Data Structures --------------------------*/ struct Node { /** * Dimension used for subdivision. */ int divfeat; /** * The values used for subdivision. */ DistanceType divval; /** * Point data */ ElementType* point; /** * The child nodes. */ Node* child1, *child2; Node(){ child1 = NULL; child2 = NULL; } ~Node() { if (child1 != NULL) { child1->~Node(); child1 = NULL; } if (child2 != NULL) { child2->~Node(); child2 = NULL; } } private: template<typename Archive> void serialize(Archive& ar) { typedef KDTreeIndex<Distance> Index; Index* obj = static_cast<Index*>(ar.getObject()); ar & divfeat; ar & divval; bool leaf_node = false; if (Archive::is_saving::value) { leaf_node = ((child1==NULL) && (child2==NULL)); } ar & leaf_node; if (leaf_node) { if (Archive::is_loading::value) { point = obj->points_[divfeat]; } } if (!leaf_node) { if (Archive::is_loading::value) { child1 = new(obj->pool_) Node(); child2 = new(obj->pool_) Node(); } ar & *child1; ar & *child2; } } friend struct serialization::access; }; typedef Node* NodePtr; typedef BranchStruct<NodePtr, DistanceType> BranchSt; typedef BranchSt* Branch; public: /** * KDTree constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the kdtree algorithm */ KDTreeIndex(const IndexParams& params = KDTreeIndexParams(), Distance d = Distance() ) : BaseClass(params, d), mean_(NULL), var_(NULL) { trees_ = get_param(index_params_,"trees",4); } /** * KDTree constructor * * Params: * inputData = dataset with the input features * params = parameters passed to the kdtree algorithm */ KDTreeIndex(const Matrix<ElementType>& dataset, const IndexParams& params = KDTreeIndexParams(), Distance d = Distance() ) : BaseClass(params,d ), mean_(NULL), var_(NULL) { trees_ = get_param(index_params_,"trees",4); setDataset(dataset); } KDTreeIndex(const KDTreeIndex& other) : BaseClass(other), trees_(other.trees_) { tree_roots_.resize(other.tree_roots_.size()); for (size_t i=0;i<tree_roots_.size();++i) { copyTree(tree_roots_[i], other.tree_roots_[i]); } } KDTreeIndex& operator=(KDTreeIndex other) { this->swap(other); return *this; } /** * Standard destructor */ virtual ~KDTreeIndex() { freeIndex(); } BaseClass* clone() const { return new KDTreeIndex(*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 (size_t i=old_size;i<size_;++i) { for (int j = 0; j < trees_; j++) { addPointToTree(tree_roots_[j], i); } } } } flann_algorithm_t getType() const { return FLANN_INDEX_KDTREE; } template<typename Archive> void serialize(Archive& ar) { ar.setObject(this); ar & *static_cast<NNIndex<Distance>*>(this); ar & trees_; if (Archive::is_loading::value) { tree_roots_.resize(trees_); } for (size_t i=0;i<tree_roots_.size();++i) { if (Archive::is_loading::value) { tree_roots_[i] = new(pool_) Node(); } ar & *tree_roots_[i]; } if (Archive::is_loading::value) { index_params_["algorithm"] = getType(); index_params_["trees"] = trees_; } } void saveIndex(FILE* stream) { serialization::SaveArchive sa(stream); sa & *this; } void loadIndex(FILE* stream) { freeIndex(); serialization::LoadArchive la(stream); la & *this; } /** * Computes the inde memory usage * Returns: memory used by the index */ int usedMemory() const { return int(pool_.usedMemory+pool_.wastedMemory+size_*sizeof(int)); // pool memory and vind array memory } /** * 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 { int maxChecks = searchParams.checks; float epsError = 1+searchParams.eps; if (maxChecks==FLANN_CHECKS_UNLIMITED) { if (removed_) { getExactNeighbors<true>(result, vec, epsError); } else { getExactNeighbors<false>(result, vec, epsError); } } else { if (removed_) { getNeighbors<true>(result, vec, maxChecks, epsError); } else { getNeighbors<false>(result, vec, maxChecks, epsError); } } } #ifdef FLANN_KDTREE_MEM_OPT /** * 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, Heap<BranchSt>* heap) const { int maxChecks = searchParams.checks; float epsError = 1+searchParams.eps; if (maxChecks==FLANN_CHECKS_UNLIMITED) { if (removed_) { getExactNeighbors<true>(result, vec, epsError); } else { getExactNeighbors<false>(result, vec, epsError); } } else { if (removed_) { getNeighbors<true>(result, vec, maxChecks, epsError, heap); } else { getNeighbors<false>(result, vec, maxChecks, epsError, heap); } } } /** * @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 */ virtual 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); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } int count = 0; Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_); if (use_heap) { //#pragma omp parallel num_threads(params.cores) { KNNResultSet2<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, heap); 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 { std::vector<double> times(queries.rows); //#pragma omp parallel num_threads(params.cores) { KNNSimpleResultSet<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, heap); 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; } } std::sort(times.begin(), times.end()); } delete heap; 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 */ virtual 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()); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_); int count = 0; if (use_heap) { //#pragma omp parallel num_threads(params.cores) { KNNResultSet2<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, heap); 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) { KNNSimpleResultSet<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, heap); 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; } } } delete heap; return count; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indices of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ virtual int radiusSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; size_t num_neighbors = std::min(indices.cols, dists.cols); int max_neighbors = params.max_neighbors; if (max_neighbors<0) max_neighbors = num_neighbors; else max_neighbors = std::min(max_neighbors,(int)num_neighbors); Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_); if (max_neighbors==0) { //#pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); count += resultSet.size(); } } } else { // explicitly indicated to use unbounded radius result set // and we know there'll be enough room for resulting indices and dists if (params.max_neighbors<0 && (num_neighbors>=this->size())) { //#pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); size_t n = resultSet.size(); count += n; if (n>num_neighbors) n = num_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } else { // number of neighbors limited to max_neighbors //#pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, max_neighbors); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); size_t n = resultSet.size(); count += n; if ((int)n>max_neighbors) n = max_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } } delete heap; return count; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indices of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ virtual int radiusSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_); // just count neighbors if (params.max_neighbors==0) { //#pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); count += resultSet.size(); } } } else { if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); if (params.max_neighbors<0) { // search for all neighbors //#pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); size_t n = resultSet.size(); count += n; 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); } } } } else { // number of neighbors limited to max_neighbors //#pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, params.max_neighbors); //#pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, heap); size_t n = resultSet.size(); count += n; if ((int)n>params.max_neighbors) n = params.max_neighbors; 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); } } } } } delete heap; return count; } #endif protected: /** * Builds the index */ void buildIndexImpl() { // Create a permutable array of indices to the input vectors. std::vector<int> ind(size_); for (size_t i = 0; i < size_; ++i) { ind[i] = int(i); } mean_ = new DistanceType[veclen_]; var_ = new DistanceType[veclen_]; tree_roots_.resize(trees_); /* Construct the randomized trees. */ for (int i = 0; i < trees_; i++) { /* Randomize the order of vectors to allow for unbiased sampling. */ std::random_shuffle(ind.begin(), ind.end()); tree_roots_[i] = divideTree(&ind[0], int(size_) ); } delete[] mean_; delete[] var_; } void freeIndex() { for (size_t i=0;i<tree_roots_.size();++i) { // using placement new, so call destructor explicitly if (tree_roots_[i]!=NULL) tree_roots_[i]->~Node(); } pool_.free(); } private: void copyTree(NodePtr& dst, const NodePtr& src) { dst = new(pool_) Node(); dst->divfeat = src->divfeat; dst->divval = src->divval; if (src->child1==NULL && src->child2==NULL) { dst->point = points_[dst->divfeat]; dst->child1 = NULL; dst->child2 = NULL; } else { copyTree(dst->child1, src->child1); copyTree(dst->child2, src->child2); } } /** * Create a tree node that subdivides the list of vecs from vind[first] * to vind[last]. The routine is called recursively on each sublist. * Place a pointer to this new tree node in the location pTree. * * Params: pTree = the new node to create * first = index of the first vector * last = index of the last vector */ NodePtr divideTree(int* ind, int count) { NodePtr node = new(pool_) Node(); // allocate memory /* If too few exemplars remain, then make this a leaf node. */ if (count == 1) { node->child1 = node->child2 = NULL; /* Mark as leaf node. */ node->divfeat = *ind; /* Store index of this vec. */ node->point = points_[*ind]; } else { int idx; int cutfeat; DistanceType cutval; meanSplit(ind, count, idx, cutfeat, cutval); node->divfeat = cutfeat; node->divval = cutval; node->child1 = divideTree(ind, idx); node->child2 = divideTree(ind+idx, count-idx); } return node; } /** * Choose which feature to use in order to subdivide this set of vectors. * Make a random choice among those with the highest variance, and use * its variance as the threshold value. */ void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) { memset(mean_,0,veclen_*sizeof(DistanceType)); memset(var_,0,veclen_*sizeof(DistanceType)); /* Compute mean values. Only the first SAMPLE_MEAN values need to be sampled to get a good estimate. */ int cnt = std::min((int)SAMPLE_MEAN+1, count); for (int j = 0; j < cnt; ++j) { ElementType* v = points_[ind[j]]; for (size_t k=0; k<veclen_; ++k) { mean_[k] += v[k]; } } DistanceType div_factor = DistanceType(1)/cnt; for (size_t k=0; k<veclen_; ++k) { mean_[k] *= div_factor; } /* Compute variances (no need to divide by count). */ for (int j = 0; j < cnt; ++j) { ElementType* v = points_[ind[j]]; for (size_t k=0; k<veclen_; ++k) { DistanceType dist = v[k] - mean_[k]; var_[k] += dist * dist; } } /* Select one of the highest variance indices at random. */ cutfeat = selectDivision(var_); cutval = mean_[cutfeat]; int lim1, lim2; planeSplit(ind, count, cutfeat, cutval, lim1, lim2); if (lim1>count/2) index = lim1; else if (lim2<count/2) index = lim2; else index = count/2; /* If either list is empty, it means that all remaining features * are identical. Split in the middle to maintain a balanced tree. */ if ((lim1==count)||(lim2==0)) index = count/2; } /** * Select the top RAND_DIM largest values from v and return the index of * one of these selected at random. */ int selectDivision(DistanceType* v) { int num = 0; size_t topind[RAND_DIM]; /* Create a list of the indices of the top RAND_DIM values. */ for (size_t i = 0; i < veclen_; ++i) { if ((num < RAND_DIM)||(v[i] > v[topind[num-1]])) { /* Put this element at end of topind. */ if (num < RAND_DIM) { topind[num++] = i; /* Add to list. */ } else { topind[num-1] = i; /* Replace last element. */ } /* Bubble end value down to right location by repeated swapping. */ int j = num - 1; while (j > 0 && v[topind[j]] > v[topind[j-1]]) { std::swap(topind[j], topind[j-1]); --j; } } } /* Select a random integer in range [0,num-1], and return that index. */ int rnd = rand_int(num); return (int)topind[rnd]; } /** * Subdivide the list of points by a plane perpendicular on axe corresponding * to the 'cutfeat' dimension at 'cutval' position. * * On return: * dataset[ind[0..lim1-1]][cutfeat]<cutval * dataset[ind[lim1..lim2-1]][cutfeat]==cutval * dataset[ind[lim2..count]][cutfeat]>cutval */ void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) { /* Move vector indices for left subtree to front of list. */ int left = 0; int right = count-1; for (;; ) { while (left<=right && points_[ind[left]][cutfeat]<cutval) ++left; while (left<=right && points_[ind[right]][cutfeat]>=cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } lim1 = left; right = count-1; for (;; ) { while (left<=right && points_[ind[left]][cutfeat]<=cutval) ++left; while (left<=right && points_[ind[right]][cutfeat]>cutval) --right; if (left>right) break; std::swap(ind[left], ind[right]); ++left; --right; } lim2 = left; } /** * Performs an exact nearest neighbor search. The exact search performs a full * traversal of the tree. */ template<bool with_removed> void getExactNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, float epsError) const { // checkID -= 1; /* Set a different unique ID for each search. */ if (trees_ > 1) { fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); } if (trees_>0) { searchLevelExact<with_removed>(result, vec, tree_roots_[0], 0.0, epsError); } } /** * Performs the approximate nearest-neighbor search. The search is approximate * because the tree traversal is abandoned after a given number of descends in * the tree. */ template<bool with_removed> void getNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, int maxCheck, float epsError) const { int i; BranchSt branch; int checkCount = 0; Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_); DynamicBitset checked(size_); /* Search once through each tree down to root. */ for (i = 0; i < trees_; ++i) { searchLevel<with_removed>(result, vec, tree_roots_[i], 0, checkCount, maxCheck, epsError, heap, checked); } /* Keep searching other branches from heap until finished. */ while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { searchLevel<with_removed>(result, vec, branch.node, branch.mindist, checkCount, maxCheck, epsError, heap, checked); } delete heap; } #ifdef FLANN_KDTREE_MEM_OPT /** * Performs the approximate nearest-neighbor search. The search is approximate * because the tree traversal is abandoned after a given number of descends in * the tree. */ template<bool with_removed> void getNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, int maxCheck, float epsError, Heap<BranchSt>* heap) const { int i; BranchSt branch; int checkCount = 0; DynamicBitset checked(size_); heap->clear(); /* Search once through each tree down to root. */ for (i = 0; i < trees_; ++i) { searchLevel<with_removed>(result, vec, tree_roots_[i], 0, checkCount, maxCheck, epsError, heap, checked); } /* Keep searching other branches from heap until finished. */ while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { searchLevel<with_removed>(result, vec, branch.node, branch.mindist, checkCount, maxCheck, epsError, heap, checked); } } #endif /** * Search starting from a given node of the tree. Based on any mismatches at * higher levels, all exemplars below this level must have a distance of * at least "mindistsq". */ template<bool with_removed> void searchLevel(ResultSet<DistanceType>& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, float epsError, Heap<BranchSt>* heap, DynamicBitset& checked) const { if (result_set.worstDist()<mindist) { // printf("Ignoring branch, too far\n"); return; } /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL)&&(node->child2 == NULL)) { int index = node->divfeat; if (with_removed) { if (removed_points_.test(index)) return; } /* Do not check same node more than once when searching multiple trees. */ if ( checked.test(index) || ((checkCount>=maxCheck)&& result_set.full()) ) return; checked.set(index); checkCount++; DistanceType dist = distance_(node->point, vec, veclen_); result_set.addPoint(dist,index); return; } /* Which child branch should be taken first? */ ElementType val = vec[node->divfeat]; DistanceType diff = val - node->divval; NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; /* Create a branch record for the branch not taken. Add distance of this feature boundary (we don't attempt to correct for any use of this feature in a parent node, which is unlikely to happen and would have only a small effect). Don't bother adding more branches to heap after halfway point, as cost of adding exceeds their value. */ DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); // if (2 * checkCount < maxCheck || !result.full()) { if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { heap->insert( BranchSt(otherChild, new_distsq) ); } /* Call recursively to search next level down. */ searchLevel<with_removed>(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); } /** * Performs an exact search in the tree starting from a node. */ template<bool with_removed> void searchLevelExact(ResultSet<DistanceType>& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) const { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL)&&(node->child2 == NULL)) { int index = node->divfeat; if (with_removed) { if (removed_points_.test(index)) return; // ignore removed points } DistanceType dist = distance_(node->point, vec, veclen_); result_set.addPoint(dist,index); return; } /* Which child branch should be taken first? */ ElementType val = vec[node->divfeat]; DistanceType diff = val - node->divval; NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; /* Create a branch record for the branch not taken. Add distance of this feature boundary (we don't attempt to correct for any use of this feature in a parent node, which is unlikely to happen and would have only a small effect). Don't bother adding more branches to heap after halfway point, as cost of adding exceeds their value. */ DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); /* Call recursively to search next level down. */ searchLevelExact<with_removed>(result_set, vec, bestChild, mindist, epsError); if (mindist*epsError<=result_set.worstDist()) { searchLevelExact<with_removed>(result_set, vec, otherChild, new_distsq, epsError); } } void addPointToTree(NodePtr node, int ind) { ElementType* point = points_[ind]; if ((node->child1==NULL) && (node->child2==NULL)) { ElementType* leaf_point = node->point; ElementType max_span = 0; size_t div_feat = 0; for (size_t i=0;i<veclen_;++i) { ElementType span = std::abs(point[i]-leaf_point[i]); if (span > max_span) { max_span = span; div_feat = i; } } NodePtr left = new(pool_) Node(); left->child1 = left->child2 = NULL; NodePtr right = new(pool_) Node(); right->child1 = right->child2 = NULL; if (point[div_feat]<leaf_point[div_feat]) { left->divfeat = ind; left->point = point; right->divfeat = node->divfeat; right->point = node->point; } else { left->divfeat = node->divfeat; left->point = node->point; right->divfeat = ind; right->point = point; } node->divfeat = div_feat; node->divval = (point[div_feat]+leaf_point[div_feat])/2; node->child1 = left; node->child2 = right; } else { if (point[node->divfeat]<node->divval) { addPointToTree(node->child1,ind); } else { addPointToTree(node->child2,ind); } } } private: void swap(KDTreeIndex& other) { BaseClass::swap(other); std::swap(trees_, other.trees_); std::swap(tree_roots_, other.tree_roots_); std::swap(pool_, other.pool_); } private: enum { /** * To improve efficiency, only SAMPLE_MEAN random values are used to * compute the mean and variance at each level when building a tree. * A value of 100 seems to perform as well as using all values. */ SAMPLE_MEAN = 100, /** * Top random dimensions to consider * * When creating random trees, the dimension on which to subdivide is * selected at random from among the top RAND_DIM dimensions with the * highest variance. A value of 5 works well. */ RAND_DIM=5 }; /** * Number of randomized trees that are used */ int trees_; DistanceType* mean_; DistanceType* var_; /** * Array of k-d trees used to find neighbours. */ std::vector<NodePtr> tree_roots_; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool_; USING_BASECLASS_SYMBOLS }; // class KDTreeIndex } #endif //FLANN_KDTREE_INDEX_H_
GB_AxB_dot3.c
//------------------------------------------------------------------------------ // GB_AxB_dot3: compute C<M> = A'*B in parallel //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // This function only computes C<M>=A'*B. The mask must be present, and not // complemented. The mask is always applied. #include "GB_mxm.h" #ifndef GBCOMPACT #include "GB_AxB__include.h" #endif #define GB_FREE_WORK \ { \ GB_FREE_MEMORY (TaskList, max_ntasks+1, sizeof (GB_task_struct)) ; \ } #define GB_FREE_ALL \ { \ GB_FREE_WORK ; \ GB_MATRIX_FREE (Chandle) ; \ } GrB_Info GB_AxB_dot3 // C<M> = A'*B using dot product method ( GrB_Matrix *Chandle, // output matrix const GrB_Matrix M, // mask matrix const bool Mask_struct, // if true, use the only structure of M const GrB_Matrix A, // input matrix const GrB_Matrix B, // input matrix const GrB_Semiring semiring, // semiring that defines C=A*B const bool flipxy, // if true, do z=fmult(b,a) vs fmult(a,b) GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT (Chandle != NULL) ; ASSERT (*Chandle == NULL) ; ASSERT_MATRIX_OK (M, "M for dot3 A'*B", GB0) ; ASSERT_MATRIX_OK (A, "A for dot3 A'*B", GB0) ; ASSERT_MATRIX_OK (B, "B for dot3 A'*B", GB0) ; ASSERT (!GB_PENDING (M)) ; ASSERT (!GB_ZOMBIES (M)) ; ASSERT (!GB_PENDING (A)) ; ASSERT (!GB_ZOMBIES (A)) ; ASSERT (!GB_PENDING (B)) ; ASSERT (!GB_ZOMBIES (B)) ; ASSERT_SEMIRING_OK (semiring, "semiring for numeric A'*B", GB0) ; ASSERT (A->vlen == B->vlen) ; int ntasks, max_ntasks = 0, nthreads ; GB_task_struct *TaskList = NULL ; //-------------------------------------------------------------------------- // get the semiring operators //-------------------------------------------------------------------------- GrB_BinaryOp mult = semiring->multiply ; GrB_Monoid add = semiring->add ; ASSERT (mult->ztype == add->op->ztype) ; bool op_is_first = mult->opcode == GB_FIRST_opcode ; bool op_is_second = mult->opcode == GB_SECOND_opcode ; bool op_is_pair = mult->opcode == GB_PAIR_opcode ; bool A_is_pattern = false ; bool B_is_pattern = false ; if (flipxy) { // z = fmult (b,a) will be computed A_is_pattern = op_is_first || op_is_pair ; B_is_pattern = op_is_second || op_is_pair ; ASSERT (GB_IMPLIES (!A_is_pattern, GB_Type_compatible (A->type, mult->ytype))) ; ASSERT (GB_IMPLIES (!B_is_pattern, GB_Type_compatible (B->type, mult->xtype))) ; } else { // z = fmult (a,b) will be computed A_is_pattern = op_is_second || op_is_pair ; B_is_pattern = op_is_first || op_is_pair ; ASSERT (GB_IMPLIES (!A_is_pattern, GB_Type_compatible (A->type, mult->xtype))) ; ASSERT (GB_IMPLIES (!B_is_pattern, GB_Type_compatible (B->type, mult->ytype))) ; } (*Chandle) = NULL ; //-------------------------------------------------------------------------- // get M, A, and B //-------------------------------------------------------------------------- const int64_t *GB_RESTRICT Mp = M->p ; const int64_t *GB_RESTRICT Mh = M->h ; const int64_t *GB_RESTRICT Mi = M->i ; const GB_void *GB_RESTRICT Mx = (Mask_struct ? NULL : (M->x)) ; const size_t msize = M->type->size ; const int64_t mvlen = M->vlen ; const int64_t mvdim = M->vdim ; const int64_t mnz = GB_NNZ (M) ; const int64_t mnvec = M->nvec ; const bool M_is_hyper = M->is_hyper ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ah = A->h ; // const int64_t *GB_RESTRICT Ai = A->i ; // const int64_t avlen = A->vlen ; // const int64_t avdim = A->vdim ; // const int64_t anz = GB_NNZ (A) ; const int64_t anvec = A->nvec ; const bool A_is_hyper = A->is_hyper ; const int64_t *GB_RESTRICT Bp = B->p ; const int64_t *GB_RESTRICT Bh = B->h ; // const int64_t *GB_RESTRICT Bi = B->i ; // const int64_t bvlen = B->vlen ; // const int64_t bvdim = B->vdim ; // const int64_t bnz = GB_NNZ (B) ; const int64_t bnvec = B->nvec ; const bool B_is_hyper = B->is_hyper ; //-------------------------------------------------------------------------- // allocate C, the same size and # of entries as M //-------------------------------------------------------------------------- GrB_Type ctype = add->op->ztype ; int64_t cvlen = mvlen ; int64_t cvdim = mvdim ; int64_t cnz = mnz ; int64_t cnvec = mnvec ; GB_CREATE (Chandle, ctype, cvlen, cvdim, GB_Ap_malloc, true, GB_SAME_HYPER_AS (M_is_hyper), M->hyper_ratio, cnvec, cnz+1, // add one to cnz for GB_cumsum of Cwork in GB_AxB_dot3_slice true, Context) ; if (info != GrB_SUCCESS) { // out of memory GB_FREE_ALL ; return (info) ; } GrB_Matrix C = (*Chandle) ; int64_t *GB_RESTRICT Cp = C->p ; int64_t *GB_RESTRICT Ch = C->h ; int64_t *GB_RESTRICT Cwork = C->i ; // use C->i as workspace //-------------------------------------------------------------------------- // determine the # of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; //-------------------------------------------------------------------------- // copy Mp and Mh into C //-------------------------------------------------------------------------- // FUTURE:: C->p and C->h could be shallow copies of M->p and M->h, which // could same some time and memory if C is then, say, transposed by // GB_accum_mask later on. nthreads = GB_nthreads (cnvec, chunk, nthreads_max) ; GB_memcpy (Cp, Mp, (cnvec+1) * sizeof (int64_t), nthreads) ; if (M_is_hyper) { GB_memcpy (Ch, Mh, cnvec * sizeof (int64_t), nthreads) ; } C->magic = GB_MAGIC ; C->nvec_nonempty = M->nvec_nonempty ; C->nvec = M->nvec ; //-------------------------------------------------------------------------- // construct the tasks for the first phase //-------------------------------------------------------------------------- nthreads = GB_nthreads (cnz, chunk, nthreads_max) ; GB_OK (GB_AxB_dot3_one_slice (&TaskList, &max_ntasks, &ntasks, &nthreads, M, Context)) ; //-------------------------------------------------------------------------- // phase1: estimate the work to compute each entry in C //-------------------------------------------------------------------------- // The work to compute C(i,j) is held in Cwork [p], if C(i,j) appears in // as the pth entry in C. int taskid; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- // GB_GET_TASK_DESCRIPTOR ; int64_t kfirst = TaskList [taskid].kfirst ; int64_t klast = TaskList [taskid].klast ; bool fine_task = (klast == -1) ; if (fine_task) { // a fine task operates on a slice of a single vector klast = kfirst ; } int64_t bpleft = 0 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get j, the kth vector of C and M //------------------------------------------------------------------ int64_t j = (Mh == NULL) ? k : Mh [k] ; GB_GET_VECTOR (pM, pM_end, pM, pM_end, Mp, k) ; //------------------------------------------------------------------ // get B(:,j) //------------------------------------------------------------------ int64_t pB, pB_end ; GB_lookup (B_is_hyper, Bh, Bp, &bpleft, bnvec-1, j, &pB, &pB_end) ; int64_t bjnz = pB_end - pB ; //------------------------------------------------------------------ // estimate the work to compute each entry of C(:,j) //------------------------------------------------------------------ // A decent estimate of the work to compute the dot product C(i,j) // = A(:,i)'*B(:,j) is min (|A(:,i)|, |B(:,j)|) + 1. This is a // lower bound. The actual work could require a binary search of // either A(:,i) or B(:,j), or a merge of the two vectors. Or it // could require no work at all if all entries in A(:,i) appear // before all entries in B(:,j), or visa versa. No work is done if // M(i,j)=0. A more accurate estimate is possible to compute, // following the different methods used in // Template/GB_AxB_dot_cij.c. if (bjnz == 0) { // B(:,j) is empty, so C(:,j) is empty as well. No work is to // be done, but it still takes unit work to flag each C(:,j) as // a zombie for ( ; pM < pM_end ; pM++) { Cwork [pM] = 1 ; } } else { int64_t apleft = 0 ; for ( ; pM < pM_end ; pM++) { int64_t work = 1 ; if (GB_mcast (Mx, pM, msize)) { int64_t pA, pA_end, i = Mi [pM] ; GB_lookup (A_is_hyper, Ah, Ap, &apleft, anvec-1, i, &pA, &pA_end) ; int64_t ajnz = pA_end - pA ; work += GB_IMIN (ajnz, bjnz) ; } Cwork [pM] = work ; } } } } //-------------------------------------------------------------------------- // free the current tasks and construct the tasks for the second phase //-------------------------------------------------------------------------- GB_FREE_MEMORY (TaskList, max_ntasks+1, sizeof (GB_task_struct)) ; GB_OK (GB_AxB_dot3_slice (&TaskList, &max_ntasks, &ntasks, &nthreads, C, Context)) ; GBBURBLE ("nthreads %d ntasks %d ", nthreads, ntasks) ; //-------------------------------------------------------------------------- // C<M> = A'*B, via masked dot product method and built-in semiring //-------------------------------------------------------------------------- bool done = false ; #ifndef GBCOMPACT //-------------------------------------------------------------------------- // define the worker for the switch factory //-------------------------------------------------------------------------- #define GB_Adot3B(add,mult,xyname) GB_Adot3B_ ## add ## mult ## xyname #define GB_AxB_WORKER(add,mult,xyname) \ { \ info = GB_Adot3B (add,mult,xyname) (C, M, Mask_struct, \ A, A_is_pattern, B, B_is_pattern, \ TaskList, ntasks, nthreads) ; \ done = (info != GrB_NO_VALUE) ; \ } \ break ; //-------------------------------------------------------------------------- // launch the switch factory //-------------------------------------------------------------------------- GB_Opcode mult_opcode, add_opcode ; GB_Type_code xycode, zcode ; if (GB_AxB_semiring_builtin (A, A_is_pattern, B, B_is_pattern, semiring, flipxy, &mult_opcode, &add_opcode, &xycode, &zcode)) { #include "GB_AxB_factory.c" } #endif //-------------------------------------------------------------------------- // C<M> = A'*B, via masked dot product method and typecasting //-------------------------------------------------------------------------- if (!done) { GB_BURBLE_MATRIX (C, "generic ") ; //---------------------------------------------------------------------- // get operators, functions, workspace, contents of A, B, C, and M //---------------------------------------------------------------------- GxB_binary_function fmult = mult->function ; GxB_binary_function fadd = add->op->function ; size_t csize = C->type->size ; size_t asize = A_is_pattern ? 0 : A->type->size ; size_t bsize = B_is_pattern ? 0 : B->type->size ; size_t xsize = mult->xtype->size ; size_t ysize = mult->ytype->size ; // scalar workspace: because of typecasting, the x/y types need not // be the same as the size of the A and B types. // flipxy false: aki = (xtype) A(k,i) and bkj = (ytype) B(k,j) // flipxy true: aki = (ytype) A(k,i) and bkj = (xtype) B(k,j) size_t aki_size = flipxy ? ysize : xsize ; size_t bkj_size = flipxy ? xsize : ysize ; GB_void *GB_RESTRICT terminal = add->terminal ; GB_cast_function cast_A, cast_B ; if (flipxy) { // A is typecasted to y, and B is typecasted to x cast_A = A_is_pattern ? NULL : GB_cast_factory (mult->ytype->code, A->type->code) ; cast_B = B_is_pattern ? NULL : GB_cast_factory (mult->xtype->code, B->type->code) ; } else { // A is typecasted to x, and B is typecasted to y cast_A = A_is_pattern ? NULL : GB_cast_factory (mult->xtype->code, A->type->code) ; cast_B = B_is_pattern ? NULL : GB_cast_factory (mult->ytype->code, B->type->code) ; } //---------------------------------------------------------------------- // C<M> = A'*B via dot products, function pointers, and typecasting //---------------------------------------------------------------------- // aki = A(k,i), located in Ax [pA] #define GB_GETA(aki,Ax,pA) \ GB_void aki [GB_VLA(aki_size)] ; \ if (!A_is_pattern) cast_A (aki, Ax +((pA)*asize), asize) // bkj = B(k,j), located in Bx [pB] #define GB_GETB(bkj,Bx,pB) \ GB_void bkj [GB_VLA(bkj_size)] ; \ if (!B_is_pattern) cast_B (bkj, Bx +((pB)*bsize), bsize) // break if cij reaches the terminal value #define GB_DOT_TERMINAL(cij) \ if (terminal != NULL && memcmp (cij, terminal, csize) == 0) \ { \ break ; \ } // C(i,j) = A(i,k) * B(k,j) #define GB_MULT(cij, aki, bkj) \ GB_MULTIPLY (cij, aki, bkj) // C(i,j) += A(i,k) * B(k,j) #define GB_MULTADD(cij, aki, bkj) \ GB_void zwork [GB_VLA(csize)] ; \ GB_MULTIPLY (zwork, aki, bkj) ; \ fadd (cij, cij, zwork) // define cij for each task #define GB_CIJ_DECLARE(cij) \ GB_void cij [GB_VLA(csize)] // address of Cx [p] #define GB_CX(p) Cx +((p)*csize) // save the value of C(i,j) #define GB_CIJ_SAVE(cij,p) \ memcpy (GB_CX (p), cij, csize) #define GB_ATYPE GB_void #define GB_BTYPE GB_void #define GB_CTYPE GB_void // no vectorization #define GB_PRAGMA_VECTORIZE #define GB_PRAGMA_VECTORIZE_DOT if (flipxy) { #define GB_MULTIPLY(z,x,y) fmult (z,y,x) #include "GB_AxB_dot3_template.c" #undef GB_MULTIPLY } else { #define GB_MULTIPLY(z,x,y) fmult (z,x,y) #include "GB_AxB_dot3_template.c" #undef GB_MULTIPLY } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- if (C->nzombies > 0) { // C has been created with zombies, so place it in the queue GB_CRITICAL (GB_queue_insert (C)) ; } GB_FREE_WORK ; ASSERT_MATRIX_OK (C, "dot3: C<M> = A'*B output", GB0) ; ASSERT (*Chandle == C) ; ASSERT (GB_ZOMBIES_OK (C)) ; ASSERT (!GB_PENDING (C)) ; return (GrB_SUCCESS) ; }
mm_p_parallel_for.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <omp.h> int main(int argc, char* argv[]) { printf("entered main function!"); int size = 1024; int (*matrix_A)[size] = malloc(sizeof(int[size][size])); int (*matrix_B)[size] = malloc(sizeof(int[size][size])); int (*result)[size] = malloc(sizeof(int[size][size])); printf("const set-up done!"); //Initialize matrix: for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { matrix_A[i][j] = rand(); matrix_B[i][j] = rand(); result[i][j] = 0; } } printf("matrix initialization done!"); //Matrix multiplication double t1 = omp_get_wtime(); omp_set_num_threads(16); #pragma omp parallel shared(matrix_A,matrix_B,result) { #pragma omp for schedule(dynamic) for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { result[i][j] += matrix_A[i][k] * matrix_B[k][j]; } } } } printf("matrix multiplication done!"); double t2 = omp_get_wtime(); printf("%f\n", t2 - t1); free(matrix_A); free(matrix_B); free(result); return 0; }
symgs.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ void smooth(level_type * level, int phi_id, int rhs_id, double a, double b){ int box,s; for(s=0;s<2*NUM_SMOOTHS;s++){ // there are two sweeps (forward/backward) per GS smooth exchange_boundary(level,phi_id,stencil_is_star_shaped()); apply_BCs(level,phi_id,stencil_is_star_shaped()); uint64_t _timeStart = CycleTime(); #ifdef _OPENMP #pragma omp parallel for private(box) #endif for(box=0;box<level->num_my_boxes;box++){ int i,j,k; const int ghosts = level->box_ghosts; const int jStride = level->my_boxes[box].jStride; const int kStride = level->my_boxes[box].kStride; const int dim = level->my_boxes[box].dim; const double h2inv = 1.0/(level->h*level->h); double * __restrict__ phi = level->my_boxes[box].vectors[ phi_id] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point const double * __restrict__ rhs = level->my_boxes[box].vectors[ rhs_id] + ghosts*(1+jStride+kStride); const double * __restrict__ alpha = level->my_boxes[box].vectors[VECTOR_ALPHA ] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_i = level->my_boxes[box].vectors[VECTOR_BETA_I] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_j = level->my_boxes[box].vectors[VECTOR_BETA_J] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_k = level->my_boxes[box].vectors[VECTOR_BETA_K] + ghosts*(1+jStride+kStride); const double * __restrict__ Dinv = level->my_boxes[box].vectors[VECTOR_DINV ] + ghosts*(1+jStride+kStride); const double * __restrict__ valid = level->my_boxes[box].vectors[VECTOR_VALID ] + ghosts*(1+jStride+kStride); // cell is inside the domain if( (s&0x1)==0 ){ // forward sweep... hard to thread for(k=0;k<dim;k++){ for(j=0;j<dim;j++){ for(i=0;i<dim;i++){ int ijk = i + j*jStride + k*kStride; double Ax = apply_op_ijk(phi); phi[ijk] = phi[ijk] + Dinv[ijk]*(rhs[ijk]-Ax); }}} }else{ // backward sweep... hard to thread for(k=dim-1;k>=0;k--){ for(j=dim-1;j>=0;j--){ for(i=dim-1;i>=0;i--){ int ijk = i + j*jStride + k*kStride; double Ax = apply_op_ijk(phi); phi[ijk] = phi[ijk] + Dinv[ijk]*(rhs[ijk]-Ax); }}} } } // boxes level->cycles.smooth += (uint64_t)(CycleTime()-_timeStart); } // s-loop } //------------------------------------------------------------------------------------------------------------------------------
a2a_sources.h
#ifndef _A2A_SOURCES_H #define _A2A_SOURCES_H CPS_START_NAMESPACE //Spatial source structure in *momentum-space*. Should assign the same value to both flavors if G-parity //3D complex field. Defined for a *single flavor* if GPBC template<typename mf_Complex,typename DimensionPolicy = SpatialPolicy, typename FieldAllocPolicy = StandardAllocPolicy, typename my_enable_if<DimensionPolicy::EuclideanDimension == 3, int>::type = 0> class A2Asource{ public: typedef CPSfield<mf_Complex,1,DimensionPolicy,OneFlavorPolicy,FieldAllocPolicy> FieldType; protected: FieldType *src; public: A2Asource(const typename FieldType::InputParamType &params){ setup(params); } inline void setup(const typename FieldType::InputParamType &params){ src = new FieldType(params); } A2Asource(): src(NULL){} A2Asource(const A2Asource &cp): src(cp.src == NULL ? NULL : new FieldType(*cp.src)){} ~A2Asource(){ if(src != NULL) delete src; } inline const mf_Complex & siteComplex(const int site) const{ return *src->site_ptr(site); } inline const int nsites() const{ return src->nsites(); } template< typename extComplexType, typename extDimPol, typename extAllocPol> void importSource(const A2Asource<extComplexType,extDimPol,extAllocPol> &from){ src->importField(*from.src); } FieldType & getSource(){ return *src; } //For testing //Periodic modulus operation inline static int pmod(const int x, const int Lx){ return x <= Lx/2 ? x : Lx-x; // 0 ... L/2-1, L/2, L/2-1, ... 1 } //Periodic coordinate relative to boundary inline static int pcoord(const int x, const int Lx){ return (x + Lx/2) % Lx - Lx/2; // 0 ... L/2-1, -L/2, 1-L/2, ... -1 includes sign. Note convention for sign at L/2 } //Radial coordinate static Float pmodr(const int x[3], const int L[3]){ Float ssq =0.; for(int i=0;i<3;i++){ int sr = pmod(x[i],L[i]); ssq += sr*sr; } return sqrt(ssq); } //Spherical coordinates that know about the periodicity of the lattice static void pmodspherical(Float &r, Float &theta, Float &phi, const int x[3], const int L[3]){ int xp[3]; Float ssq = 0.; for(int i=0;i<3;i++){ xp[i] = pcoord(x[i],L[i]); ssq += xp[i]*xp[i]; } r = sqrt(ssq); theta = acos(xp[2]/r); phi = atan(xp[1]/xp[0]); } }; //Use CRTP for 'setSite' method which should be specialized according to the source type template<typename FieldPolicies, typename Child> class A2AsourceBase: public A2Asource<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>{ public: typedef FieldPolicies Policies; typedef typename A2Asource<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>::FieldType::InputParamType FieldParamType; A2AsourceBase(const FieldParamType &p): A2Asource<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>(p){}; A2AsourceBase(): A2Asource<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>(){}; //SOURCE IS NOT SETUP A2AsourceBase(const A2AsourceBase &r): A2Asource<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>(r){} void fft_source(){ assert(this->src != NULL); int glb_size[3]; for(int i=0;i<3;i++) glb_size[i] = GJP.Nodes(i)*GJP.NodeSites(i); //Generate a global 4d source CPSglobalComplexSpatial<cps::ComplexD,OneFlavorPolicy> glb; //always of this type glb.zero(); #pragma omp_parallel for for(int i=0;i<glb.nsites();i++){ int x[3]; glb.siteUnmap(i,x); *glb.site_ptr(i) = static_cast<Child const*>(this)->value(x,glb_size); } //Perform the FFT and pull out this nodes subvolume glb.fft(); glb.scatter<typename FieldPolicies::ComplexType, typename FieldPolicies::DimensionPolicy, typename FieldPolicies::AllocPolicy>(*this->src); } }; template<typename FieldPolicies, typename Derived> class A2AhydrogenSourceBase: public A2AsourceBase<FieldPolicies, Derived >{ protected: Float radius; public: typedef FieldPolicies Policies; typedef typename A2AsourceBase<FieldPolicies, Derived >::FieldParamType FieldParamType; typedef typename Policies::ComplexType ComplexType; A2AhydrogenSourceBase(const Float _radius, const FieldParamType &field_params): radius(_radius), A2AsourceBase<FieldPolicies, Derived >(field_params){ this->fft_source(); } A2AhydrogenSourceBase(): radius(0.), A2AsourceBase<FieldPolicies, Derived >(){} //src is not setup A2AhydrogenSourceBase(const A2AhydrogenSourceBase &r): radius(r.radius), A2AsourceBase<FieldPolicies, Derived >(r){} //Setup the source if the default constructor was used void setup(const Float _radius, const FieldParamType &field_params){ this->A2AsourceBase<FieldPolicies, Derived >::setup(field_params); radius = _radius; this->fft_source(); } void setup(const Float radius){ return setup(radius, NullObject()); } inline void siteFmat(FlavorMatrixGeneral<typename Policies::ComplexType> &out, const int site) const{ out(0,0) = out(1,1) = this->siteComplex(site); out(0,1) = out(1,0) = typename Policies::ComplexType(0); } }; //Exponential (hydrogen wavefunction) source //SrcParams is just a Float for the radius template<typename FieldPolicies = StandardSourcePolicies> class A2AexpSource: public A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >{ public: typedef FieldPolicies Policies; typedef typename A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >::FieldParamType FieldParamType; typedef typename Policies::ComplexType ComplexType; inline cps::ComplexD value(const int site[3], const int glb_size[3]) const{ Float v = this->pmodr(site,glb_size)/this->radius; v = exp(-v)/(glb_size[0]*glb_size[1]*glb_size[2]); return ComplexD(v,0); } A2AexpSource(const Float _radius, const FieldParamType &field_params): A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >(_radius,field_params){ } A2AexpSource(const Float _radius): A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >(_radius, NullObject()){ } A2AexpSource(): A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >(){} //src is not setup A2AexpSource(const A2AexpSource &r): A2AhydrogenSourceBase<FieldPolicies, A2AexpSource<FieldPolicies> >(r){} }; //General s-wave hydrogen wavefunction source template<typename FieldPolicies = StandardSourcePolicies> class A2AhydrogenSource: public A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >{ int n, l, m; public: typedef FieldPolicies Policies; typedef typename A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >::FieldParamType FieldParamType; typedef typename Policies::ComplexType ComplexType; inline static cps::ComplexD zexp(const Float phi){ return cps::ComplexD( cos(phi), sin(phi) ); } inline cps::ComplexD value(const int site[3], const int glb_size[3]) const{ assert(n>=0 && n <= 3 && l>=0 && l <= n-1 && abs(m) <= l); Float a0 = this->radius; Float na0 = a0 * n; Float r, theta, phi; if(l==0) r = this->pmodr(site,glb_size); //don't need theta and phi for s-wave else this->pmodspherical(r,theta,phi,site,glb_size); cps::ComplexD v( exp(-r/na0)/(glb_size[0]*glb_size[1]*glb_size[2]), 0.); switch(n){ case 1: break; case 2: switch(l){ case 0: v *= (2. - r/a0); break; case 1: v *= r/a0; switch(m){ case 0: v *= cos(theta); break; case 1: case -1: v *= sin(theta) * zexp(phi*m); break; }//m }//l break; case 3: switch(l){ case 0: v *= (27. - 18.*r/a0 + 2.*r*r/a0/a0); break; case 1: v *= (6. -r/a0)*r/a0; switch(m){ case 0: v *= cos(theta); break; case 1: case -1: v *= sin(theta) * zexp(phi*m); break; }//m case 2: v *= r*r/a0/a0; switch(m){ case 0: v *= 3.*cos(theta)*cos(theta) - 1.; break; case 1: case -1: v *= sin(theta) * cos(theta) * zexp(phi*m); break; case 2: case -2: v *= sin(theta) * sin(theta) * zexp(phi*m); break; }//m }//l break; }//n return v; } A2AhydrogenSource(const int _n, const int _l, const int _m, const Float _radius, const FieldParamType &field_params): n(_n), l(_l), m(_m), A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >(_radius,field_params){ } A2AhydrogenSource(const int _n, const int _l, const int _m, const Float _radius): n(_n), l(_l), m(_m), A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >(_radius, NullObject()){ } A2AhydrogenSource(): A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >(){} //src is not setup A2AhydrogenSource(const A2AhydrogenSource &r): n(r.n), l(r.l), m(r.m), A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >(r){} void setup(const int _n, const int _l, const int _m, const Float _radius, const FieldParamType &field_params){ n = _n; l=_l; m=_m; this->A2AhydrogenSourceBase<FieldPolicies, A2AhydrogenSource<FieldPolicies> >::setup(_radius,field_params); } void setup(const int _n, const int _l, const int _m, const Float radius){ return setup(_n,_l,_m, radius, NullObject()); } }; //Box source. Unflavored so ignore second flav //SrcParams is std::vector<Float> for the extents x,y,z . *These must be even numbers* (checked) template<typename FieldPolicies = StandardSourcePolicies> class A2AboxSource: public A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >{ int box_size[3]; void box_setup_fft(const int _box_size[3]){ for(int i=0;i<3;i++){ if(_box_size[i] % 2 == 1){ ERR.General("A2AboxSource","A2AboxSource","box size must be multiple of 2"); } box_size[i] = _box_size[i]; } this->fft_source(); } public: typedef FieldPolicies Policies; typedef typename A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >::FieldParamType FieldParamType; typedef typename Policies::ComplexType ComplexType; cps::ComplexD value(const int site[3], const int glb_size[3]) const{ bool inbox = true; int V = glb_size[0]*glb_size[1]*glb_size[2]; for(int i=0;i<3;i++){ int bdist = this->pmod(site[i],glb_size[i]); if(bdist > box_size[i]){ inbox = false; break; } } if(inbox) return cps::ComplexD(1./V); } A2AboxSource(const int _box_size[3],const FieldParamType &field_params): A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >(field_params){ this->box_setup_fft(_box_size); } A2AboxSource(const int _box_size[3]): A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >(NullObject()){ this->box_setup_fft(_box_size); }//syntatic sugar to avoid creating a NullObject A2AboxSource(const A2AboxSource &r): A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >(r){ memcpy(box_size,r.box_size,3*sizeof(int)); } void setup(const int _box_size[3], const FieldParamType &field_params = NullObject()){ this->A2AsourceBase<FieldPolicies, A2AboxSource<FieldPolicies> >::setup(field_params); this->box_setup_fft(_box_size); } inline void siteFmat(FlavorMatrixGeneral<typename Policies::ComplexType> &out, const int site) const{ out(0,0) = out(1,1) = this->siteComplex(site); out(0,1) = out(1,0) = typename Policies::ComplexType(0); } }; //Splat a cps::ComplexD onto a SIMD type. Just a plain copy for non-SIMD complex types #ifdef USE_GRID template<typename ComplexType> inline void SIMDsplat(ComplexType &to, const cps::ComplexD &from, typename my_enable_if< _equal< typename ComplexClassify<ComplexType>::type, grid_vector_complex_mark >::value, int>::type = 0){ vsplat(to,from); } #endif template<typename ComplexType> inline void SIMDsplat(ComplexType &to, const cps::ComplexD &from, typename my_enable_if< !_equal< typename ComplexClassify<ComplexType>::type, grid_vector_complex_mark >::value, int>::type = 0){ to = ComplexType(from.real(),from.imag()); } //Daiqian's original implementation sets the (1 +/- sigma_2) flavor projection on G-parity fields to unity when the two fermion fields coincide. //I'm not sure this is actually necessary, but I need to be able to reproduce his numbers //Derived class should setup the sources template<typename SourceType> class A2AflavorProjectedSource: public SourceType{ public: typedef typename SourceType::FieldParamType FieldParamType; typedef typename SourceType::Policies::ComplexType ComplexType; protected: int sign; ComplexType *val000; virtual void dummy() = 0; //make sure this class can't be instantiated directly void setup_projected_src_info(const int p[3]){ sign = getProjSign(p); int zero[3] = {0,0,0}; int L[3] = {GJP.NodeSites(0)*GJP.Nodes(0), GJP.NodeSites(1)*GJP.Nodes(1), GJP.NodeSites(2)*GJP.Nodes(2) }; cps::ComplexD v = this->value(zero,L); SIMDsplat(*val000,v); } public: A2AflavorProjectedSource(): val000( (ComplexType*)memalign(128,sizeof(ComplexType)) ), SourceType(){} ~A2AflavorProjectedSource(){ free(val000); } A2AflavorProjectedSource(const A2AflavorProjectedSource &r): val000( (ComplexType*)memalign(128,sizeof(ComplexType)) ), sign(r.sign), SourceType(r){ *val000 = *r.val000; } //Assumes momenta are in units of \pi/2L, and must be *odd integer* (checked) inline static int getProjSign(const int p[3]){ if(!GJP.Gparity()){ ERR.General("A2AflavorProjectedSource","getProjSign","Requires GPBC in at least one direction\n"); } //Sign is exp(i\pi n_p) //where n_p is the solution to p_j = \pi/2L( 1 + 2n_p ) //Must be consistent for all j int np; for(int j=0;j<3;j++){ if(GJP.Bc(j)!=BND_CND_GPARITY) continue; if(abs(p[j]) %2 != 1){ ERR.General("A2AflavorProjectedSource","getProjSign","Component %d of G-parity momentum (%d,%d,%d) is invalid as it is not an odd integer!\n",j,p[0],p[1],p[2]); } int npj = (p[j] - 1)/2; if(j == 0) np = npj; else if(abs(npj)%2 != abs(np)%2){ ERR.General("A2AflavorProjectedSource","getProjSign","Momentum component %d of G-parity momentum (%d,%d,%d) is invalid because it doesn't differ from component 0 by multiple of 2pi (4 in these units). Got np(0)=%d, np(j)=%d\n",j,p[0],p[1],p[2],np,npj); } } int sgn = (abs(np) % 2 == 0 ? 1 : -1); //exp(i\pi n_p) = exp(-i\pi n_p) for all integer n_p if(!UniqueID()){ printf("A2AflavorProjectedSource::getProjSign got sign %d (np = %d) for p=(%d,%d,%d)pi/2L\n",sgn,np,p[0],p[1],p[2]); fflush(stdout); } return sgn; } inline void siteFmat(FlavorMatrixGeneral<ComplexType> &out, const int site) const{ //Matrix is FFT of (1 + [sign]*sigma_2) when |x-y| !=0 or 1 when |x-y| == 0 //It is always 1 on the diagonals const ComplexType &val = this->siteComplex(site); out(0,0) = out(1,1) = val; //and has \pm i on the diagonals with a momentum structure that is computed by omitting site 0,0,0 out(1,0) = multiplySignTimesI(sign,val - *val000); out(0,1) = -out(1,0); //-1 from sigma2 } //Can change momentum sign without redoing FFT void setMomentum(const int p[3]){ sign = getProjSign(p); } }; template<typename FieldPolicies = StandardSourcePolicies> class A2AflavorProjectedExpSource : public A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >{ void dummy(){} public: typedef typename A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >::FieldParamType FieldParamType; typedef typename A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >::ComplexType ComplexType; A2AflavorProjectedExpSource(const Float radius, const int p[3], const FieldParamType &src_field_params = NullObject()){ this->A2AexpSource<FieldPolicies>::setup(radius,src_field_params); this->A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >::setup_projected_src_info(p); } A2AflavorProjectedExpSource(): A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >(){} A2AflavorProjectedExpSource(const A2AflavorProjectedExpSource &r): A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >(r){} void setup(const Float radius, const int p[3], const FieldParamType &src_field_params = NullObject()){ this->A2AexpSource<FieldPolicies>::setup(radius,src_field_params); this->A2AflavorProjectedSource<A2AexpSource<FieldPolicies> >::setup_projected_src_info(p); } }; template<typename FieldPolicies = StandardSourcePolicies> class A2AflavorProjectedHydrogenSource : public A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >{ void dummy(){} public: typedef typename A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >::FieldParamType FieldParamType; typedef typename A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >::ComplexType ComplexType; A2AflavorProjectedHydrogenSource(const int _n, const int _l, const int _m, const Float _radius, const int p[3], const FieldParamType &src_field_params = NullObject()){ this->A2AhydrogenSource<FieldPolicies>::setup(_n,_l,_m,_radius,src_field_params); this->A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >::setup_projected_src_info(p); } A2AflavorProjectedHydrogenSource(): A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >(){} A2AflavorProjectedHydrogenSource(const A2AflavorProjectedHydrogenSource &r): A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >(r){} void setup(const int _n, const int _l, const int _m, const Float _radius, const int p[3], const FieldParamType &src_field_params = NullObject()){ this->A2AhydrogenSource<FieldPolicies>::setup(_n,_l,_m,_radius,src_field_params); this->A2AflavorProjectedSource<A2AhydrogenSource<FieldPolicies> >::setup_projected_src_info(p); } }; define_test_has_enum(nSources); //a test for multisrc types (all should have enum nSources) template<typename SourceList> class A2AmultiSource{ public: typedef ListStruct<SourceList> SourceListStruct; private: SourceListStruct sources; public: enum { nSources = getSizeOfListStruct<SourceListStruct>::value }; //Accessors for sources (call like src.template get<Idx>() ) template<int i> typename getTypeFromList<SourceListStruct,i>::type & getSource(){ return getElemFromListStruct<SourceListStruct,i>::get(sources); } template<int i> const typename getTypeFromList<SourceListStruct,i>::type & getSource() const{ return getConstElemFromListStruct<SourceListStruct,i>::get(sources); } }; CPS_END_NAMESPACE #endif
GB_binop__iseq_fc32.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__iseq_fc32) // A.*B function (eWiseMult): GB (_AemultB_01__iseq_fc32) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_fc32) // A.*B function (eWiseMult): GB (_AemultB_03__iseq_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_fc32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_fc32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_fc32) // C=scalar+B GB (_bind1st__iseq_fc32) // C=scalar+B' GB (_bind1st_tran__iseq_fc32) // C=A+scalar GB (_bind2nd__iseq_fc32) // C=A'+scalar GB (_bind2nd_tran__iseq_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_iseq (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ GxB_FC32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ GxB_FC32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_FC32_iseq (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_ISEQ || GxB_NO_FC32 || GxB_NO_ISEQ_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__iseq_fc32) ( 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__iseq_fc32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__iseq_fc32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__iseq_fc32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__iseq_fc32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__iseq_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__iseq_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__iseq_fc32) ( 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__iseq_fc32) ( 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 GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_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 ; GxB_FC32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_FC32_iseq (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__iseq_fc32) ( 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 ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_FC32_iseq (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_iseq (x, aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_fc32) ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_iseq (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_fc32) ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
profile.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/linked-list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/option-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType,ExceptionInfo *); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* Typedef declarations */ struct _ProfileInfo { char *name; size_t length; unsigned char *info; size_t signature; }; typedef struct _CMSExceptionInfo { Image *image; ExceptionInfo *exception; } CMSExceptionInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) static unsigned short **DestroyPixelThreadSet(unsigned short **pixels) { register ssize_t i; assert(pixels != (unsigned short **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (unsigned short *) NULL) pixels[i]=(unsigned short *) RelinquishMagickMemory(pixels[i]); pixels=(unsigned short **) RelinquishMagickMemory(pixels); return(pixels); } static unsigned short **AcquirePixelThreadSet(const size_t columns, const size_t channels) { register ssize_t i; unsigned short **pixels; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(unsigned short **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (unsigned short **) NULL) return((unsigned short **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(unsigned short *) AcquireQuantumMemory(columns,channels* sizeof(**pixels)); if (pixels[i] == (unsigned short *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { register ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(Image *image, const cmsHPROFILE source_profile,const cmsUInt32Number source_type, const cmsHPROFILE target_profile,const cmsUInt32Number target_type, const int intent,const cmsUInt32Number flags) { cmsHTRANSFORM *transform; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) ResetMagickMemory(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR((cmsContext) image,source_profile, source_type,target_profile,target_type,intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } #endif #if defined(MAGICKCORE_LCMS_DELEGATE) static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { CMSExceptionInfo *cms_exception; ExceptionInfo *exception; Image *image; cms_exception=(CMSExceptionInfo *) context; if (cms_exception == (CMSExceptionInfo *) NULL) return; exception=cms_exception->exception; if (exception == (ExceptionInfo *) NULL) return; image=cms_exception->image; if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s'","unknown context"); return; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s'",image->filename); } #endif static MagickBooleanType SetsRGBImageProfile(Image *image, ExceptionInfo *exception) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length,ExceptionInfo *exception) { #define ProfileImageTag "Profile/Image" #define ThrowProfileException(severity,tag,context) \ { \ if (source_profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_profile); \ if (target_profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile,exception); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace",exception); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image,exception); value=GetImageProperty(image,"exif:InteroperabilityIndex",exception); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image,exception); /* Future. value=GetImageProperty(image,"exif:InteroperabilityIndex",exception); if (LocaleCompare(value,"R03.") != 0) (void) SetAdobeRGB1998ImageProfile(image,exception); */ icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (LCMS)",image->filename); #else { cmsHPROFILE source_profile; CMSExceptionInfo cms_exception; /* Transform pixel colors as defined by the color profiles. */ cmsSetLogErrorHandler(CMSExceptionHandler); cms_exception.image=image; cms_exception.exception=exception; (void) cms_exception; source_profile=cmsOpenProfileFromMemTHR((cmsContext) &cms_exception, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_profile == (cmsHPROFILE) NULL) ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile,exception); else { CacheView *image_view; ColorspaceType source_colorspace, target_colorspace; cmsColorSpaceSignature signature; cmsHPROFILE target_profile; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags, source_type, target_type; int intent; MagickOffsetType progress; size_t source_channels, target_channels; ssize_t y; unsigned short **magick_restrict source_pixels, **magick_restrict target_pixels; target_profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_profile=source_profile; source_profile=cmsOpenProfileFromMemTHR((cmsContext) &cms_exception,GetStringInfoDatum(icc_profile), (cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } switch (cmsGetColorSpace(source_profile)) { case cmsSigCmykData: { source_colorspace=CMYKColorspace; source_type=(cmsUInt32Number) TYPE_CMYK_16; source_channels=4; break; } case cmsSigGrayData: { source_colorspace=GRAYColorspace; source_type=(cmsUInt32Number) TYPE_GRAY_16; source_channels=1; break; } case cmsSigLabData: { source_colorspace=LabColorspace; source_type=(cmsUInt32Number) TYPE_Lab_16; source_channels=3; break; } case cmsSigLuvData: { source_colorspace=YUVColorspace; source_type=(cmsUInt32Number) TYPE_YUV_16; source_channels=3; break; } case cmsSigRgbData: { source_colorspace=sRGBColorspace; source_type=(cmsUInt32Number) TYPE_RGB_16; source_channels=3; break; } case cmsSigXYZData: { source_colorspace=XYZColorspace; source_type=(cmsUInt32Number) TYPE_XYZ_16; source_channels=3; break; } case cmsSigYCbCrData: { source_colorspace=YCbCrColorspace; source_type=(cmsUInt32Number) TYPE_YCbCr_16; source_channels=3; break; } default: { source_colorspace=UndefinedColorspace; source_type=(cmsUInt32Number) TYPE_RGB_16; source_channels=3; break; } } signature=cmsGetPCS(source_profile); if (target_profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_profile); switch (signature) { case cmsSigCmykData: { target_colorspace=CMYKColorspace; target_type=(cmsUInt32Number) TYPE_CMYK_16; target_channels=4; break; } case cmsSigLabData: { target_colorspace=LabColorspace; target_type=(cmsUInt32Number) TYPE_Lab_16; target_channels=3; break; } case cmsSigGrayData: { target_colorspace=GRAYColorspace; target_type=(cmsUInt32Number) TYPE_GRAY_16; target_channels=1; break; } case cmsSigLuvData: { target_colorspace=YUVColorspace; target_type=(cmsUInt32Number) TYPE_YUV_16; target_channels=3; break; } case cmsSigRgbData: { target_colorspace=sRGBColorspace; target_type=(cmsUInt32Number) TYPE_RGB_16; target_channels=3; break; } case cmsSigXYZData: { target_colorspace=XYZColorspace; target_type=(cmsUInt32Number) TYPE_XYZ_16; target_channels=3; break; } case cmsSigYCbCrData: { target_colorspace=YCbCrColorspace; target_type=(cmsUInt32Number) TYPE_YCbCr_16; target_channels=3; break; } default: { target_colorspace=UndefinedColorspace; target_type=(cmsUInt32Number) TYPE_RGB_16; target_channels=3; break; } } if ((source_colorspace == UndefinedColorspace) || (target_colorspace == UndefinedColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == GRAYColorspace) && (SetImageGray(image,exception) == MagickFalse)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == CMYKColorspace) && (image->colorspace != CMYKColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == XYZColorspace) && (image->colorspace != XYZColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == YCbCrColorspace) && (image->colorspace != YCbCrColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace != CMYKColorspace) && (source_colorspace != LabColorspace) && (source_colorspace != XYZColorspace) && (source_colorspace != YCbCrColorspace) && (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); switch (image->rendering_intent) { case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break; case PerceptualIntent: intent=INTENT_PERCEPTUAL; break; case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break; case SaturationIntent: intent=INTENT_SATURATION; break; default: intent=INTENT_PERCEPTUAL; break; } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(image,source_profile, source_type,target_profile,target_type,intent,flags); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_pixels=AcquirePixelThreadSet(image->columns,source_channels); target_pixels=AcquirePixelThreadSet(image->columns,target_channels); if ((source_pixels == (unsigned short **) NULL) || (target_pixels == (unsigned short **) NULL)) { transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { target_pixels=DestroyPixelThreadSet(target_pixels); source_pixels=DestroyPixelThreadSet(source_pixels); transform=DestroyTransformThreadSet(transform); if (source_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_profile); if (target_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_profile); return(MagickFalse); } if (target_colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_colorspace,exception); progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; register unsigned short *p; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } p=source_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=ScaleQuantumToShort(GetPixelRed(image,q)); if (source_channels > 1) { *p++=ScaleQuantumToShort(GetPixelGreen(image,q)); *p++=ScaleQuantumToShort(GetPixelBlue(image,q)); } if (source_channels > 3) *p++=ScaleQuantumToShort(GetPixelBlack(image,q)); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_pixels[id],target_pixels[id], (unsigned int) image->columns); p=target_pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_channels == 1) SetPixelGray(image,ScaleShortToQuantum(*p),q); else SetPixelRed(image,ScaleShortToQuantum(*p),q); p++; if (target_channels > 1) { SetPixelGreen(image,ScaleShortToQuantum(*p),q); p++; SetPixelBlue(image,ScaleShortToQuantum(*p),q); p++; } if (target_channels > 3) { SetPixelBlack(image,ScaleShortToQuantum(*p),q); p++; } q+=GetPixelChannels(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 critical (MagickCore_ProfileImage) #endif proceed=SetImageProgress(image,ProfileImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_colorspace,exception); switch (signature) { case cmsSigRgbData: { image->type=image->alpha_trait == UndefinedPixelTrait ? TrueColorType : TrueColorAlphaType; break; } case cmsSigCmykData: { image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; break; } case cmsSigGrayData: { image->type=image->alpha_trait == UndefinedPixelTrait ? GrayscaleType : GrayscaleAlphaType; break; } default: break; } target_pixels=DestroyPixelThreadSet(target_pixels); source_pixels=DestroyPixelThreadSet(source_pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) && (cmsGetDeviceClass(source_profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile,exception); if (target_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_profile); } (void) cmsCloseProfile(source_profile); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) CopyMagickMemory(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset-4); WriteResourceLong(extract_profile->datum+offset-4,(unsigned int) profile->length); (void) CopyMagickMemory(extract_profile->datum+offset, profile->datum,profile->length); } (void) CopyMagickMemory(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block,ExceptionInfo *exception) { const unsigned char *datum; register const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ p=ReadResourceLong(p,&resolution); image->resolution.x=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->resolution.y=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive, ExceptionInfo *exception) { char key[MagickPathExtent], property[MagickPathExtent]; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MagickPathExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),CloneStringInfo(profile)); if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,profile,exception); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,profile); } /* Inject profile into image properties. */ (void) FormatLocaleString(property,MagickPathExtent,"%s:*",name); (void) GetImageProperty(image,property,exception); return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { return(SetImageProfileInternal(image,name,profile,MagickFalse,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) CopyMagickMemory(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) CopyMagickMemory(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) CopyMagickMemory(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) CopyMagickMemory(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*2.54* 65536.0),p); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(int) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((offset < 0) || ((size_t) (offset+number_bytes) > length)) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickPrivate MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); }
DRB018-plusplus-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Data race on outLen due to ++ operation. Adding private (outLen) can avoid race condition. But it is wrong semantically. Data races on outLen also cause output[outLen++] to have data races. Data race pairs (we allow two pairs to preserve the original code pattern): 1. outLen@72 vs. outLen@72 2. output[]@72 vs. output[]@72 */ #include <stdlib.h> #include <stdio.h> int input[1000]; int output[1000]; int main() { int i ; int inLen=1000 ; int outLen = 0; #pragma omp parallel for private(i ) for (i=0; i<inLen; ++i) input[i]= i; for (i=0; i<inLen; ++i) { output[outLen++] = input[i]; } printf("output[500]=%d\n",output[500]); return 0; }
GB_binop__first_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__first_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__first_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__first_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__first_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__first_uint16) // A*D function (colscale): GB (_AxD__first_uint16) // D*A function (rowscale): GB (_DxB__first_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__first_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__first_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__first_uint16) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint16_t // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 1 // BinaryOp: cij = aij #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint16_t aij = GBX (Ax, pA, A_iso) // 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) \ ; // true if values of B are not used #define GB_B_IS_PATTERN \ 1 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = x ; // 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_FIRST || GxB_NO_UINT16 || GxB_NO_FIRST_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__first_uint16) ( 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__first_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #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__first_uint16) ( 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 uint16_t uint16_t bwork = (*((uint16_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__first_uint16) ( 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 uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__first_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__first_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_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__first_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__first_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__first_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__first_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = aij ; } 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] = x ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } #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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
Ligo_abc_gsl.c
// mimetic_bayes program // Alessandro Casalino, University of Trento // For licence informations, see the Github repository license // // Compile with: gcc-8 -O2 -DHAVE_INLINE -DGSL_RANGE_CHECK_OFF Ligo_abc_gsl.c -o Ligo_abc_gsl.o -lgsl -lgslcblas -fopenmp // Run with: ./Ligo_abc_gsl.o // Test running time: time ./Ligo_abc_gsl.o #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <sys/time.h> #include <omp.h> // PROGRAM VARIABLES // Variables for parallelization with OpenMP // Info on OpenMP: https://bisqwit.iki.fi/story/howto/openmp/#Syntax // Enable OpenMP int OPENMP = 1; // Number of threads used by OpenMP (can't be bigger than the number of threads available on your computer) // If 0, the number of threads available on the computer is used int OMP_THREAD_NUM = 0; // Number of Chains (for higher efficiency, consider N_CHAIN as a multiple of OMP_THREAD_NUM) int N_CHAINS = 8; // Make the Lag test (can make the computation very long!) int LAG_TEST = 0; // Ratio of lag function computed with respect to the total number of points in every chain // Smaller values make the computation faster double LAG_TEST_STOP_RATIO = 0.001; // Write (in the terminal) debug informations and informations that might be considered in order to improve results int DEBUG = 1; // Write .csv files #define CSV 1 // Write covariant matrix in .csv file int CSV_COV = 1; // Write correlation matrix (Pearson coefficients) in .csv file int CSV_CORR = 1; // NUMERICAL VARIABLES // Chain evaluation dimension (every step found from proposal distribution is multiplied by this quantity) // This is also used to define the covariance matrix for the Gaussian proposal double SPEED[] = {1e-1,5e-16,4e-16}; // Mean value for Gaussian proposal (PROPOSAL=1) double MEAN_P1[] = {0.,0.,0.}; // Number of points in every chain int N = 1e6; // PHYSICAL VARIABLES // Choose to use the constraint on Ct2 in the prior int CT2_CONSTR = 1; // Choose the proposal distribution int PROPOSAL = 1; // Note that the constraints are defined in rho(pos) // PROGRAM typedef struct chain { gsl_vector * mean; gsl_matrix * covariance; double acceptance_ratio; } chain_res; inline double cT2 (gsl_vector * pos) { double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2); return (2.0-2.0*a)/(2.0-2.0*a+b); } inline double cS2 (gsl_vector * pos) { double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2); return (b-c)*(2.0*a-2.0)/(2.0*a-b-2.0)/(4.0-4.0*a-b+3.0*c); } inline double MPl2 (gsl_vector * pos) { double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2); return 4.0-4.0*a-b+3.0*c; } inline double rho(gsl_vector * pos){ double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2); // Value of the sound speed squared double cs2=cS2(pos); // Value of the tensor speed squared double ct2=cT2(pos); // Value of the Planck mass rescaling factor double Mpl2=MPl2(pos); // Value of the argument of the Gaussian in the Likelihood double delta=fabs(sqrt(ct2)-1.0); // This is the experimental sigma on cT2 double sigma = 4.5e-16; double result = 0.; // With these ifs I'm introducing the constraints on cT2, cS2 and on the parameters a and c // To eliminate these constraints, put CT2_CONSTR=0 at the beginning of the file // // OLD constraint: CT2_CONSTR==1 && a>=-1. && a<=1. && b>=0. && b<=1. && ct2>=0.0 && ct2<= 1.0 && cs2>=0.0 && cs2<=1.0 // // NEW (correct) constraint: CT2_CONSTR==1 && a>=-1. && a<=1. && Mpl2>=0. && c<=1. && c>=0 && ct2>=0.0 && ct2<= 1.0 && cs2<=0.0 // if (CT2_CONSTR==1 && a>=-1. && a<=1. && c>=0. && c<=1. && ct2>=0. && ct2<=1. && cs2>=0. && cs2<=1.){ result=exp(-0.5 * pow(delta/sigma,2.0) ); } else if(CT2_CONSTR==1){ result=exp(-1e90); } else{ result=exp(-0.5 * pow(delta/sigma,2.0) ); } return result; } chain_res chain_analysis(double (* chain)[3]){ chain_res result; gsl_vector * mean = gsl_vector_alloc(3); int i,k,s; for(k=0;k<3;k++){ double mean_temp = 0.; for(i=0;i<N;i++){ mean_temp = mean_temp + chain[i][k]; } gsl_vector_set(mean, k, mean_temp); } gsl_vector_scale(mean,1./N); gsl_matrix * cm = gsl_matrix_alloc(3,3); for(k=0;k<3;k++){ double mean_row = gsl_vector_get(mean,k); for(s=0;s<3;s++){ double mean_column = gsl_vector_get(mean,s); double cm_temp = 0.; for(i=0;i<N;i++){ cm_temp = cm_temp + (chain[i][k]-mean_row)*(chain[i][s]-mean_column); } gsl_matrix_set(cm, k, s, cm_temp); } } gsl_matrix_scale(cm,1./(N-1.)); result.mean = gsl_vector_alloc(3); gsl_vector_memcpy(result.mean,mean); result.covariance = gsl_matrix_alloc(3,3); gsl_matrix_memcpy(result.covariance,cm); gsl_matrix_free(cm); gsl_vector_free(mean); return result; } inline double Gaussian_proposal(double mean, double sigma, double u1, double u2) { // Box Muller transform from flat distribution to Guassian distribution return mean + sigma * sqrt(-2.*log(u1)) * cos(2.*M_PI*u2); } void C_Delta(double (* chain)[3], chain_res results, double f_stop, int chain_number){ int id_thread = omp_get_thread_num(); double mean_X = gsl_vector_get(results.mean,0); double mean_Y = gsl_vector_get(results.mean,1); double mean_Z = gsl_vector_get(results.mean,2); double cm_XX = gsl_matrix_get(results.covariance,0,0); double cm_YY = gsl_matrix_get(results.covariance,1,1); double cm_ZZ = gsl_matrix_get(results.covariance,2,2); int stop = N*f_stop; double * C_Delta_X; double * C_Delta_Y; double * C_Delta_Z; C_Delta_X = (double *) malloc(sizeof(double) * stop); C_Delta_Y = (double *) malloc(sizeof(double) * stop); C_Delta_Z = (double *) malloc(sizeof(double) * stop); int i,j; for(i=0;i<stop;i++){ for(j=0;j<N-i;j++){ C_Delta_X[i]=C_Delta_X[i]+(chain[j][0]-mean_X)*(chain[j+i][0]-mean_X); C_Delta_Y[i]=C_Delta_Y[i]+(chain[j][1]-mean_Y)*(chain[j+i][1]-mean_Y); C_Delta_Z[i]=C_Delta_Z[i]+(chain[j][2]-mean_Z)*(chain[j+i][2]-mean_Z); } C_Delta_X[i]=C_Delta_X[i]/(N-i)/cm_XX; C_Delta_Y[i]=C_Delta_Y[i]/(N-i)/cm_YY; C_Delta_Z[i]=C_Delta_Z[i]/(N-i)/cm_ZZ; } FILE *fp; char filename[25]; sprintf(filename,"Ligo_abc_DeltaC_t%d.csv",chain_number); fp = fopen (filename, "w+"); for(i=0;i<stop;i++){ fprintf(fp, "%d,%.8e,%.8e,%.8e\n", i, C_Delta_X[i], C_Delta_Y[i], C_Delta_Z[i]); } fclose(fp); free(C_Delta_X); free(C_Delta_Y); free(C_Delta_Z); } chain_res LHSampling(int proposal, int chain_number){ int k; int id_thread=omp_get_thread_num(); const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); unsigned long seed = time(NULL) + chain_number; gsl_rng_set(r, seed); gsl_vector * pos_ini = gsl_vector_alloc(3); for(k=0;k<3;k++){ if(k==0){ double random_number = 2. * gsl_rng_uniform (r) - 1.; gsl_vector_set(pos_ini,k,SPEED[k]*random_number); } else if (k==1){ double random_number = gsl_rng_uniform (r); gsl_vector_set(pos_ini,k,SPEED[k]*random_number); } else { double random_number = gsl_rng_uniform (r); gsl_vector_set(pos_ini,k,SPEED[k]*random_number); } } // Here definitions only for the Gaussian proposal distribution gsl_vector * pos_mean_p1 = gsl_vector_alloc(3); for(k=0;k<3;k++){ gsl_vector_set(pos_mean_p1, k, MEAN_P1[k]); } gsl_matrix * S = gsl_matrix_calloc(3,3); gsl_matrix * L = gsl_matrix_alloc(3,3); gsl_vector * pos_temp2 = gsl_vector_alloc(3); gsl_matrix_set(S,0,0,pow(SPEED[0],2.)); gsl_matrix_set(S,1,1,pow(SPEED[1],2.)); gsl_matrix_set(S,2,2,pow(SPEED[2],2.)); gsl_matrix_memcpy(L,S); gsl_linalg_cholesky_decomp1(L); // End of Gaussian proposal definitions gsl_vector * pos = gsl_vector_alloc(3); gsl_vector_memcpy(pos,pos_ini); #if CSV==1 FILE *fp; char filename[25]; sprintf(filename,"Ligo_abc_%d.txt",chain_number); fp = fopen (filename, "w+"); #endif double (* chain)[3] = malloc(sizeof(* chain) * N); int i = 0; int j = 0; int rc = 1; while (i<N) { double f0 = rho(pos); gsl_vector * pos_temp = gsl_vector_calloc(3); // NOTE: Introducing the proposal distributions here if(proposal==0){ for(k=0;k<3;k++){ double random_number = 2. * gsl_rng_uniform (r) - 1.; gsl_vector_set(pos_temp, k, SPEED[k]*random_number); } gsl_vector_add(pos_temp,pos); } else if(proposal=!0){ for(k=0;k<3;k++){ gsl_vector_set(pos_temp2, k, Gaussian_proposal(0., 1., gsl_rng_uniform (r), gsl_rng_uniform (r))); } gsl_blas_dgemv (CblasNoTrans, 1., L, pos_temp2, 0., pos_temp); gsl_vector_add(pos_temp,pos_mean_p1); gsl_vector_add(pos_temp,pos); } double f1 = rho(pos_temp); // NOTE: here we also print data in .csv file (if CSV==1) in Getdist ready format // Getdist output with (no commas): repetitions count log(rho) {parameters} {(optional) other outputs - not considered by Getdist} if (f1>f0) { gsl_vector_memcpy(pos,pos_temp); j++; #if CSV==1 fprintf(fp, "%d %.8e %.8e %.8e %.8e\n", rc, -log(rho(pos)), gsl_vector_get(pos,0), gsl_vector_get(pos,1), gsl_vector_get(pos,2)); #endif rc = 1; } else { double ra = gsl_rng_uniform (r); if (ra<f1/f0) { gsl_vector_memcpy(pos,pos_temp); j++; #if CSV==1 fprintf(fp, "%d %.8e %.8e %.8e %.8e\n", rc, -log(rho(pos)), gsl_vector_get(pos,0), gsl_vector_get(pos,1), gsl_vector_get(pos,2)); #endif rc = 1; } else{ rc++; } } for(k=0;k<3;k++){ chain[i][k]=gsl_vector_get(pos,k); } gsl_vector_free(pos_temp); i++; } chain_res result; result = chain_analysis(chain); result.acceptance_ratio = (double) j/i; if(DEBUG==1 && result.acceptance_ratio<0.05) printf("\n WARNING (chain %d): Acceptance ratio at %e. The chain seems stuck at initial point. \n", chain_number, result.acceptance_ratio); if(DEBUG==1 && result.acceptance_ratio>0.8) printf("\n WARNING (chain %d): Acceptance ratio at %e. The chain seems evolving too slowly. \n", chain_number, result.acceptance_ratio); // Check of correlation (with lag) if(LAG_TEST==1){ printf(" Computing Lag function..\n"); if(DEBUG==1) printf(" Note: This computation can take a lot of computational time.\n"); if(DEBUG==1) printf(" Lower LAG_TEST_STOP_RATIO for faster results.\n"); C_Delta(chain,result,LAG_TEST_STOP_RATIO, chain_number); } #if CSV==1 if(CSV_COV==1){ FILE *fp2; sprintf(filename,"Ligo_abc_%d.covmat",chain_number); fp2 = fopen (filename, "w+"); fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,0,0),gsl_matrix_get(result.covariance,0,1),gsl_matrix_get(result.covariance,0,2)); fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,1,0),gsl_matrix_get(result.covariance,1,1),gsl_matrix_get(result.covariance,1,2)); fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,2,0),gsl_matrix_get(result.covariance,2,1),gsl_matrix_get(result.covariance,2,2)); fclose(fp2); } #endif #if CSV==1 if(CSV_CORR==1){ FILE *fp3; sprintf(filename,"Ligo_abc_%d.corr",chain_number); fp3 = fopen (filename, "w+"); fprintf(fp3, "%.8e %.8e %.8e\n", 1.,gsl_matrix_get(result.covariance,0,1)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,1,1))),gsl_matrix_get(result.covariance,0,2)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2)))); fprintf(fp3, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,1,0)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,1,1))),1.,gsl_matrix_get(result.covariance,1,2)/sqrt(fabs(gsl_matrix_get(result.covariance,1,1)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2)))); fprintf(fp3, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,2,0)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))),gsl_matrix_get(result.covariance,2,1)/sqrt(fabs(gsl_matrix_get(result.covariance,1,1)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))),1.); fclose(fp3); } #endif // Free all the variables free(chain); gsl_vector_free(pos_ini); gsl_vector_free(pos_mean_p1); gsl_vector_free(pos); gsl_rng_free(r); gsl_vector_free(pos_temp2); gsl_matrix_free(S); gsl_matrix_free(L); #if CSV==1 fclose(fp); #endif return result; } inline double R(double sigma2_chain, double sigma2_mean){ int noc = N_CHAINS; return sqrt(((N-1.)/N*sigma2_chain + (noc+1.)/N/noc*sigma2_mean)/sigma2_chain); } gsl_vector * GR_Test(chain_res * chain_results) { int i, k; int noc = N_CHAINS; gsl_vector * mean = gsl_vector_alloc(3); gsl_vector * sigma2_chain = gsl_vector_alloc(3); gsl_vector * sigma2_mean = gsl_vector_alloc(3); for(k=0;k<3;k++){ double mean_temp = 0.; double sigma2_temp = 0.; for(i=0;i<noc;i++){ mean_temp = mean_temp + gsl_vector_get(chain_results[i].mean,k)/noc; sigma2_temp = sigma2_temp + fabs(gsl_matrix_get(chain_results[i].covariance,k,k))/noc; } gsl_vector_set(mean, k, mean_temp); gsl_vector_set(sigma2_chain, k, sigma2_temp); } for(k=0;k<3;k++){ double mean_temp = 0.; double sigma2_temp = 0.; for(i=0;i<noc;i++){ sigma2_temp = sigma2_temp + pow(gsl_vector_get(mean,k)-gsl_vector_get(chain_results[i].mean,k),2.)*N/(noc-1.); } gsl_vector_set(sigma2_mean, k, sigma2_temp); } double R_a = R(gsl_vector_get(sigma2_chain,0), gsl_vector_get(sigma2_mean,0)); double R_b = R(gsl_vector_get(sigma2_chain,1), gsl_vector_get(sigma2_mean,1)); double R_c = R(gsl_vector_get(sigma2_chain,2), gsl_vector_get(sigma2_mean,2)); printf("\n Gelman-Rubin test.\n"); printf(" \t- R_a : %f\n", R_a); printf(" \t- R_b : %f\n", R_b); printf(" \t- R_c : %f\n", R_c); if(DEBUG==1) printf(" Converge if (approximately) R < 1.2. For better results R < 1.01.\n"); printf("\n ------------------------------------------------------------------------ \n"); gsl_vector_free(mean); gsl_vector_free(sigma2_chain); gsl_vector_free(sigma2_mean); gsl_vector * result = gsl_vector_alloc(3); gsl_vector_set(result,0,R_a);gsl_vector_set(result,1,R_b);gsl_vector_set(result,2,R_c); return result; } void init_msg(int proposal){ printf(" Starting the MCMC computation with Metropolis-Hastings algorithm.\n"); printf(" Properties of the chains:\n"); if(proposal==0){ printf(" \t- Proposal distribution: flat.\n"); } if(proposal!=0){ printf(" \t- Proposal distribution: Gaussian.\n"); } if(OPENMP==0){ printf(" \t- The chain will be %d points long.\n", N); } if(OPENMP==1){ printf(" \t- Each of the %d chains will be %d points long.\n", N_CHAINS, N); } printf(" ------------------------------------------------------------------------ \n"); } int main(){ int proposal=PROPOSAL; printf(" ------------------------------------------------------------------------ \n"); printf("\t mimetic_bayes program "); if(DEBUG==1) printf("(with DEBUG mode on)"); printf("\n"); printf(" ------------------------------------------------------------------------ \n"); if(OPENMP==1){ int i; chain_res * chain_results; chain_results = (chain_res *) malloc(sizeof(chain_res) * N_CHAINS); if(OMP_THREAD_NUM==0) OMP_THREAD_NUM = omp_get_max_threads(); if(DEBUG==1) { printf(" Info on OpenMP on this computer. \n"); printf(" \t- Number of processors available = %d\n", omp_get_num_procs ( ) ); printf(" \t- Number of threads = %d\n", omp_get_max_threads ( ) ); printf(" \t- Number of working threads = %d\n", OMP_THREAD_NUM ); printf(" Specify the number of working threads in .c file.\n"); printf(" ------------------------------------------------------------------------ \n"); } printf(" Number of chains requested = %d. \n", N_CHAINS); printf(" ------------------------------------------------------------------------ \n"); if(OMP_THREAD_NUM>omp_get_max_threads()){ printf(" Fatal Error. Can't set number of threads (OMP_THREAD_NUM = %d) bigger than the available number of threads (%d). \n",OMP_THREAD_NUM, omp_get_max_threads()); printf(" \t Change OMP_THREAD_NUM and try again. \n"); printf(" The program will be terminated. \n"); exit(0); } omp_set_num_threads(OMP_THREAD_NUM); init_msg(proposal); printf("\n Doing parallelized workflow. Please wait. \n\n"); if(DEBUG==1) printf(" NOTE: Some WARNING might be shown. \n"); if(DEBUG==1) printf(" Consider to stop the program and check the parameters if WARNINGs appear. \n\n"); #pragma omp parallel for for(i=1;i<=N_CHAINS;i++) { int current_thread = omp_get_thread_num(); if(DEBUG==1) printf(" Thread %d working on chain %d .\n", current_thread, i); chain_results[i-1]=LHSampling(proposal, i); if(DEBUG==1) printf(" Thread %d finished working on chain %d. \n", current_thread, i); } printf(" ------------------------------------------------------------------------ \n"); for(i=0;i<N_CHAINS;i++){ printf(" CHAIN %d RESULTS. \n", i+1); printf("\n Acceptance ratio: %f \n\n", chain_results[i].acceptance_ratio); printf(" Results: Mean value pm sqrt(covariant_ii).\n"); printf(" \ta: %e pm %e\n", gsl_vector_get(chain_results[i].mean,0), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0)))); printf(" \tb: %e pm %e\n", gsl_vector_get(chain_results[i].mean,1), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1)))); printf(" \tc: %e pm %e\n", gsl_vector_get(chain_results[i].mean,2), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2)))); printf("\n Results: Correlation coefficients.\n"); printf(" \tab: %e \n", gsl_matrix_get(chain_results[i].covariance,0,1)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1)))); printf(" \tac: %e \n", gsl_matrix_get(chain_results[i].covariance,0,2)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2)))); printf(" \tbc: %e \n", gsl_matrix_get(chain_results[i].covariance,1,2)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2)))); printf(" These are the Pearson coefficients : covariant_ij / sigma_i sigma_j\n\n"); printf(" ------------------------------------------------------------------------ \n"); } gsl_vector * GR_test_result = gsl_vector_alloc(3); GR_test_result = GR_Test(chain_results); double R_a = gsl_vector_get(GR_test_result,0); double R_b = gsl_vector_get(GR_test_result,1); double R_c = gsl_vector_get(GR_test_result,2); if(DEBUG==1){ int k = 0; double C00 = sqrt(gsl_matrix_get(chain_results[0].covariance,0,0)); double C11 = sqrt(gsl_matrix_get(chain_results[0].covariance,1,1)); double C22 = sqrt(gsl_matrix_get(chain_results[0].covariance,2,2)); printf("\n INFORMATIONS for better convergence. \n\n"); printf(" WARNING: These are hints based on the results and thumb rules. \n"); printf(" Follow these hints at your own risk. \n\n"); if(R_a>1.2||R_b>1.2||R_c>1.2) { printf(" - An R_i>1.2 : Chains are sampling different parameter spaces.\n"); printf(" There might be some troubles in your SPEED vector definition.\n"); k++; } if((R_a<1.2&&R_a>1.01)||(R_b<1.2&&R_b>1.01)||(R_c<1.2&&R_c>1.01)) { printf(" - An R_i>1.01 : The results might be good, but the results can be improved.\n"); printf(" Try different values for the SPEED vector to achieve better results.\n"); k++; } double p_value = 0.5; if(fabs(SPEED[0]-C00/4.)/fabs(SPEED[0]+C00/4.)>p_value){ printf(" - From covariance matrix: Try with a SPEED[0] = %e .\n",C00/4.); k++; } if(fabs(SPEED[1]-C11/4.)/fabs(SPEED[1]+C11/4.)>p_value){ printf(" - From covariance matrix: Try with a SPEED[1] = %e .\n",C11/4.); k++; } if(fabs(SPEED[2]-C22/4.)/fabs(SPEED[2]+C22/4.)>p_value){ printf(" - From covariance matrix: Try with a SPEED[2] = %e .\n",C22/4.); k++; } int j=0, r=0; for(i=0;i<N_CHAINS;i++){ if(chain_results[i].acceptance_ratio>0.5) j++; if(chain_results[i].acceptance_ratio<0.1) r++; } if(j>0){ printf(" - From acceptance rations: Maybe some acceptance ratios are too big.\n"); printf(" The configuration space might be explored slowly.\n"); printf(" This is not necessarily a problem,\n"); printf(" but if the results are not good:\n"); printf(" try with different SPEED vector values.\n"); k++; } if(r>0){ printf(" - From acceptance rations: Maybe some acceptance ratios are too small.\n"); printf(" The configuration space might be explored very inefficiently.\n"); printf(" This is not necessarily a problem,\n"); printf(" but if the results are not good:\n"); printf(" try with different SPEED vector values.\n"); k++; } double mean_a = gsl_vector_get(chain_results[0].mean,0); double sigma_a = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,0,0))); if(PROPOSAL==1 && (fabs(mean_a-MEAN_P1[0])/fabs(mean_a+MEAN_P1[0])>3.*sigma_a)) { printf(" - A burn-in removal might be needed: Try with MEAN_P1[0] = %e.\n",mean_a); printf(" Note that this can improve but also worsen the results.\n"); printf(" Revert the result and make a burn-in removal instead if the results get worse.\n"); } double mean_b = gsl_vector_get(chain_results[0].mean,1); double sigma_b = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,1,1))); if(PROPOSAL==1 && (fabs(mean_b-MEAN_P1[1])/fabs(mean_b+MEAN_P1[1])>3.*sigma_b)) { printf(" - A burn-in removal might be needed: Try with MEAN_P1[1] = %e.\n",mean_b); printf(" Note that this can improve but also worsen the results.\n"); printf(" Revert the result and make a burn-in removal instead if the results get worse.\n"); } double mean_c = gsl_vector_get(chain_results[0].mean,2); double sigma_c = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,2,2))); if(PROPOSAL==1 && (fabs(mean_a-MEAN_P1[2])/fabs(mean_a+MEAN_P1[2])>3.*sigma_c)) { printf(" - A burn-in removal might be needed: Try with MEAN_P1[2] = %e .\n",mean_c); printf(" Note that this can improve but also worsen the results.\n"); printf(" Revert the result and make a burn-in removal instead if the results get worse.\n"); } if(k==0){ printf(" Congratulations! The convercence seems good. \n"); } printf("\n ------------------------------------------------------------------------ \n"); } free(chain_results); } else{ init_msg(proposal); LHSampling(proposal, 0); printf(" ------------------------------------------------------------------------ \n"); } return 0; }
read_matrix.h
//------------------------------------------------------------------------------ // GraphBLAS/Demo/Include/demos.h: include file for all demo programs //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #ifndef GRAPHBLAS_DEMOS_H #define GRAPHBLAS_DEMOS_H #include <stdbool.h> #include "GraphBLAS.h" // #include "simple_rand.h" // #include "simple_timer.h" // #include "usercomplex.h" //------------------------------------------------------------------------------ // manage compiler warnings //------------------------------------------------------------------------------ #if defined __INTEL_COMPILER #pragma warning (disable: 58 167 144 177 181 186 188 589 593 869 981 1418 1419 1572 1599 2259 2282 2557 2547 3280 ) #elif defined __GNUC__ #pragma GCC diagnostic ignored "-Wunknown-pragmas" //#pragma GCC diagnostic ignored "-Wunknown-warning-option" #pragma GCC diagnostic ignored "-Wformat-truncation=" #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunused-result" #pragma GCC diagnostic ignored "-Wint-in-bool-context" #pragma GCC diagnostic ignored "-Wunused-parameter" // #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wtype-limits" #pragma GCC diagnostic ignored "-Wincompatible-pointer-types" // enable these warnings as errors #pragma GCC diagnostic error "-Wmisleading-indentation" #pragma GCC diagnostic error "-Wswitch-default" #endif #undef MIN #undef MAX #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) GrB_Info read_matrix // read a double-precision matrix ( GrB_Matrix *A, // handle of matrix to create FILE *f, // file to read the tuples from bool make_symmetric, // if true, return A as symmetric bool no_self_edges, // if true, then remove self edges from A bool one_based, // if true, input matrix is 1-based bool boolean, // if true, input is GrB_BOOL, otherwise GrB_FP64 bool printstuff // if true, print status to stdout ) ; extern int32_t level ; #pragma omp threadprivate(level) // multiplicative scaling factor for ipagerank, ZSCALE = 2^30 #define ZSCALE ((uint64_t) 1073741824) //------------------------------------------------------------------------------ // CHECK: expr must be true; if not, return an error condition //------------------------------------------------------------------------------ // the #include'ing file must define the FREE_ALL macro #define CHECK(expr,info) \ { \ if (! (expr)) \ { \ /* free the result and all workspace, and return NULL */ \ FREE_ALL ; \ printf ("Failure: line %d file %s\n", __LINE__, __FILE__) ; \ return (info) ; \ } \ } //------------------------------------------------------------------------------ // OK: call a GraphBLAS method and check the result //------------------------------------------------------------------------------ // OK(method) is a macro that calls a GraphBLAS method and checks the status; // if a failure occurs, it handles the error via the CHECK macro above, and // returns the error status to the caller. #define OK(method) \ { \ info = method ; \ if (info != GrB_SUCCESS) \ { \ printf ("GraphBLAS error:\n%s\n", GrB_error ( )) ; \ CHECK (false, info) ; \ } \ } #endif //------------------------------------------------------------------------------ // GraphBLAS/Demo/Source/read_matrix.c: read a matrix from stdin //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Reads a matrix from stdin. For sample inputs, see the Matrix/* files. // Each line has the form: // // i j x // // where i and j are the row and column indices, and x is the value. // The matrix is read in double precision. // free all workspace; this used by the OK(...) macro if an error occurs #define FREE_ALL \ if (I != NULL) free (I) ; \ if (J != NULL) free (J) ; \ if (X != NULL) free (X) ; \ if (I2 != NULL) free (I2) ; \ if (J2 != NULL) free (J2) ; \ if (X2 != NULL) free (X2) ; \ GrB_free (&scale2_op) ; \ GrB_free (&dt2) ; \ GrB_free (&dt1) ; \ GrB_free (&A) ; \ GrB_free (&B) ; \ GrB_free (&C) ; //------------------------------------------------------------------------------ // unary operator to divide by 2 //------------------------------------------------------------------------------ void scale2 (double *z, const double *x) { (*z) = (*x) / 2.0 ; } //------------------------------------------------------------------------------ // read a matrix from a file //------------------------------------------------------------------------------ GrB_Info read_matrix // read a double-precision or boolean matrix ( GrB_Matrix *A_output, // handle of matrix to create FILE *f, // file to read the tuples from bool make_symmetric, // if true, return A as symmetric bool no_self_edges, // if true, then remove self edges from A bool one_based, // if true, input matrix is 1-based bool boolean, // if true, input is GrB_BOOL, otherwise GrB_FP64 bool pr // if true, print status to stdout ) { int64_t len = 256 ; int64_t ntuples = 0 ; double x ; GrB_Index nvals ; //-------------------------------------------------------------------------- // set all pointers to NULL so that FREE_ALL can free everything safely //-------------------------------------------------------------------------- GrB_Matrix C = NULL, A = NULL, B = NULL ; GrB_Descriptor dt1 = NULL, dt2 = NULL ; GrB_UnaryOp scale2_op = NULL ; //-------------------------------------------------------------------------- // allocate initial space for tuples //-------------------------------------------------------------------------- size_t xsize = ((boolean) ? sizeof (bool) : sizeof (double)) ; GrB_Index *I = malloc (len * sizeof (int64_t)), *I2 = NULL ; GrB_Index *J = malloc (len * sizeof (int64_t)), *J2 = NULL ; void *X = malloc (len * xsize) ; bool *Xbool ; double *Xdouble ; void *X2 = NULL ; if (I == NULL || J == NULL || X == NULL) { // out of memory if (pr) printf ("out of memory for initial tuples\n") ; FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } Xbool = (bool *) X ; Xdouble = (double *) X ; //-------------------------------------------------------------------------- // read in the tuples from stdin, one per line //-------------------------------------------------------------------------- // format warnings vary with compilers, so read in as double double i2, j2 ; while (fscanf (f, "%lg %lg %lg\n", &i2, &j2, &x) != EOF) { int64_t i = (int64_t) i2 ; int64_t j = (int64_t) j2 ; if (ntuples >= len) { I2 = realloc (I, 2 * len * sizeof (int64_t)) ; J2 = realloc (J, 2 * len * sizeof (int64_t)) ; X2 = realloc (X, 2 * len * xsize) ; if (I2 == NULL || J2 == NULL || X2 == NULL) { if (pr) printf ("out of memory for tuples\n") ; FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } I = I2 ; I2 = NULL ; J = J2 ; J2 = NULL ; X = X2 ; X2 = NULL ; len = len * 2 ; Xbool = (bool *) X ; Xdouble = (double *) X ; } if (one_based) { i-- ; j-- ; } I [ntuples] = i ; J [ntuples] = j ; if (boolean) { Xbool [ntuples] = (x != 0) ; } else { Xdouble [ntuples] = x ; } ntuples++ ; } //-------------------------------------------------------------------------- // find the dimensions //-------------------------------------------------------------------------- if (pr) printf ("ntuples: %.16g\n", (double) ntuples) ; int64_t nrows = 0 ; int64_t ncols = 0 ; for (int64_t k = 0 ; k < ntuples ; k++) { nrows = MAX (nrows, I [k]) ; ncols = MAX (ncols, J [k]) ; } nrows++ ; ncols++ ; if (pr) printf ("nrows %.16g ncols %.16g\n", (double) nrows, (double) ncols) ; //-------------------------------------------------------------------------- // prune self edges //-------------------------------------------------------------------------- // but not if creating the augmented system aka a bipartite graph double tic [2], t1 ; if (no_self_edges && ! (make_symmetric && nrows != ncols)) { int64_t ntuples2 = 0 ; for (int64_t k = 0 ; k < ntuples ; k++) { if (I [k] != J [k]) { // keep this off-diagonal edge I [ntuples2] = I [k] ; J [ntuples2] = J [k] ; if (boolean) { Xbool [ntuples2] = Xbool [k] ; } else { Xdouble [ntuples2] = Xdouble [k] ; } ntuples2++ ; } } ntuples = ntuples2 ; } //-------------------------------------------------------------------------- // build the matrix, summing up duplicates, and then free the tuples //-------------------------------------------------------------------------- GrB_Type xtype ; GrB_BinaryOp xop, xop2 ; if (boolean) { xtype = GrB_BOOL ; xop = GrB_LOR ; xop2 = GrB_FIRST_BOOL ; } else { xtype = GrB_FP64 ; xop = GrB_PLUS_FP64 ; xop2 = GrB_FIRST_FP64 ; } GrB_Info info ; OK (GrB_Matrix_new (&C, xtype, nrows, ncols)) ; if (boolean) { OK (GrB_Matrix_build (C, I, J, Xbool, ntuples, xop)) ; } else { OK (GrB_Matrix_build (C, I, J, Xdouble, ntuples, xop)) ; } free (I) ; I = NULL ; free (J) ; J = NULL ; free (X) ; X = NULL ; //-------------------------------------------------------------------------- // construct the descriptors //-------------------------------------------------------------------------- // descriptor dt2: transpose the 2nd input OK (GrB_Descriptor_new (&dt2)) ; OK (GrB_Descriptor_set (dt2, GrB_INP1, GrB_TRAN)) ; // descriptor dt1: transpose the 1st input OK (GrB_Descriptor_new (&dt1)) ; OK (GrB_Descriptor_set (dt1, GrB_INP0, GrB_TRAN)) ; //-------------------------------------------------------------------------- // create the output matrix //-------------------------------------------------------------------------- if (make_symmetric) { //---------------------------------------------------------------------- // ensure the matrix is symmetric //---------------------------------------------------------------------- if (pr) printf ("make symmetric\n") ; if (nrows == ncols) { //------------------------------------------------------------------ // A = (C+C')/2 //------------------------------------------------------------------ if (pr) printf ("A = (C+C')/2\n") ; double tic [2], t ; OK (GrB_Matrix_new (&A, xtype, nrows, nrows)) ; OK (GrB_eWiseAdd (A, NULL, NULL, xop, C, C, dt2)) ; OK (GrB_free (&C)) ; if (boolean) { *A_output = A ; A = NULL ; } else { OK (GrB_Matrix_new (&C, xtype, nrows, nrows)) ; OK (GrB_UnaryOp_new (&scale2_op, scale2, xtype, xtype)) ; OK (GrB_apply (C, NULL, NULL, scale2_op, A, NULL)) ; OK (GrB_free (&A)) ; OK (GrB_free (&scale2_op)) ; *A_output = C ; C = NULL ; } } else { //------------------------------------------------------------------ // A = [0 C ; C' 0], a bipartite graph //------------------------------------------------------------------ // no self edges will exist if (pr) printf ("A = [0 C ; C' 0], a bipartite graph\n") ; double tic [2], t ; int64_t n = nrows + ncols ; OK (GrB_Matrix_new (&A, xtype, n, n)) ; GrB_Index I_range [3], J_range [3] ; I_range [GxB_BEGIN] = 0 ; I_range [GxB_END ] = nrows-1 ; J_range [GxB_BEGIN] = nrows ; J_range [GxB_END ] = ncols+nrows-1 ; // A (nrows:n-1, 0:nrows-1) += C' OK (GrB_assign (A, NULL, xop2, // or NULL, C, J_range, GxB_RANGE, I_range, GxB_RANGE, dt1)) ; // A (0:nrows-1, nrows:n-1) += C OK (GrB_assign (A, NULL, xop2, // or NULL, C, I_range, GxB_RANGE, J_range, GxB_RANGE, NULL)) ; // force completion; if this statement does not appear, the // timing will not account for the final build, which would be // postponed until A is used by the caller in another GraphBLAS // operation. GrB_Matrix_nvals (&nvals, A) ; *A_output = A ; // set A to NULL so the FREE_ALL macro does not free *A_output A = NULL ; } } else { //---------------------------------------------------------------------- // return the matrix as-is //---------------------------------------------------------------------- if (pr) printf ("leave A as-is\n") ; *A_output = C ; // set C to NULL so the FREE_ALL macro does not free *A_output C = NULL ; } //-------------------------------------------------------------------------- // success: free everything except the result, and return it to the caller //-------------------------------------------------------------------------- FREE_ALL ; if (pr) printf ("\nMatrix from file:\n") ; GxB_print (*A_output, pr ? GxB_SHORT : GxB_SILENT) ; return (GrB_SUCCESS) ; }
GB_binop__lor_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lor_int8 // A.*B function (eWiseMult): GB_AemultB__lor_int8 // A*D function (colscale): GB_AxD__lor_int8 // D*A function (rowscale): GB_DxB__lor_int8 // C+=B function (dense accum): GB_Cdense_accumB__lor_int8 // C+=b function (dense accum): GB_Cdense_accumb__lor_int8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lor_int8 // C=scalar+B GB_bind1st__lor_int8 // C=scalar+B' GB_bind1st_tran__lor_int8 // C=A+scalar GB_bind2nd__lor_int8 // C=A'+scalar GB_bind2nd_tran__lor_int8 // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = ((aij != 0) || (bij != 0)) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = ((x != 0) || (y != 0)) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOR || GxB_NO_INT8 || GxB_NO_LOR_INT8) //------------------------------------------------------------------------------ // 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__lor_int8 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__lor_int8 ( 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__lor_int8 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lor_int8 ( 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 int8_t *GB_RESTRICT Cx = (int8_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__lor_int8 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *GB_RESTRICT Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__lor_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lor_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lor_int8 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t bij = Bx [p] ; Cx [p] = ((x != 0) || (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lor_int8 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; Cx [p] = ((aij != 0) || (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) || (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lor_int8 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) || (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lor_int8 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
deprecate.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD EEEEE PPPP RRRR EEEEE CCCC AAA TTTTT EEEEE % % D D E P P R R E C A A T E % % D D EEE PPPPP RRRR EEE C AAAAA T EEE % % D D E P R R E C A A T E % % DDDD EEEEE P R R EEEEE CCCC A A T EEEEE % % % % % % MagickCore Deprecated Methods % % % % Software Design % % John Cristy % % October 2002 % % % % % % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/fx.h" #include "magick/geometry.h" #include "magick/identify.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/magick.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/morphology.h" #include "magick/paint.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/segment.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/utility.h" #if !defined(MAGICKCORE_EXCLUDE_DEPRECATED) /* Global declarations. */ static MonitorHandler monitor_handler = (MonitorHandler) NULL; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e C a c h e V i e w I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCacheViewIndexes() returns the indexes associated with the specified % view. % % Deprecated, replace with: % % GetCacheViewVirtualIndexQueue(cache_view); % % The format of the AcquireCacheViewIndexes method is: % % const IndexPacket *AcquireCacheViewIndexes(const CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport const IndexPacket *AcquireCacheViewIndexes( const CacheView *cache_view) { return(GetCacheViewVirtualIndexQueue(cache_view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCacheViewPixels() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewVirtualPixels(cache_view,x,y,columns,rows,exception); % % The format of the AcquireCacheViewPixels method is: % % const PixelPacket *AcquireCacheViewPixels(const CacheView *cache_view, % const ssize_t x,const ssize_t y,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *AcquireCacheViewPixels( const CacheView *cache_view,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { return(GetCacheViewVirtualPixels(cache_view,x,y,columns,rows,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImagePixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in RAM, or in a memory-mapped file. The % returned pointer should *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access % the black color component or to obtain the colormap indexes (of type % IndexPacket) corresponding to the region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the AcquireImagePixels() and GetAuthenticPixels() methods are not % thread-safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % Deprecated, replace with: % % GetVirtualPixels(image,x,y,columns,rows,exception); % % The format of the AcquireImagePixels() method is: % % const PixelPacket *AcquireImagePixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *AcquireImagePixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns, const size_t rows,ExceptionInfo *exception) { return(GetVirtualPixels(image,x,y,columns,rows,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireIndexes() returns the black channel or the colormap indexes % associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % Deprecated, replace with: % % GetVirtualIndexQueue(image); % % The format of the AcquireIndexes() method is: % % const IndexPacket *AcquireIndexes(const Image *image) % % A description of each parameter follows: % % o indexes: AcquireIndexes() returns the indexes associated with the last % call to QueueAuthenticPixels() or GetVirtualPixels(). % % o image: the image. % */ MagickExport const IndexPacket *AcquireIndexes(const Image *image) { return(GetVirtualIndexQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMemory() returns a pointer to a block of memory at least size bytes % suitably aligned for any use. % % The format of the AcquireMemory method is: % % void *AcquireMemory(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *AcquireMemory(const size_t size) { void *allocation; assert(size != 0); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); allocation=malloc(size); return(allocation); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e C a c h e V i e w P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneCacheViewPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneCacheViewAuthenticPixel() instead. % % Deprecated, replace with: % % GetOneCacheViewVirtualPixel(cache_view,x,y,pixel,exception); % % The format of the AcquireOneCacheViewPixel method is: % % MagickBooleanType AcquireOneCacheViewPixel(const CacheView *cache_view, % const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y: These values define the offset of the pixel. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AcquireOneCacheViewPixel( const CacheView *cache_view,const ssize_t x,const ssize_t y,PixelPacket *pixel, ExceptionInfo *exception) { return(GetOneCacheViewVirtualPixel(cache_view,x,y,pixel,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e C a c h e V i e w V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneCacheViewVirtualPixel() returns a single pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneCacheViewAuthenticPixel() instead. % % Deprecated, replace with: % % GetOneCacheViewVirtualMethodPixel(cache_view,virtual_pixel_method, % x,y,pixel,exception); % % The format of the AcquireOneCacheViewPixel method is: % % MagickBooleanType AcquireOneCacheViewVirtualPixel( % const CacheView *cache_view, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the offset of the pixel. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AcquireOneCacheViewVirtualPixel( const CacheView *cache_view,const VirtualPixelMethod virtual_pixel_method, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { MagickBooleanType status; status=GetOneCacheViewVirtualMethodPixel(cache_view,virtual_pixel_method, x,y,pixel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e M a g i c k P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneMagickPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOnePixel() instead. % % Deprecated, replace with: % % MagickPixelPacket pixel; % GetOneVirtualMagickPixel(image,x,y,&pixel,exception); % % The format of the AcquireOneMagickPixel() method is: % % MagickPixelPacket AcquireOneMagickPixel(const Image image,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickPixelPacket AcquireOneMagickPixel(const Image *image, const ssize_t x,const ssize_t y,ExceptionInfo *exception) { MagickPixelPacket pixel; (void) GetOneVirtualMagickPixel(image,x,y,&pixel,exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOnePixel() returns a single pixel at the specified (x,y) location. % The image background color is returned if an error occurs. If you plan to % modify the pixel, use GetOnePixel() instead. % % Deprecated, replace with: % % PixelPacket pixel; % GetOneVirtualPixel(image,x,y,&pixel,exception); % % The format of the AcquireOnePixel() method is: % % PixelPacket AcquireOnePixel(const Image image,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket AcquireOnePixel(const Image *image,const ssize_t x, const ssize_t y,ExceptionInfo *exception) { PixelPacket pixel; (void) GetOneVirtualPixel(image,x,y,&pixel,exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneVirtualPixel() returns a single pixel at the specified (x,y) % location as defined by specified pixel method. The image background color % is returned if an error occurs. If you plan to modify the pixel, use % GetOnePixel() instead. % % Deprecated, replace with: % % PixelPacket pixel; % GetOneVirtualMethodPixel(image,virtual_pixel_method,x,y,&pixel,exception); % % The format of the AcquireOneVirtualPixel() method is: % % PixelPacket AcquireOneVirtualPixel(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o virtual_pixel_method: the virtual pixel method. % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket AcquireOneVirtualPixel(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, ExceptionInfo *exception) { PixelPacket pixel; (void) GetOneVirtualMethodPixel(image,virtual_pixel_method,x,y,&pixel, exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixels() returns the pixels associated with the last call to % QueueAuthenticPixels() or GetVirtualPixels(). % % Deprecated, replace with: % % GetVirtualPixelQueue(image); % % The format of the AcquirePixels() method is: % % const PixelPacket *AcquirePixels(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const PixelPacket *AcquirePixels(const Image *image) { return(GetVirtualPixelQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A f f i n i t y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AffinityImage() replaces the colors of an image with the closest color from % a reference image. % % Deprecated, replace with: % % RemapImage(quantize_info,image,affinity_image); % % The format of the AffinityImage method is: % % MagickBooleanType AffinityImage(const QuantizeInfo *quantize_info, % Image *image,const Image *affinity_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o affinity_image: the reference image. % */ MagickExport MagickBooleanType AffinityImage(const QuantizeInfo *quantize_info, Image *image,const Image *affinity_image) { return(RemapImage(quantize_info,image,affinity_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A f f i n i t y I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AffinityImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % Deprecated, replace with: % % RemapImages(quantize_info,images,affinity_image); % % The format of the AffinityImage method is: % % MagickBooleanType AffinityImages(const QuantizeInfo *quantize_info, % Image *images,Image *affinity_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o affinity_image: the reference image. % */ MagickExport MagickBooleanType AffinityImages(const QuantizeInfo *quantize_info, Image *images,const Image *affinity_image) { return(RemapImages(quantize_info,images,affinity_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateImage() returns a pointer to an image structure initialized to % default values. % % Deprecated, replace with: % % AcquireImage(image_info); % % The format of the AllocateImage method is: % % Image *AllocateImage(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % */ MagickExport Image *AllocateImage(const ImageInfo *image_info) { return(AcquireImage(image_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateImageColormap() allocates an image colormap and initializes % it to a linear gray colorspace. If the image already has a colormap, % it is replaced. AllocateImageColormap() returns MagickTrue if successful, % otherwise MagickFalse if there is not enough memory. % % Deprecated, replace with: % % AcquireImageColormap(image,colors); % % The format of the AllocateImageColormap method is: % % MagickBooleanType AllocateImageColormap(Image *image, % const size_t colors) % % A description of each parameter follows: % % o image: the image. % % o colors: the number of colors in the image colormap. % */ MagickExport MagickBooleanType AllocateImageColormap(Image *image, const size_t colors) { return(AcquireImageColormap(image,colors)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % Deprecated, replace with: % % AcquireNextImage(image_info,image); % % The format of the AllocateNextImage method is: % % void AllocateNextImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % */ MagickExport void AllocateNextImage(const ImageInfo *image_info,Image *image) { AcquireNextImage(image_info,image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateString() allocates memory for a string and copies the source string % to that memory location (and returns it). % % The format of the AllocateString method is: % % char *AllocateString(const char *source) % % A description of each parameter follows: % % o source: A character string. % */ MagickExport char *AllocateString(const char *source) { char *destination; size_t length; assert(source != (const char *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); length=strlen(source)+MaxTextExtent+1; destination=(char *) AcquireQuantumMemory(length,sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *destination='\0'; if (source != (char *) NULL) (void) CopyMagickString(destination,source,length); return(destination); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A v e r a g e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AverageImages() takes a set of images and averages them together. Each % image in the set must have the same width and height. AverageImages() % returns a single image with each corresponding pixel component of each % image averaged. On failure, a NULL image is returned and exception % describes the reason for the failure. % % Deprecated, replace with: % % EvaluateImages(images,MeanEvaluateOperator,exception); % % The format of the AverageImages method is: % % Image *AverageImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AverageImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MeanEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a n n e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Extract a channel from the image. A channel is a particular color component % of each pixel in the image. % % Deprecated, replace with: % % SeparateImageChannel(image,channel); % % The format of the ChannelImage method is: % % unsigned int ChannelImage(Image *image,const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: Identify which channel to extract: RedChannel, GreenChannel, % BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, % or BlackChannel. % */ MagickExport unsigned int ChannelImage(Image *image,const ChannelType channel) { return(SeparateImageChannel(image,channel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a n n e l T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ChannelThresholdImage() changes the value of individual pixels based on % the intensity of each pixel channel. The result is a high-contrast image. % % The format of the ChannelThresholdImage method is: % % unsigned int ChannelThresholdImage(Image *image,const char *level) % % A description of each parameter follows: % % o image: the image. % % o level: define the threshold values. % */ MagickExport unsigned int ChannelThresholdImage(Image *image,const char *level) { MagickPixelPacket threshold; GeometryInfo geometry_info; unsigned int flags, status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (level == (char *) NULL) return(MagickFalse); flags=ParseGeometry(level,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; status=BilevelImageChannel(image,RedChannel,threshold.red); status|=BilevelImageChannel(image,GreenChannel,threshold.green); status|=BilevelImageChannel(image,BlueChannel,threshold.blue); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPathImage() sets the image clip mask based any clipping path information % if it exists. % % Deprecated, replace with: % % ClipImagePath(image,pathname,inside); % % The format of the ClipImage method is: % % MagickBooleanType ClipPathImage(Image *image,const char *pathname, % const MagickBooleanType inside) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % */ MagickExport MagickBooleanType ClipPathImage(Image *image,const char *pathname, const MagickBooleanType inside) { return(ClipImagePath(image,pathname,inside)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageAttributes() clones one or more image attributes. % % Deprecated, replace with: % % CloneImageProperties(image,clone_image); % % The format of the CloneImageAttributes method is: % % MagickBooleanType CloneImageAttributes(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageAttributes(Image *image, const Image *clone_image) { return(CloneImageProperties(image,clone_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneMemory() copies size bytes from memory area source to the destination. % Copying between objects that overlap will take place correctly. It returns % destination. % % The format of the CloneMemory method is: % % void *CloneMemory(void *destination,const void *source, % const size_t size) % % A description of each parameter follows: % % o destination: the destination. % % o source: the source. % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *CloneMemory(void *destination,const void *source, const size_t size) { register const unsigned char *p; register unsigned char *q; register ssize_t i; assert(destination != (void *) NULL); assert(source != (const void *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); p=(const unsigned char *) source; q=(unsigned char *) destination; if ((p <= q) || ((p+size) >= q)) return(CopyMagickMemory(destination,source,size)); /* Overlap, copy backwards. */ p+=size; q+=size; for (i=(ssize_t) (size-1); i >= 0; i--) *--q=(*--p); return(destination); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o s e C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloseCacheView() closes the specified view returned by a previous call to % OpenCacheView(). % % Deprecated, replace with: % % DestroyCacheView(view_info); % % The format of the CloseCacheView method is: % % CacheView *CloseCacheView(CacheView *view_info) % % A description of each parameter follows: % % o view_info: the address of a structure of type CacheView. % */ MagickExport CacheView *CloseCacheView(CacheView *view_info) { return(DestroyCacheView(view_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorFloodfill() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % The format of the ColorFloodfillImage method is: % % MagickBooleanType ColorFloodfillImage(Image *image, % const DrawInfo *draw_info,const PixelPacket target, % const ssize_t x_offset,const ssize_t y_offset,const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x,y: the starting location of the operation. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ #define MaxStacksize (1UL << 15) #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } MagickExport MagickBooleanType ColorFloodfillImage(Image *image, const DrawInfo *draw_info,const PixelPacket target,const ssize_t x_offset, const ssize_t y_offset,const PaintMethod method) { Image *floodplane_image; MagickBooleanType skip; PixelPacket fill_color; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); /* Set floodfill color. */ segment_stack=(SegmentInfo *) AcquireQuantumMemory(MaxStacksize, sizeof(*segment_stack)); if (segment_stack == (SegmentInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Push initial segment on stack. */ x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); while (s > segment_stack) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetVirtualPixels(image,0,y,(size_t) (x1+1),1,&image->exception); q=GetAuthenticPixels(floodplane_image,0,y,(size_t) (x1+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; p--; q--; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetVirtualPixels(image,x,y,image->columns-x,1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,image->columns-x,1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; p++; q++; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetVirtualPixels(image,x,y,(size_t) (x2-x+1),1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,(size_t) (x2-x+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) != MagickFalse) break; } else if (IsColorSimilar(image,p,&target) == MagickFalse) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Tile fill color onto floodplane. */ p=GetVirtualPixels(floodplane_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) { (void) GetFillColor(draw_info,x,y,&fill_color); MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q, (MagickRealType) q->opacity,q); } p++; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } segment_stack=(SegmentInfo *) RelinquishMagickMemory(segment_stack); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageAttribute() deletes an attribute from the image. % % Deprecated, replace with: % % DeleteImageProperty(image,key); % % The format of the DeleteImageAttribute method is: % % MagickBooleanType DeleteImageAttribute(Image *image,const char *key) % % A description of each parameter follows: % % o image: the image info. % % o key: the image key. % */ MagickExport MagickBooleanType DeleteImageAttribute(Image *image, const char *key) { return(DeleteImageProperty(image,key)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageList() deletes an image at the specified position in the list. % % The format of the DeleteImageList method is: % % unsigned int DeleteImageList(Image *images,const ssize_t offset) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % */ MagickExport unsigned int DeleteImageList(Image *images,const ssize_t offset) { register ssize_t i; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); while (GetPreviousImageInList(images) != (Image *) NULL) images=GetPreviousImageInList(images); for (i=0; i < offset; i++) { if (GetNextImageInList(images) == (Image *) NULL) return(MagickFalse); images=GetNextImageInList(images); } DeleteImageFromList(&images); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteMagickRegistry() deletes an entry in the registry as defined by the id. % It returns MagickTrue if the entry is deleted otherwise MagickFalse if no % entry is found in the registry that matches the id. % % Deprecated, replace with: % % char key[MaxTextExtent]; % FormatLocaleString(key,MaxTextExtent,"%ld\n",id); % DeleteImageRegistry(key); % % The format of the DeleteMagickRegistry method is: % % MagickBooleanType DeleteMagickRegistry(const ssize_t id) % % A description of each parameter follows: % % o id: the registry id. % */ MagickExport MagickBooleanType DeleteMagickRegistry(const ssize_t id) { char key[MaxTextExtent]; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); return(DeleteImageRegistry(key)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C o n s t i t u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyConstitute() destroys the constitute component. % % The format of the DestroyConstitute method is: % % DestroyConstitute(void) % */ MagickExport void DestroyConstitute(void) { ConstituteComponentTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagickRegistry() deallocates memory associated the magick registry. % % Deprecated, replace with: % % RegistryComponentTerminus(); % % The format of the DestroyMagickRegistry method is: % % void DestroyMagickRegistry(void) % */ MagickExport void DestroyMagickRegistry(void) { RegistryComponentTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s c r i b e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DescribeImage() describes an image by printing its attributes to the file. % Attributes include the image width, height, size, and others. % % Deprecated, replace with: % % IdentifyImage(image,file,verbose); % % The format of the DescribeImage method is: % % MagickBooleanType DescribeImage(Image *image,FILE *file, % const MagickBooleanType verbose) % % A description of each parameter follows: % % o image: the image. % % o file: the file, typically stdout. % % o verbose: A value other than zero prints more detailed information % about the image. % */ MagickExport MagickBooleanType DescribeImage(Image *image,FILE *file, const MagickBooleanType verbose) { return(IdentifyImage(image,file,verbose)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageAttributes() deallocates memory associated with the image % attribute list. % % The format of the DestroyImageAttributes method is: % % DestroyImageAttributes(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageAttributes(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->attributes != (void *) NULL) image->attributes=(void *) DestroySplayTree((SplayTreeInfo *) image->attributes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImages() destroys an image list. % % Deprecated, replace with: % % DestroyImageList(image); % % The format of the DestroyImages method is: % % void DestroyImages(Image *image) % % A description of each parameter follows: % % o image: the image sequence. % */ MagickExport void DestroyImages(Image *image) { if (image == (Image *) NULL) return; if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.3"); image=DestroyImageList(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y M a g i c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagick() destroys the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreTerminus(); % % The format of the DestroyMagick function is: % % DestroyMagick(void) % */ MagickExport void DestroyMagick(void) { MagickCoreTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p a t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DispatchImage() extracts pixel data from an image and returns it to you. % The method returns MagickFalse on success otherwise MagickTrue if an error is % encountered. The data is returned as char, short int, int, ssize_t, float, % or double in the order specified by map. % % Suppose you want to extract the first scanline of a 640x480 image as % character data in red-green-blue order: % % DispatchImage(image,0,0,640,1,"RGB",CharPixel,pixels,exception); % % Deprecated, replace with: % % ExportImagePixels(image,x_offset,y_offset,columns,rows,map,type,pixels, % exception); % % The format of the DispatchImage method is: % % unsigned int DispatchImage(const Image *image,const ssize_t x_offset, % const ssize_t y_offset,const size_t columns, % const size_t rows,const char *map,const StorageType type, % void *pixels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x_offset, y_offset, columns, rows: These values define the perimeter % of a region of pixels you want to extract. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or % I = intensity (for grayscale). % % o type: Define the data type of the pixels. Float and double types are % normalized to [0..1] otherwise [0..QuantumRange]. Choose from these % types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel, or % DoublePixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int DispatchImage(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const char *map,const StorageType type,void *pixels,ExceptionInfo *exception) { unsigned int status; if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); status=ExportImagePixels(image,x_offset,y_offset,columns,rows,map,type,pixels, exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x t r a c t S u b i m a g e F r o m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExtractSubimageFromImageImage() extracts a region of the image that most % closely resembles the reference. % % The format of the ExtractSubimageFromImageImage method is: % % Image *ExtractSubimageFromImage(const Image *image, % const Image *reference,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reference: find an area of the image that closely resembles this image. % % o exception: return any errors or warnings in this structure. % */ static double GetSimilarityMetric(const Image *image,const Image *reference, const ssize_t x_offset,const ssize_t y_offset, const double similarity_threshold,ExceptionInfo *exception) { CacheView *image_view, *reference_view; double channels, normalized_similarity, similarity; ssize_t y; /* Compute the similarity in pixels between two images. */ normalized_similarity=1.0; similarity=0.0; channels=3; if ((image->matte != MagickFalse) && (reference->matte != MagickFalse)) channels++; if ((image->colorspace == CMYKColorspace) && (reference->colorspace == CMYKColorspace)) channels++; image_view=AcquireVirtualCacheView(image,exception); reference_view=AcquireVirtualCacheView(reference,exception); for (y=0; y < (ssize_t) reference->rows; y++) { register const IndexPacket *indexes, *reference_indexes; register const PixelPacket *p, *q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset+y, reference->columns,1,exception); q=GetCacheViewVirtualPixels(reference_view,0,y,reference->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) continue; indexes=GetCacheViewVirtualIndexQueue(image_view); reference_indexes=GetCacheViewVirtualIndexQueue(reference_view); for (x=0; x < (ssize_t) reference->columns; x++) { MagickRealType pixel; pixel=QuantumScale*(GetPixelRed(p)-(double) GetPixelRed(q)); similarity+=pixel*pixel; pixel=QuantumScale*(GetPixelGreen(p)-(double) GetPixelGreen(q)); similarity+=pixel*pixel; pixel=QuantumScale*(GetPixelBlue(p)-(double) GetPixelBlue(q)); similarity+=pixel*pixel; if ((image->matte != MagickFalse) && (reference->matte != MagickFalse)) { pixel=QuantumScale*(GetPixelOpacity(p)-(double) GetPixelOpacity(q)); similarity+=pixel*pixel; } if ((image->colorspace == CMYKColorspace) && (reference->colorspace == CMYKColorspace)) { pixel=QuantumScale*(GetPixelIndex(indexes+x)-(double) GetPixelIndex(reference_indexes+x)); similarity+=pixel*pixel; } p++; q++; } normalized_similarity=sqrt(similarity)/reference->columns/reference->rows/ channels; if (normalized_similarity > similarity_threshold) break; } reference_view=DestroyCacheView(reference_view); image_view=DestroyCacheView(image_view); return(normalized_similarity); } MagickExport Image *ExtractSubimageFromImage(Image *image, const Image *reference,ExceptionInfo *exception) { double similarity_threshold; RectangleInfo offset; ssize_t y; /* Extract reference from image. */ if ((reference->columns > image->columns) || (reference->rows > image->rows)) return((Image *) NULL); similarity_threshold=(double) image->columns*image->rows; SetGeometry(reference,&offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (y=0; y < (ssize_t) (image->rows-reference->rows); y++) { double similarity; register ssize_t x; for (x=0; x < (ssize_t) (image->columns-reference->columns); x++) { similarity=GetSimilarityMetric(image,reference,x,y,similarity_threshold, exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ExtractSubimageFromImage) #endif if (similarity < similarity_threshold) { similarity_threshold=similarity; offset.x=x; offset.y=y; } } } if (similarity_threshold > (QuantumScale*reference->fuzz/100.0)) return((Image *) NULL); return(CropImage(image,&offset,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l a t t e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlattenImages() Obsolete Function: Use MergeImageLayers() instead. % % Deprecated, replace with: % % MergeImageLayers(image,FlattenLayer,exception); % % The format of the FlattenImage method is: % % Image *FlattenImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FlattenImages(Image *image,ExceptionInfo *exception) { return(MergeImageLayers(image,FlattenLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatImageAttribute() permits formatted key/value pairs to be saved as an % image attribute. % % The format of the FormatImageAttribute method is: % % MagickBooleanType FormatImageAttribute(Image *image,const char *key, % const char *format,...) % % A description of each parameter follows. % % o image: The image. % % o key: The attribute key. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport MagickBooleanType FormatImageAttributeList(Image *image, const char *key,const char *format,va_list operands) { char value[MaxTextExtent]; int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(value,MaxTextExtent,format,operands); #else n=vsprintf(value,format,operands); #endif if (n < 0) value[MaxTextExtent-1]='\0'; return(SetImageProperty(image,key,value)); } MagickExport MagickBooleanType FormatImagePropertyList(Image *image, const char *property,const char *format,va_list operands) { char value[MaxTextExtent]; int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(value,MaxTextExtent,format,operands); #else n=vsprintf(value,format,operands); #endif if (n < 0) value[MaxTextExtent-1]='\0'; return(SetImageProperty(image,property,value)); } MagickExport MagickBooleanType FormatImageAttribute(Image *image, const char *key,const char *format,...) { char value[MaxTextExtent]; int n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(value,MaxTextExtent,format,operands); (void) n; va_end(operands); return(SetImageProperty(image,key,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t M a g i c k S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatMagickString() prints formatted output of a variable argument list. % % The format of the FormatMagickString method is: % % ssize_t FormatMagickString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatMagickString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport ssize_t FormatMagickStringList(char *string,const size_t length, const char *format,va_list operands) { int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(string,length,format,operands); #else n=vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return((ssize_t) n); } MagickExport ssize_t FormatMagickString(char *string,const size_t length, const char *format,...) { ssize_t n; va_list operands; va_start(operands,format); n=(ssize_t) FormatMagickStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatString() prints formatted output of a variable argument list. % % The format of the FormatString method is: % % void FormatString(char *string,const char *format,...) % % A description of each parameter follows. % % o string: Method FormatString returns the formatted string in this % character buffer. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport void FormatStringList(char *string,const char *format, va_list operands) { int n; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(string,MaxTextExtent,format,operands); #else n=vsprintf(string,format,operands); #endif if (n < 0) string[MaxTextExtent-1]='\0'; } MagickExport void FormatString(char *string,const char *format,...) { va_list operands; va_start(operands,format); (void) FormatLocaleStringList(string,MaxTextExtent,format,operands); va_end(operands); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y C o l o r M a t c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyColorMatch() returns true if two pixels are identical in color. % % The format of the ColorMatch method is: % % void FuzzyColorMatch(const PixelPacket *p,const PixelPacket *q, % const double fuzz) % % A description of each parameter follows: % % o p: Pixel p. % % o q: Pixel q. % % o distance: Define how much tolerance is acceptable to consider % two colors as the same. % */ MagickExport unsigned int FuzzyColorMatch(const PixelPacket *p, const PixelPacket *q,const double fuzz) { MagickPixelPacket pixel; register MagickRealType distance; if ((fuzz == 0.0) && (GetPixelRed(p) == GetPixelRed(q)) && (GetPixelGreen(p) == GetPixelGreen(q)) && (GetPixelBlue(p) == GetPixelBlue(q))) return(MagickTrue); pixel.red=GetPixelRed(p)-(MagickRealType) GetPixelRed(q); distance=pixel.red*pixel.red; if (distance > (fuzz*fuzz)) return(MagickFalse); pixel.green=GetPixelGreen(p)-(MagickRealType) GetPixelGreen(q); distance+=pixel.green*pixel.green; if (distance > (fuzz*fuzz)) return(MagickFalse); pixel.blue=GetPixelBlue(p)-(MagickRealType) GetPixelBlue(q); distance+=pixel.blue*pixel.blue; if (distance > (fuzz*fuzz)) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y C o l o r C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyColorCompare() returns MagickTrue if the distance between two colors is % less than the specified distance in a linear three dimensional color space. % This method is used by ColorFloodFill() and other algorithms which % compare two colors. % % The format of the FuzzyColorCompare method is: % % void FuzzyColorCompare(const Image *image,const PixelPacket *p, % const PixelPacket *q) % % A description of each parameter follows: % % o image: the image. % % o p: Pixel p. % % o q: Pixel q. % */ MagickExport MagickBooleanType FuzzyColorCompare(const Image *image, const PixelPacket *p,const PixelPacket *q) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.5"); return(IsColorSimilar(image,p,q)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y O p a c i t y C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyOpacityCompare() returns true if the distance between two opacity % values is less than the specified distance in a linear color space. This % method is used by MatteFloodFill() and other algorithms which compare % two opacity values. % % Deprecated, replace with: % % IsOpacitySimilar(image,p,q); % % The format of the FuzzyOpacityCompare method is: % % void FuzzyOpacityCompare(const Image *image,const PixelPacket *p, % const PixelPacket *q) % % A description of each parameter follows: % % o image: the image. % % o p: Pixel p. % % o q: Pixel q. % */ MagickExport MagickBooleanType FuzzyOpacityCompare(const Image *image, const PixelPacket *p,const PixelPacket *q) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.5"); return(IsOpacitySimilar(image,p,q)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C o n f i g u r e B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetConfigureBlob() returns the specified configure file as a blob. % % The format of the GetConfigureBlob method is: % % void *GetConfigureBlob(const char *filename,ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the configure file name. % % o path: return the full path information of the configure file. % % o length: This pointer to a size_t integer sets the initial length of the % blob. On return, it reflects the actual length of the blob. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetConfigureBlob(const char *filename,char *path, size_t *length,ExceptionInfo *exception) { void *blob; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); assert(path != (char *) NULL); assert(length != (size_t *) NULL); assert(exception != (ExceptionInfo *) NULL); blob=(void *) NULL; (void) CopyMagickString(path,filename,MaxTextExtent); #if defined(MAGICKCORE_INSTALLED_SUPPORT) #if defined(MAGICKCORE_LIBRARY_PATH) if (blob == (void *) NULL) { /* Search hard coded paths. */ (void) FormatLocaleString(path,MaxTextExtent,"%s%s", MAGICKCORE_LIBRARY_PATH,filename); if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } #endif #if defined(MAGICKCORE_WINDOWS_SUPPORT) && !(defined(MAGICKCORE_CONFIGURE_PATH) || defined(MAGICKCORE_SHARE_PATH)) if (blob == (void *) NULL) { char *key_value; /* Locate file via registry key. */ key_value=NTRegistryKeyLookup("ConfigurePath"); if (key_value != (char *) NULL) { (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",key_value, DirectorySeparator,filename); if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } } #endif #else if (blob == (void *) NULL) { char *home; home=GetEnvironmentValue("MAGICK_HOME"); if (home != (char *) NULL) { /* Search MAGICK_HOME. */ #if !defined(MAGICKCORE_POSIX_SUPPORT) (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",home, DirectorySeparator,filename); #else (void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",home, MAGICKCORE_LIBRARY_RELATIVE_PATH,filename); #endif if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); home=DestroyString(home); } home=GetEnvironmentValue("HOME"); if (home == (char *) NULL) home=GetEnvironmentValue("USERPROFILE"); if (home != (char *) NULL) { /* Search $HOME/.magick. */ (void) FormatLocaleString(path,MaxTextExtent,"%s%s.magick%s%s",home, DirectorySeparator,DirectorySeparator,filename); if ((IsPathAccessible(path) != MagickFalse) && (blob == (void *) NULL)) blob=FileToBlob(path,~0,length,exception); home=DestroyString(home); } } if ((blob == (void *) NULL) && (*GetClientPath() != '\0')) { #if !defined(MAGICKCORE_POSIX_SUPPORT) (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",GetClientPath(), DirectorySeparator,filename); #else char prefix[MaxTextExtent]; /* Search based on executable directory if directory is known. */ (void) CopyMagickString(prefix,GetClientPath(), MaxTextExtent); ChopPathComponents(prefix,1); (void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",prefix, MAGICKCORE_LIBRARY_RELATIVE_PATH,filename); #endif if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } /* Search current directory. */ if ((blob == (void *) NULL) && (IsPathAccessible(path) != MagickFalse)) blob=FileToBlob(path,~0,length,exception); #if defined(MAGICKCORE_WINDOWS_SUPPORT) /* Search Windows registry. */ if (blob == (void *) NULL) blob=NTResourceToBlob(filename); #endif #endif if (blob == (void *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),ConfigureWarning, "UnableToOpenConfigureFile","`%s'",path); return(blob); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheView() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned if % the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the GetCacheView method is: % % PixelPacket *GetCacheView(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the address of a structure of type CacheView. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetCacheView(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheViewIndexes() returns the indexes associated with the specified % view. % % Deprecated, replace with: % % GetCacheViewAuthenticIndexQueue(cache_view); % % The format of the GetCacheViewIndexes method is: % % IndexPacket *GetCacheViewIndexes(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport IndexPacket *GetCacheViewIndexes(CacheView *cache_view) { return(GetCacheViewAuthenticIndexQueue(cache_view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheViewPixels() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned if % the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the GetCacheViewPixels method is: % % PixelPacket *GetCacheViewPixels(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetCacheViewPixels(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageAttribute() searches the list of image attributes and returns % a pointer to the attribute if it exists otherwise NULL. % % The format of the GetImageAttribute method is: % % const ImageAttribute *GetImageAttribute(const Image *image, % const char *key) % % A description of each parameter follows: % % o image: the image. % % o key: These character strings are the name of an image attribute to % return. % */ static void *DestroyAttribute(void *attribute) { register ImageAttribute *p; p=(ImageAttribute *) attribute; if (p->value != (char *) NULL) p->value=DestroyString(p->value); return(RelinquishMagickMemory(p)); } MagickExport const ImageAttribute *GetImageAttribute(const Image *image, const char *key) { const char *value; ImageAttribute *attribute; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); value=GetImageProperty(image,key); if (value == (const char *) NULL) return((const ImageAttribute *) NULL); if (image->attributes == (void *) NULL) ((Image *) image)->attributes=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,DestroyAttribute); else { const ImageAttribute *attribute; attribute=(const ImageAttribute *) GetValueFromSplayTree((SplayTreeInfo *) image->attributes,key); if (attribute != (const ImageAttribute *) NULL) return(attribute); } attribute=(ImageAttribute *) AcquireMagickMemory(sizeof(*attribute)); if (attribute == (ImageAttribute *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(attribute,0,sizeof(*attribute)); attribute->key=ConstantString(key); attribute->value=ConstantString(value); (void) AddValueToSplayTree((SplayTreeInfo *) ((Image *) image)->attributes, attribute->key,attribute); return((const ImageAttribute *) attribute); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C l i p p i n g P a t h A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageClippingPathAttribute() searches the list of image attributes and % returns a pointer to a clipping path if it exists otherwise NULL. % % Deprecated, replace with: % % GetImageAttribute(image,"8BIM:1999,2998"); % % The format of the GetImageClippingPathAttribute method is: % % const ImageAttribute *GetImageClippingPathAttribute(Image *image) % % A description of each parameter follows: % % o attribute: Method GetImageClippingPathAttribute returns the clipping % path if it exists otherwise NULL. % % o image: the image. % */ MagickExport const ImageAttribute *GetImageClippingPathAttribute(Image *image) { return(GetImageAttribute(image,"8BIM:1999,2998")); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F r o m M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFromMagickRegistry() gets an image from the registry as defined by % its name. If the image is not found, a NULL image is returned. % % Deprecated, replace with: % % GetImageRegistry(ImageRegistryType,name,exception); % % The format of the GetImageFromMagickRegistry method is: % % Image *GetImageFromMagickRegistry(const char *name,ssize_t *id, % ExceptionInfo *exception) % % A description of each parameter follows: % % o name: the name of the image to retrieve from the registry. % % o id: the registry id. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GetImageFromMagickRegistry(const char *name,ssize_t *id, ExceptionInfo *exception) { *id=0L; return((Image *) GetImageRegistry(ImageRegistryType,name,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickRegistry() gets a blob from the registry as defined by the id. If % the blob that matches the id is not found, NULL is returned. % % The format of the GetMagickRegistry method is: % % const void *GetMagickRegistry(const ssize_t id,RegistryType *type, % size_t *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o id: the registry id. % % o type: the registry type. % % o length: the blob length in number of bytes. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetMagickRegistry(const ssize_t id,RegistryType *type, size_t *length,ExceptionInfo *exception) { char key[MaxTextExtent]; void *blob; *type=UndefinedRegistryType; *length=0; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); blob=(void *) GetImageRegistry(ImageRegistryType,key,exception); if (blob != (void *) NULL) return(blob); blob=(void *) GetImageRegistry(ImageInfoRegistryType,key,exception); if (blob != (void *) NULL) return(blob); return((void *) GetImageRegistry(UndefinedRegistryType,key,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageGeometry() returns a region as defined by the geometry string with % respect to the image and its gravity. % % Deprecated, replace with: % % if (size_to_fit != MagickFalse) % ParseRegionGeometry(image,geometry,region_info,&image->exception); else % ParsePageGeometry(image,geometry,region_info,&image->exception); % % The format of the GetImageGeometry method is: % % int GetImageGeometry(Image *image,const char *geometry, % const unsigned int size_to_fit,RectangeInfo *region_info) % % A description of each parameter follows: % % o flags: Method GetImageGeometry returns a bitmask that indicates % which of the four values were located in the geometry string. % % o geometry: The geometry (e.g. 100x100+10+10). % % o size_to_fit: A value other than 0 means to scale the region so it % fits within the specified width and height. % % o region_info: the region as defined by the geometry string with % respect to the image and its gravity. % */ MagickExport int GetImageGeometry(Image *image,const char *geometry, const unsigned int size_to_fit,RectangleInfo *region_info) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.4"); if (size_to_fit != MagickFalse) return((int) ParseRegionGeometry(image,geometry,region_info,&image->exception)); return((int) ParsePageGeometry(image,geometry,region_info,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageList() returns an image at the specified position in the list. % % Deprecated, replace with: % % CloneImage(GetImageFromList(images,(ssize_t) offset),0,0,MagickTrue, % exception); % % The format of the GetImageList method is: % % Image *GetImageList(const Image *images,const ssize_t offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GetImageList(const Image *images,const ssize_t offset, ExceptionInfo *exception) { Image *image; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); image=CloneImage(GetImageFromList(images,(ssize_t) offset),0,0,MagickTrue, exception); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageListIndex() returns the position in the list of the specified % image. % % Deprecated, replace with: % % GetImageIndexInList(images); % % The format of the GetImageListIndex method is: % % ssize_t GetImageListIndex(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport ssize_t GetImageListIndex(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetImageIndexInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageListSize() returns the number of images in the list. % % Deprecated, replace with: % % GetImageListLength(images); % % The format of the GetImageListSize method is: % % size_t GetImageListSize(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport size_t GetImageListSize(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetImageListLength(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a PixelPacket array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in RAM, or in a memory-mapped file. The returned pointer % should *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or if the storage class is % PseduoClass, call GetAuthenticIndexQueue() after invoking GetImagePixels() % to obtain the black color component or colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % Deprecated, replace with: % % GetAuthenticPixels(image,x,y,columns,rows,&image->exception); % % The format of the GetImagePixels() method is: % % PixelPacket *GetImagePixels(Image *image,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetImagePixels(Image *image,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows) { return(GetAuthenticPixels(image,x,y,columns,rows,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetIndexes() returns the black channel or the colormap indexes associated % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the black channel or colormap indexes are not available. % % Deprecated, replace with: % % GetAuthenticIndexQueue(image); % % The format of the GetIndexes() method is: % % IndexPacket *GetIndexes(const Image *image) % % A description of each parameter follows: % % o indexes: GetIndexes() returns the indexes associated with the last % call to QueueAuthenticPixels() or GetAuthenticPixels(). % % o image: the image. % */ MagickExport IndexPacket *GetIndexes(const Image *image) { return(GetAuthenticIndexQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t M a g i c k G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickGeometry() is similar to GetGeometry() except the returned % geometry is modified as determined by the meta characters: %, !, <, >, % and ~. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,x,y,width,height); % % The format of the GetMagickGeometry method is: % % unsigned int GetMagickGeometry(const char *geometry,ssize_t *x,ssize_t *y, % size_t *width,size_t *height) % % A description of each parameter follows: % % o geometry: Specifies a character string representing the geometry % specification. % % o x,y: A pointer to an integer. The x and y offset as determined by % the geometry specification is returned here. % % o width,height: A pointer to an unsigned integer. The width and height % as determined by the geometry specification is returned here. % */ MagickExport unsigned int GetMagickGeometry(const char *geometry,ssize_t *x, ssize_t *y,size_t *width,size_t *height) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.3"); return(ParseMetaGeometry(geometry,x,y,width,height)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImage() returns the next image in a list. % % Deprecated, replace with: % % GetNextImageInList(images); % % The format of the GetNextImage method is: % % Image *GetNextImage(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *GetNextImage(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetNextImageInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageAttribute() gets the next image attribute. % % Deprecated, replace with: % % const char *property; % property=GetNextImageProperty(image); % if (property != (const char *) NULL) % GetImageAttribute(image,property); % % The format of the GetNextImageAttribute method is: % % const ImageAttribute *GetNextImageAttribute(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const ImageAttribute *GetNextImageAttribute(const Image *image) { const char *property; property=GetNextImageProperty(image); if (property == (const char *) NULL) return((const ImageAttribute *) NULL); return(GetImageAttribute(image,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N u m b e r S c e n e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNumberScenes() returns the number of images in the list. % % Deprecated, replace with: % % GetImageListLength(image); % % The format of the GetNumberScenes method is: % % unsigned int GetNumberScenes(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport unsigned int GetNumberScenes(const Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return((unsigned int) GetImageListLength(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOnePixel() returns a single pixel at the specified (x,y) location. % The image background color is returned if an error occurs. % % Deprecated, replace with: % % GetOneAuthenticPixel(image,x,y,&pixel,&image->exception); % % The format of the GetOnePixel() method is: % % PixelPacket GetOnePixel(const Image image,const ssize_t x,const ssize_t y) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % */ MagickExport PixelPacket GetOnePixel(Image *image,const ssize_t x,const ssize_t y) { PixelPacket pixel; (void) GetOneAuthenticPixel(image,x,y,&pixel,&image->exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixels() returns the pixels associated with the last call to % QueueAuthenticPixels() or GetAuthenticPixels(). % % Deprecated, replace with: % % GetAuthenticPixelQueue(image); % % The format of the GetPixels() method is: % % PixelPacket *GetPixels(const Image image) % % A description of each parameter follows: % % o pixels: GetPixels() returns the pixels associated with the last call % to QueueAuthenticPixels() or GetAuthenticPixels(). % % o image: the image. % */ MagickExport PixelPacket *GetPixels(const Image *image) { return(GetAuthenticPixelQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P r e v i o u s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPreviousImage() returns the previous image in a list. % % Deprecated, replace with: % % GetPreviousImageInList(images)); % % The format of the GetPreviousImage method is: % % Image *GetPreviousImage(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *GetPreviousImage(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetPreviousImageInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H S L T r a n s f o r m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HSLTransform() converts a (hue, saturation, lightness) to a (red, green, % blue) triple. % % The format of the HSLTransformImage method is: % % void HSLTransform(const double hue,const double saturation, % const double lightness,Quantum *red,Quantum *green,Quantum *blue) % % A description of each parameter follows: % % o hue, saturation, lightness: A double value representing a % component of the HSL color space. % % o red, green, blue: A pointer to a pixel component of type Quantum. % */ static inline MagickRealType HueToRGB(MagickRealType m1,MagickRealType m2, MagickRealType hue) { if (hue < 0.0) hue+=1.0; if (hue > 1.0) hue-=1.0; if ((6.0*hue) < 1.0) return(m1+6.0*(m2-m1)*hue); if ((2.0*hue) < 1.0) return(m2); if ((3.0*hue) < 2.0) return(m1+6.0*(m2-m1)*(2.0/3.0-hue)); return(m1); } MagickExport void HSLTransform(const double hue,const double saturation, const double lightness,Quantum *red,Quantum *green,Quantum *blue) { MagickRealType b, g, r, m1, m2; /* Convert HSL to RGB colorspace. */ assert(red != (Quantum *) NULL); assert(green != (Quantum *) NULL); assert(blue != (Quantum *) NULL); if (lightness <= 0.5) m2=lightness*(saturation+1.0); else m2=lightness+saturation-lightness*saturation; m1=2.0*lightness-m2; r=HueToRGB(m1,m2,hue+1.0/3.0); g=HueToRGB(m1,m2,hue); b=HueToRGB(m1,m2,hue-1.0/3.0); *red=ClampToQuantum((MagickRealType) QuantumRange*r); *green=ClampToQuantum((MagickRealType) QuantumRange*g); *blue=ClampToQuantum((MagickRealType) QuantumRange*b); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I d e n t i t y A f f i n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IdentityAffine() initializes the affine transform to the identity matrix. % % The format of the IdentityAffine method is: % % IdentityAffine(AffineMatrix *affine) % % A description of each parameter follows: % % o affine: A pointer the affine transform of type AffineMatrix. % */ MagickExport void IdentityAffine(AffineMatrix *affine) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); assert(affine != (AffineMatrix *) NULL); (void) ResetMagickMemory(affine,0,sizeof(AffineMatrix)); affine->sx=1.0; affine->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n i t i a l i z e M a g i c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeMagick() initializes the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreGenesis(path,MagickFalse); % % The format of the InitializeMagick function is: % % InitializeMagick(const char *path) % % A description of each parameter follows: % % o path: the execution path of the current ImageMagick client. % */ MagickExport void InitializeMagick(const char *path) { MagickCoreGenesis(path,MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t e P i x e l C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolatePixelColor() applies bi-linear or tri-linear interpolation % between a pixel and it's neighbors. % % The format of the InterpolatePixelColor method is: % % MagickPixelPacket InterpolatePixelColor(const Image *image, % CacheView *view_info,InterpolatePixelMethod method,const double x, % const double y,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o image_view: the image cache view. % % o type: the type of pixel color interpolation. % % o x,y: A double representing the current (x,y) position of the pixel. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static void BicubicInterpolate(const MagickPixelPacket *pixels,const double dx, MagickPixelPacket *pixel) { MagickRealType dx2, p, q, r, s; dx2=dx*dx; p=(pixels[3].red-pixels[2].red)-(pixels[0].red-pixels[1].red); q=(pixels[0].red-pixels[1].red)-p; r=pixels[2].red-pixels[0].red; s=pixels[1].red; pixel->red=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].green-pixels[2].green)-(pixels[0].green-pixels[1].green); q=(pixels[0].green-pixels[1].green)-p; r=pixels[2].green-pixels[0].green; s=pixels[1].green; pixel->green=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].blue-pixels[2].blue)-(pixels[0].blue-pixels[1].blue); q=(pixels[0].blue-pixels[1].blue)-p; r=pixels[2].blue-pixels[0].blue; s=pixels[1].blue; pixel->blue=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].opacity-pixels[2].opacity)-(pixels[0].opacity-pixels[1].opacity); q=(pixels[0].opacity-pixels[1].opacity)-p; r=pixels[2].opacity-pixels[0].opacity; s=pixels[1].opacity; pixel->opacity=(dx*dx2*p)+(dx2*q)+(dx*r)+s; if (pixel->colorspace == CMYKColorspace) { p=(pixels[3].index-pixels[2].index)-(pixels[0].index-pixels[1].index); q=(pixels[0].index-pixels[1].index)-p; r=pixels[2].index-pixels[0].index; s=pixels[1].index; pixel->index=(dx*dx2*p)+(dx2*q)+(dx*r)+s; } } static inline MagickRealType CubicWeightingFunction(const MagickRealType x) { MagickRealType alpha, gamma; alpha=MagickMax(x+2.0,0.0); gamma=1.0*alpha*alpha*alpha; alpha=MagickMax(x+1.0,0.0); gamma-=4.0*alpha*alpha*alpha; alpha=MagickMax(x+0.0,0.0); gamma+=6.0*alpha*alpha*alpha; alpha=MagickMax(x-1.0,0.0); gamma-=4.0*alpha*alpha*alpha; return(gamma/6.0); } static inline double MeshInterpolate(const PointInfo *delta,const double p, const double x,const double y) { return(delta->x*x+delta->y*y+(1.0-delta->x-delta->y)*p); } static inline ssize_t NearestNeighbor(MagickRealType x) { if (x >= 0.0) return((ssize_t) (x+0.5)); return((ssize_t) (x-0.5)); } MagickExport MagickPixelPacket InterpolatePixelColor(const Image *image, CacheView *image_view,const InterpolatePixelMethod method,const double x, const double y,ExceptionInfo *exception) { MagickPixelPacket pixel; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image_view != (CacheView *) NULL); GetMagickPixelPacket(image,&pixel); switch (method) { case AverageInterpolatePixel: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16]; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 16L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } gamma=alpha[i]; gamma=PerceptibleReciprocal(gamma); pixel.red+=gamma*0.0625*pixels[i].red; pixel.green+=gamma*0.0625*pixels[i].green; pixel.blue+=gamma*0.0625*pixels[i].blue; pixel.opacity+=0.0625*pixels[i].opacity; if (image->colorspace == CMYKColorspace) pixel.index+=gamma*0.0625*pixels[i].index; p++; } break; } case BicubicInterpolatePixel: { MagickPixelPacket pixels[16], u[4]; MagickRealType alpha[16]; PointInfo delta; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 16L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); for (i=0; i < 4L; i++) BicubicInterpolate(pixels+4*i,delta.x,u+i); delta.y=y-floor(y); BicubicInterpolate(u,delta.y,&pixel); break; } case BilinearInterpolatePixel: default: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16]; PointInfo delta; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),2,2,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 4L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); delta.y=y-floor(y); gamma=(((1.0-delta.y)*((1.0-delta.x)*alpha[0]+delta.x*alpha[1])+delta.y* ((1.0-delta.x)*alpha[2]+delta.x*alpha[3]))); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].red+delta.x* pixels[1].red)+delta.y*((1.0-delta.x)*pixels[2].red+delta.x* pixels[3].red)); pixel.green=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].green+delta.x* pixels[1].green)+delta.y*((1.0-delta.x)*pixels[2].green+ delta.x*pixels[3].green)); pixel.blue=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].blue+delta.x* pixels[1].blue)+delta.y*((1.0-delta.x)*pixels[2].blue+delta.x* pixels[3].blue)); pixel.opacity=((1.0-delta.y)*((1.0-delta.x)*pixels[0].opacity+delta.x* pixels[1].opacity)+delta.y*((1.0-delta.x)*pixels[2].opacity+delta.x* pixels[3].opacity)); if (image->colorspace == CMYKColorspace) pixel.index=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].index+delta.x* pixels[1].index)+delta.y*((1.0-delta.x)*pixels[2].index+delta.x* pixels[3].index)); break; } case FilterInterpolatePixel: { Image *excerpt_image, *filter_image; MagickPixelPacket pixels[1]; RectangleInfo geometry; geometry.width=4L; geometry.height=4L; geometry.x=(ssize_t) floor(x)-1L; geometry.y=(ssize_t) floor(y)-1L; excerpt_image=ExcerptImage(image,&geometry,exception); if (excerpt_image == (Image *) NULL) break; filter_image=ResizeImage(excerpt_image,1,1,image->filter,image->blur, exception); excerpt_image=DestroyImage(excerpt_image); if (filter_image == (Image *) NULL) break; p=GetVirtualPixels(filter_image,0,0,1,1,exception); if (p == (const PixelPacket *) NULL) { filter_image=DestroyImage(filter_image); break; } indexes=GetVirtualIndexQueue(filter_image); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); filter_image=DestroyImage(filter_image); break; } case IntegerInterpolatePixel: { MagickPixelPacket pixels[1]; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),1,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); break; } case MeshInterpolatePixel: { double gamma; MagickPixelPacket pixels[4]; MagickRealType alpha[4]; PointInfo delta, luminance; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),2,2,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 4L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); delta.y=y-floor(y); luminance.x=MagickPixelLuminance(pixels+0)-MagickPixelLuminance(pixels+3); luminance.y=MagickPixelLuminance(pixels+1)-MagickPixelLuminance(pixels+2); if (fabs(luminance.x) < fabs(luminance.y)) { /* Diagonal 0-3 NW-SE. */ if (delta.x <= delta.y) { /* Bottom-left triangle (pixel:2, diagonal: 0-3). */ delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[2].red, pixels[3].red,pixels[0].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[2].green, pixels[3].green,pixels[0].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[2].blue, pixels[3].blue,pixels[0].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[2].opacity, pixels[3].opacity,pixels[0].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[2].index, pixels[3].index,pixels[0].index); } else { /* Top-right triangle (pixel:1, diagonal: 0-3). */ delta.x=1.0-delta.x; gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[1].red, pixels[0].red,pixels[3].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[1].green, pixels[0].green,pixels[3].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[1].blue, pixels[0].blue,pixels[3].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[1].opacity, pixels[0].opacity,pixels[3].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[1].index, pixels[0].index,pixels[3].index); } } else { /* Diagonal 1-2 NE-SW. */ if (delta.x <= (1.0-delta.y)) { /* Top-left triangle (pixel 0, diagonal: 1-2). */ gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[0].red, pixels[1].red,pixels[2].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[0].green, pixels[1].green,pixels[2].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[0].blue, pixels[1].blue,pixels[2].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[0].opacity, pixels[1].opacity,pixels[2].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[0].index, pixels[1].index,pixels[2].index); } else { /* Bottom-right triangle (pixel: 3, diagonal: 1-2). */ delta.x=1.0-delta.x; delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[3].red, pixels[2].red,pixels[1].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[3].green, pixels[2].green,pixels[1].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[3].blue, pixels[2].blue,pixels[1].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[3].opacity, pixels[2].opacity,pixels[1].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[3].index, pixels[2].index,pixels[1].index); } } break; } case NearestNeighborInterpolatePixel: { MagickPixelPacket pixels[1]; p=GetCacheViewVirtualPixels(image_view,NearestNeighbor(x), NearestNeighbor(y),1,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); break; } case SplineInterpolatePixel: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16], dx, dy; PointInfo delta; ssize_t j, n; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); n=0; delta.x=x-floor(x); delta.y=y-floor(y); for (i=(-1); i < 3L; i++) { dy=CubicWeightingFunction((MagickRealType) i-delta.y); for (j=(-1); j < 3L; j++) { GetMagickPixelPacket(image,pixels+n); SetMagickPixelPacket(image,p,indexes+n,pixels+n); alpha[n]=1.0; if (image->matte != MagickFalse) { alpha[n]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[n].red*=alpha[n]; pixels[n].green*=alpha[n]; pixels[n].blue*=alpha[n]; if (image->colorspace == CMYKColorspace) pixels[n].index*=alpha[n]; } dx=CubicWeightingFunction(delta.x-(MagickRealType) j); gamma=alpha[n]; gamma=PerceptibleReciprocal(gamma); pixel.red+=gamma*dx*dy*pixels[n].red; pixel.green+=gamma*dx*dy*pixels[n].green; pixel.blue+=gamma*dx*dy*pixels[n].blue; if (image->matte != MagickFalse) pixel.opacity+=dx*dy*pixels[n].opacity; if (image->colorspace == CMYKColorspace) pixel.index+=gamma*dx*dy*pixels[n].index; n++; p++; } } break; } } return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageAttributes() replaces any embedded formatting characters with % the appropriate image attribute and returns the translated text. % % Deprecated, replace with: % % InterpretImageProperties(image_info,image,embed_text); % % The format of the InterpretImageAttributes method is: % % char *InterpretImageAttributes(const ImageInfo *image_info,Image *image, % const char *embed_text) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o embed_text: the address of a character string containing the embedded % formatting characters. % */ MagickExport char *InterpretImageAttributes(const ImageInfo *image_info, Image *image,const char *embed_text) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); return(InterpretImageProperties(image_info,image,embed_text)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e s R G B C o m p a n d o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InversesRGBCompandor() removes the gamma function from a sRGB pixel. % % The format of the InversesRGBCompandor method is: % % MagickRealType InversesRGBCompandor(const MagickRealType pixel) % % A description of each parameter follows: % % o pixel: the pixel. % */ MagickExport MagickRealType InversesRGBCompandor(const MagickRealType pixel) { if (pixel <= (0.0404482362771076*QuantumRange)) return(pixel/12.92); return(QuantumRange*pow((QuantumScale*pixel+0.055)/1.055,2.4)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s S u b i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSubimage() returns MagickTrue if the geometry is a valid subimage % specification (e.g. [1], [1-9], [1,7,4]). % % The format of the IsSubimage method is: % % unsigned int IsSubimage(const char *geometry,const unsigned int pedantic) % % A description of each parameter follows: % % o geometry: This string is the geometry specification. % % o pedantic: A value other than 0 invokes a more restrictive set of % conditions for a valid specification (e.g. [1], [1-4], [4-1]). % */ MagickExport unsigned int IsSubimage(const char *geometry, const unsigned int pedantic) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (geometry == (const char *) NULL) return(MagickFalse); if ((strchr(geometry,'x') != (char *) NULL) || (strchr(geometry,'X') != (char *) NULL)) return(MagickFalse); if ((pedantic != MagickFalse) && (strchr(geometry,',') != (char *) NULL)) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColor() will map the given color to "black" and "white" % values, limearly spreading out the colors, and level values on a channel by % channel bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % Deprecated, replace with: % % LevelColorsImageChannel(image,channel,black_color,white_color,invert); % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image,const ChannelType channel, % const MagickPixelPacket *black_color,const MagickPixelPacket *white_color, % const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % */ MagickBooleanType LevelImageColors(Image *image,const ChannelType channel, const MagickPixelPacket *black_color,const MagickPixelPacket *white_color, const MagickBooleanType invert) { return(LevelColorsImageChannel(image,channel,black_color,white_color,invert)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i b e r a t e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiberateMemory() frees memory that has already been allocated, and NULL's % the pointer to it. % % The format of the LiberateMemory method is: % % void LiberateMemory(void **memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void LiberateMemory(void **memory) { assert(memory != (void **) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*memory == (void *) NULL) return; free(*memory); *memory=(void *) NULL; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i b e r a t e S e m a p h o r e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiberateSemaphoreInfo() relinquishes a semaphore. % % Deprecated, replace with: % % UnlockSemaphoreInfo(*semaphore_info); % % The format of the LiberateSemaphoreInfo method is: % % LiberateSemaphoreInfo(void **semaphore_info) % % A description of each parameter follows: % % o semaphore_info: Specifies a pointer to an SemaphoreInfo structure. % */ MagickExport void LiberateSemaphoreInfo(SemaphoreInfo **semaphore_info) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); UnlockSemaphoreInfo(*semaphore_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k I n c a r n a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickIncarnate() initializes the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreGenesis(path,MagickFalse); % % The format of the MagickIncarnate function is: % % MagickIncarnate(const char *path) % % A description of each parameter follows: % % o path: the execution path of the current ImageMagick client. % */ MagickExport void MagickIncarnate(const char *path) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); MagickCoreGenesis(path,MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M o n i t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMonitor() calls the monitor handler method with a text string that % describes the task and a measure of completion. The method returns % MagickTrue on success otherwise MagickFalse if an error is encountered, e.g. % if there was a user interrupt. % % The format of the MagickMonitor method is: % % MagickBooleanType MagickMonitor(const char *text, % const MagickOffsetType offset,const MagickSizeType span, % void *client_data) % % A description of each parameter follows: % % o offset: the position relative to the span parameter which represents % how much progress has been made toward completing a task. % % o span: the span relative to completing a task. % % o client_data: the client data. % */ MagickExport MagickBooleanType MagickMonitor(const char *text, const MagickOffsetType offset,const MagickSizeType span, void *magick_unused(client_data)) { ExceptionInfo *exception; MagickBooleanType status; assert(text != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",text); ProcessPendingEvents(text); status=MagickTrue; exception=AcquireExceptionInfo(); if (monitor_handler != (MonitorHandler) NULL) status=(*monitor_handler)(text,offset,span,exception); exception=DestroyExceptionInfo(exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MapImage() replaces the colors of an image with the closest color from a % reference image. % % Deprecated, replace with: % % QuantizeInfo quantize_info; % GetQuantizeInfo(&quantize_info); % quantize_info.dither=dither; % RemapImage(&quantize_info,image,map_image); % % The format of the MapImage method is: % % MagickBooleanType MapImage(Image *image,const Image *map_image, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o map_image: the image. Reduce image to a set of colors represented by % this image. % % o dither: Set this integer value to something other than zero to % dither the mapped image. % */ MagickExport MagickBooleanType MapImage(Image *image,const Image *map_image, const MagickBooleanType dither) { QuantizeInfo quantize_info; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(map_image != (Image *) NULL); assert(map_image->signature == MagickSignature); GetQuantizeInfo(&quantize_info); quantize_info.dither=dither; return(RemapImage(&quantize_info,image,map_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MapImages() replaces the colors of a sequence of images with the closest % color from a reference image. % % Deprecated, replace with: % % QuantizeInfo quantize_info; % GetQuantizeInfo(&quantize_info); % quantize_info.dither=dither; % RemapImages(&quantize_info,images,map_image); % % The format of the MapImage method is: % % MagickBooleanType MapImages(Image *images,Image *map_image, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to a set of Image structures. % % o map_image: the image. Reduce image to a set of colors represented by % this image. % % o dither: Set this integer value to something other than zero to % dither the quantized image. % */ MagickExport MagickBooleanType MapImages(Image *images,const Image *map_image, const MagickBooleanType dither) { QuantizeInfo quantize_info; assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); GetQuantizeInfo(&quantize_info); quantize_info.dither=dither; return(RemapImages(&quantize_info,images,map_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a t t e F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MatteFloodfill() changes the transparency value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod % is specified, the transparency value is changed for any neighbor pixel % that does not match the bordercolor member of image. % % By default target must match a particular pixel transparency exactly. % However, in many cases two transparency values may differ by a % small amount. The fuzz member of image defines how much tolerance is % acceptable to consider two transparency values as the same. For example, % set fuzz to 10 and the opacity values of 100 and 102 respectively are % now interpreted as the same value for the purposes of the floodfill. % % The format of the MatteFloodfillImage method is: % % MagickBooleanType MatteFloodfillImage(Image *image, % const PixelPacket target,const Quantum opacity,const ssize_t x_offset, % const ssize_t y_offset,const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the level of transparency: 0 is fully opaque and QuantumRange is % fully transparent. % % o x,y: the starting location of the operation. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ MagickExport MagickBooleanType MatteFloodfillImage(Image *image, const PixelPacket target,const Quantum opacity,const ssize_t x_offset, const ssize_t y_offset,const PaintMethod method) { Image *floodplane_image; MagickBooleanType skip; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); /* Set floodfill color. */ segment_stack=(SegmentInfo *) AcquireQuantumMemory(MaxStacksize, sizeof(*segment_stack)); if (segment_stack == (SegmentInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Push initial segment on stack. */ x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); while (s > segment_stack) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetVirtualPixels(image,0,y,(size_t) (x1+1),1,&image->exception); q=GetAuthenticPixels(floodplane_image,0,y,(size_t) (x1+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; q--; p--; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetVirtualPixels(image,x,y,image->columns-x,1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,image->columns-x,1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; q++; p++; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetVirtualPixels(image,x,y,(size_t) (x2-x+1),1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,(size_t) (x2-x+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) != MagickFalse) break; } else if (IsColorSimilar(image,p,&target) == MagickFalse) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Tile fill color onto floodplane. */ p=GetVirtualPixels(floodplane_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) q->opacity=opacity; p++; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } segment_stack=(SegmentInfo *) RelinquishMagickMemory(segment_stack); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a x i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaximumImages() returns the maximum intensity of an image sequence. % % Deprecated, replace with: % % EvaluateImages(images,MinEvaluateOperator,exception); % % The format of the MaxImages method is: % % Image *MaximumImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MaximumImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MinEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinimumImages() returns the minimum intensity of an image sequence. % % Deprecated, replace with: % % EvaluateImages(images,MinEvaluateOperator,exception); % % The format of the MinimumImages method is: % % Image *MinimumImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MinimumImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MinEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e d i a n F i l t e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MedianFilterImage() applies a digital filter that improves the quality % of a noisy image. Each pixel is replaced by the median in a set of % neighboring pixels as defined by radius. % % The algorithm was contributed by Mike Edmonds and implements an insertion % sort for selecting median color-channel values. For more on this algorithm % see "Skip Lists: A probabilistic Alternative to Balanced Trees" by William % Pugh in the June 1990 of Communications of the ACM. % % The format of the MedianFilterImage method is: % % Image *MedianFilterImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MedianFilterImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *median_image; median_image=StatisticImage(image,MedianStatistic,(size_t) radius,(size_t) radius,exception); return(median_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModeImage() makes each pixel the 'predominant color' of the neighborhood % of the specified radius. % % The format of the ModeImage method is: % % Image *ModeImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ModeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *mode_image; mode_image=StatisticImage(image,ModeStatistic,(size_t) radius,(size_t) radius, exception); return(mode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o s a i c I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MosaicImages() Obsolete Function: Use MergeImageLayers() instead. % % Deprecated, replace with: % % MergeImageLayers(image,MosaicLayer,exception); % % The format of the MosaicImage method is: % % Image *MosaicImages(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MosaicImages(Image *image,ExceptionInfo *exception) { return(MergeImageLayers(image,MosaicLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaqueImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the OpaqueImage method is: % % MagickBooleanType OpaqueImage(Image *image, % const PixelPacket *target,const PixelPacket fill) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o fill: the replacement color. % */ MagickExport MagickBooleanType OpaqueImage(Image *image, const PixelPacket target,const PixelPacket fill) { #define OpaqueImageTag "Opaque/Image" MagickBooleanType proceed; register ssize_t i; ssize_t y; /* Make image color opaque. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.1.0"); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (image->storage_class) { case DirectClass: default: { /* Make DirectClass image opaque. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) *q=fill; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; proceed=SetImageProgress(image,OpaqueImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } break; } case PseudoClass: { /* Make PseudoClass image opaque. */ for (i=0; i < (ssize_t) image->colors; i++) { if (IsColorSimilar(image,&image->colormap[i],&target) != MagickFalse) image->colormap[i]=fill; } if (fill.opacity != OpaqueOpacity) { for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) q->opacity=fill.opacity; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } } (void) SyncImage(image); break; } } if (fill.opacity != OpaqueOpacity) image->matte=MagickTrue; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p e n C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenCacheView() opens a view into the pixel cache, using the % VirtualPixelMethod that is defined within the given image itself. % % Deprecated, replace with: % % AcquireVirtualCacheView(image,&image->exception); % % The format of the OpenCacheView method is: % % CacheView *OpenCacheView(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheView *OpenCacheView(const Image *image) { return(AcquireVirtualCacheView(image,&((Image *) image)->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p e n M a g i c k S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenMagickStream() opens the file at the specified path and return the % associated stream. % % The path of the OpenMagickStream method is: % % FILE *OpenMagickStream(const char *path,const char *mode) % % A description of each parameter follows. % % o path: the file path. % % o mode: the file mode. % */ #if defined(MAGICKCORE_HAVE__WFOPEN) static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16) { register const unsigned char *p; if (utf16 != (wchar_t *) NULL) { register wchar_t *q; wchar_t c; /* Convert UTF-8 to UTF-16. */ q=utf16; for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) *q=(*p); else if ((*p & 0xE0) == 0xC0) { c=(*p); *q=(c & 0x1F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else if ((*p & 0xF0) == 0xE0) { c=(*p); *q=c << 12; p++; if ((*p & 0xC0) != 0x80) return(0); c=(*p); *q|=(c & 0x3F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else return(0); q++; } *q++='\0'; return(q-utf16); } /* Compute UTF-16 string length. */ for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) ; else if ((*p & 0xE0) == 0xC0) { p++; if ((*p & 0xC0) != 0x80) return(0); } else if ((*p & 0xF0) == 0xE0) { p++; if ((*p & 0xC0) != 0x80) return(0); p++; if ((*p & 0xC0) != 0x80) return(0); } else return(0); } return(p-utf8); } static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source) { size_t length; wchar_t *utf16; length=UTF8ToUTF16(source,(wchar_t *) NULL); if (length == 0) { register ssize_t i; /* Not UTF-8, just copy. */ length=strlen((const char *) source); utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); for (i=0; i <= (ssize_t) length; i++) utf16[i]=source[i]; return(utf16); } utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); length=UTF8ToUTF16(source,utf16); return(utf16); } #endif MagickExport FILE *OpenMagickStream(const char *path,const char *mode) { FILE *file; if ((path == (const char *) NULL) || (mode == (const char *) NULL)) { errno=EINVAL; return((FILE *) NULL); } file=(FILE *) NULL; #if defined(MAGICKCORE_HAVE__WFOPEN) { wchar_t *unicode_mode, *unicode_path; unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path); if (unicode_path == (wchar_t *) NULL) return((FILE *) NULL); unicode_mode=ConvertUTF8ToUTF16((const unsigned char *) mode); if (unicode_mode == (wchar_t *) NULL) { unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path); return((FILE *) NULL); } file=_wfopen(unicode_path,unicode_mode); unicode_mode=(wchar_t *) RelinquishMagickMemory(unicode_mode); unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path); } #endif if (file == (FILE *) NULL) file=fopen(path,mode); return(file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a i n t F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintFloodfill() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % Deprecated, replace with: % % FloodfillPaintImage(image,channel,draw_info,target,x,y, % method == FloodfillMethod ? MagickFalse : MagickTrue); % % The format of the PaintFloodfillImage method is: % % MagickBooleanType PaintFloodfillImage(Image *image, % const ChannelType channel,const MagickPixelPacket target, % const ssize_t x,const ssize_t y,const DrawInfo *draw_info, % const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o x,y: the starting location of the operation. % % o draw_info: the draw info. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ MagickExport MagickBooleanType PaintFloodfillImage(Image *image, const ChannelType channel,const MagickPixelPacket *target,const ssize_t x, const ssize_t y,const DrawInfo *draw_info,const PaintMethod method) { MagickBooleanType status; status=FloodfillPaintImage(image,channel,draw_info,target,x,y, method == FloodfillMethod ? MagickFalse : MagickTrue); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % P a i n t O p a q u e I m a g e % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintOpaqueImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % Deprecated, replace with: % % OpaquePaintImageChannel(image,DefaultChannels,target,fill,MagickFalse); % OpaquePaintImageChannel(image,channel,target,fill,MagickFalse); % % The format of the PaintOpaqueImage method is: % % MagickBooleanType PaintOpaqueImage(Image *image, % const PixelPacket *target,const PixelPacket *fill) % MagickBooleanType PaintOpaqueImageChannel(Image *image, % const ChannelType channel,const PixelPacket *target, % const PixelPacket *fill) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o fill: the replacement color. % */ MagickExport MagickBooleanType PaintOpaqueImage(Image *image, const MagickPixelPacket *target,const MagickPixelPacket *fill) { MagickBooleanType status; status=OpaquePaintImageChannel(image,DefaultChannels,target,fill,MagickFalse); return(status); } MagickExport MagickBooleanType PaintOpaqueImageChannel(Image *image, const ChannelType channel,const MagickPixelPacket *target, const MagickPixelPacket *fill) { return(OpaquePaintImageChannel(image,channel,target,fill,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a i n t T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintTransparentImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % Deprecated, replace with: % % TransparentPaintImage(image,target,opacity,MagickFalse); % % The format of the PaintTransparentImage method is: % % MagickBooleanType PaintTransparentImage(Image *image, % const MagickPixelPacket *target,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the replacement opacity value. % */ MagickExport MagickBooleanType PaintTransparentImage(Image *image, const MagickPixelPacket *target,const Quantum opacity) { return(TransparentPaintImage(image,target,opacity,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P a r s e I m a g e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ParseImageGeometry() is similar to GetGeometry() except the returned % geometry is modified as determined by the meta characters: %, !, <, % and >. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,x,y,width,height); % % The format of the ParseImageGeometry method is: % % int ParseImageGeometry(char *geometry,ssize_t *x,ssize_t *y, % size_t *width,size_t *height) % % A description of each parameter follows: % % o flags: Method ParseImageGeometry returns a bitmask that indicates % which of the four values were located in the geometry string. % % o image_geometry: Specifies a character string representing the geometry % specification. % % o x,y: A pointer to an integer. The x and y offset as determined by % the geometry specification is returned here. % % o width,height: A pointer to an unsigned integer. The width and height % as determined by the geometry specification is returned here. % */ MagickExport int ParseImageGeometry(const char *geometry,ssize_t *x,ssize_t *y, size_t *width,size_t *height) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); return((int) ParseMetaGeometry(geometry,x,y,width,height)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a r s e S i z e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ParseSizeGeometry() returns a region as defined by the geometry string with % respect to the image dimensions and aspect ratio. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,&region_info->x,&region_info->y, % &region_info->width,&region_info->height); % % The format of the ParseSizeGeometry method is: % % MagickStatusType ParseSizeGeometry(const Image *image, % const char *geometry,RectangeInfo *region_info) % % A description of each parameter follows: % % o geometry: The geometry (e.g. 100x100+10+10). % % o region_info: the region as defined by the geometry string. % */ MagickExport MagickStatusType ParseSizeGeometry(const Image *image, const char *geometry,RectangleInfo *region_info) { MagickStatusType flags; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.4.7"); SetGeometry(image,region_info); flags=ParseMetaGeometry(geometry,&region_info->x,&region_info->y, &region_info->width,&region_info->height); return(flags); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o p I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PopImageList() removes the last image in the list. % % Deprecated, replace with: % % RemoveLastImageFromList(images); % % The format of the PopImageList method is: % % Image *PopImageList(Image **images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *PopImageList(Image **images) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(RemoveLastImageFromList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o p I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PopImagePixels() transfers one or more pixel components from the image pixel % cache to a user supplied buffer. The pixels are returned in network byte % order. MagickTrue is returned if the pixels are successfully transferred, % otherwise MagickFalse. % % The format of the PopImagePixels method is: % % size_t PopImagePixels(Image *,const QuantumType quantum, % unsigned char *destination) % % A description of each parameter follows: % % o image: the image. % % o quantum: Declare which pixel components to transfer (RGB, RGBA, etc). % % o destination: The components are transferred to this buffer. % */ MagickExport size_t PopImagePixels(Image *image,const QuantumType quantum, unsigned char *destination) { QuantumInfo *quantum_info; size_t length; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) return(0); length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, quantum,destination,&image->exception); quantum_info=DestroyQuantumInfo(quantum_info); return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t s c r i p t G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PostscriptGeometry() replaces any page mneumonic with the equivalent size in % picas. % % Deprecated, replace with: % % GetPageGeometry(page); % % The format of the PostscriptGeometry method is: % % char *PostscriptGeometry(const char *page) % % A description of each parameter follows. % % o page: Specifies a pointer to an array of characters. % The string is either a Postscript page name (e.g. A4) or a postscript % page geometry (e.g. 612x792+36+36). % */ MagickExport char *PostscriptGeometry(const char *page) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); return(GetPageGeometry(page)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P u s h I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PushImageList() adds an image to the end of the list. % % Deprecated, replace with: % % AppendImageToList(images,CloneImageList(image,exception)); % % The format of the PushImageList method is: % % unsigned int PushImageList(Image *images,const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int PushImageList(Image **images,const Image *image, ExceptionInfo *exception) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); AppendImageToList(images,CloneImageList(image,exception)); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P u s h I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PushImagePixels() transfers one or more pixel components from a user % supplied buffer into the image pixel cache of an image. The pixels are % expected in network byte order. It returns MagickTrue if the pixels are % successfully transferred, otherwise MagickFalse. % % The format of the PushImagePixels method is: % % size_t PushImagePixels(Image *image,const QuantumType quantum, % const unsigned char *source) % % A description of each parameter follows: % % o image: the image. % % o quantum: Declare which pixel components to transfer (red, green, blue, % opacity, RGB, or RGBA). % % o source: The pixel components are transferred from this buffer. % */ MagickExport size_t PushImagePixels(Image *image,const QuantumType quantum, const unsigned char *source) { QuantumInfo *quantum_info; size_t length; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) return(0); length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,quantum, source,&image->exception); quantum_info=DestroyQuantumInfo(quantum_info); return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z a t i o n E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizationError() measures the difference between the original and % quantized images. This difference is the total quantization error. The % error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % Deprecated, replace with: % % GetImageQuantizeError(image); % % The format of the QuantizationError method is: % % unsigned int QuantizationError(Image *image) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % */ MagickExport unsigned int QuantizationError(Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.3"); return(GetImageQuantizeError(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % R a n d o m C h a n n e l T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomChannelThresholdImage() changes the value of individual pixels based % on the intensity of each pixel compared to a random threshold. The result % is a low-contrast, two color image. % % The format of the RandomChannelThresholdImage method is: % % unsigned int RandomChannelThresholdImage(Image *image, % const char *channel, const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing LOWxHIGH thresholds. % If the string contains 2x2, 3x3, or 4x4, then an ordered % dither of order 2, 3, or 4 will be performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int RandomChannelThresholdImage(Image *image,const char *channel,const char *thresholds,ExceptionInfo *exception) { #define RandomChannelThresholdImageText " RandomChannelThreshold image... " double lower_threshold, upper_threshold; RandomInfo *random_info; ssize_t count, y; static MagickRealType o2[4]={0.2f, 0.6f, 0.8f, 0.4f}, o3[9]={0.1f, 0.6f, 0.3f, 0.7f, 0.5f, 0.8f, 0.4f, 0.9f, 0.2f}, o4[16]={0.1f, 0.7f, 1.1f, 0.3f, 1.0f, 0.5f, 1.5f, 0.8f, 1.4f, 1.6f, 0.6f, 1.2f, 0.4f, 0.9f, 1.3f, 0.2f}, threshold=128; size_t order; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (thresholds == (const char *) NULL) return(MagickTrue); if (LocaleCompare(thresholds,"2x2") == 0) order=2; else if (LocaleCompare(thresholds,"3x3") == 0) order=3; else if (LocaleCompare(thresholds,"4x4") == 0) order=4; else { order=1; lower_threshold=0; upper_threshold=0; count=(ssize_t) sscanf(thresholds,"%lf[/x%%]%lf",&lower_threshold, &upper_threshold); if (strchr(thresholds,'%') != (char *) NULL) { upper_threshold*=(.01*QuantumRange); lower_threshold*=(.01*QuantumRange); } if (count == 1) upper_threshold=(MagickRealType) QuantumRange-lower_threshold; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " RandomChannelThresholdImage: channel type=%s",channel); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Thresholds: %s (%fx%f)",thresholds,lower_threshold,upper_threshold); if (LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"intensity") == 0) if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfo(); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register IndexPacket index, *restrict indexes; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"intensity") == 0) { indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=(MagickRealType) PixelIntensityToQuantum(image,q); if (order == 1) { if (intensity < lower_threshold) threshold=lower_threshold; else if (intensity > upper_threshold) threshold=upper_threshold; else threshold=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info)); } else if (order == 2) threshold=(MagickRealType) QuantumRange*o2[(x%2)+2*(y%2)]; else if (order == 3) threshold=(MagickRealType) QuantumRange*o3[(x%3)+3*(y%3)]; else if (order == 4) threshold=(MagickRealType) QuantumRange*o4[(x%4)+4*(y%4)]; index=(IndexPacket) (intensity <= threshold ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } if (LocaleCompare(channel,"opacity") == 0 || LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"matte") == 0) { if (image->matte != MagickFalse) for (x=0; x < (ssize_t) image->columns; x++) { if (order == 1) { if ((MagickRealType) q->opacity < lower_threshold) threshold=lower_threshold; else if ((MagickRealType) q->opacity > upper_threshold) threshold=upper_threshold; else threshold=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info)); } else if (order == 2) threshold=(MagickRealType) QuantumRange*o2[(x%2)+2*(y%2)]; else if (order == 3) threshold=(MagickRealType) QuantumRange*o3[(x%3)+3*(y%3)]; else if (order == 4) threshold=(MagickRealType) QuantumRange*o4[(x%4)+4*(y%4)]/1.7; SetPixelOpacity(q,(MagickRealType) q->opacity <= threshold ? 0 : QuantumRange); q++; } } else { /* To Do: red, green, blue, cyan, magenta, yellow, black */ if (LocaleCompare(channel,"intensity") != 0) ThrowBinaryException(OptionError,"UnrecognizedChannelType", image->filename); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } random_info=DestroyRandomInfo(random_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a c q u i r e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReacquireMemory() changes the size of the memory and returns a pointer to % the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ReacquireMemory method is: % % void ReacquireMemory(void **memory,const size_t size) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. On return the pointer % may change but the contents of the original allocation will not. % % o size: the new size of the allocated memory. % */ MagickExport void ReacquireMemory(void **memory,const size_t size) { void *allocation; assert(memory != (void **) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*memory == (void *) NULL) { *memory=AcquireMagickMemory(size); return; } allocation=realloc(*memory,size); if (allocation == (void *) NULL) *memory=RelinquishMagickMemory(*memory); *memory=allocation; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e c o l o r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RecolorImage() apply color transformation to an image. The method permits % saturation changes, hue rotation, luminance to alpha, and various other % effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the RecolorImage method is: % % Image *RecolorImage(const Image *image,const size_t order, % const double *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o order: the number of columns and rows in the recolor matrix. % % o color_matrix: An array of double representing the recolor matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RecolorImage(const Image *image,const size_t order, const double *color_matrix,ExceptionInfo *exception) { KernelInfo *kernel_info; Image *recolor_image; kernel_info=AcquireKernelInfo("1"); if (kernel_info == (KernelInfo *) NULL) return((Image *) NULL); kernel_info->width=order; kernel_info->height=order; kernel_info->values=(double *) color_matrix; recolor_image=ColorMatrixImage(image,kernel_info,exception); kernel_info->values=(double *) NULL; kernel_info=DestroyKernelInfo(kernel_info); return(recolor_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e d u c e N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceNoiseImage() smooths the contours of an image while still preserving % edge information. The algorithm works by replacing each pixel with its % neighbor closest in value. A neighbor is defined by radius. Use a radius % of 0 and ReduceNoise() selects a suitable radius for you. % % The format of the ReduceNoiseImage method is: % % Image *ReduceNoiseImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReduceNoiseImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *reduce_image; reduce_image=StatisticImage(image,NonpeakStatistic,(size_t) radius,(size_t) radius,exception); return(reduce_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e A t t r i b u t e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageAttributeIterator() resets the image attributes iterator. Use it % in conjunction with GetNextImageAttribute() to iterate over all the values % associated with an image. % % Deprecated, replace with: % % ResetImagePropertyIterator(image); % % The format of the ResetImageAttributeIterator method is: % % ResetImageAttributeIterator(const ImageInfo *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageAttributeIterator(const Image *image) { ResetImagePropertyIterator(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetCacheViewPixels() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % QueueCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the SetCacheViewPixels method is: % % PixelPacket *SetCacheViewPixels(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *SetCacheViewPixels(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=QueueCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t C a c h e T h e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetCacheThreshold() sets the amount of free memory allocated for the pixel % cache. Once this threshold is exceeded, all subsequent pixels cache % operations are to/from disk. % % The format of the SetCacheThreshold() method is: % % void SetCacheThreshold(const size_t threshold) % % A description of each parameter follows: % % o threshold: the number of megabytes of memory available to the pixel % cache. % */ MagickExport void SetCacheThreshold(const size_t size) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); (void) SetMagickResourceLimit(MemoryResource,size*1024*1024); (void) SetMagickResourceLimit(MapResource,2*size*1024*1024); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t E x c e p t i o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetExceptionInfo() sets the exception severity. % % The format of the SetExceptionInfo method is: % % MagickBooleanType SetExceptionInfo(ExceptionInfo *exception, % ExceptionType severity) % % A description of each parameter follows: % % o exception: the exception info. % % o severity: the exception severity. % */ MagickExport MagickBooleanType SetExceptionInfo(ExceptionInfo *exception, ExceptionType severity) { assert(exception != (ExceptionInfo *) NULL); ClearMagickException(exception); exception->severity=severity; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImage() sets the red, green, and blue components of each pixel to % the image background color and the opacity component to the specified % level of transparency. The background color is defined by the % background_color member of the image. % % The format of the SetImage method is: % % void SetImage(Image *image,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o opacity: Set each pixel to this level of transparency. % */ MagickExport void SetImage(Image *image,const Quantum opacity) { PixelPacket background_color; ssize_t y; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.0"); assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); background_color=image->background_color; if (opacity != OpaqueOpacity) background_color.opacity=opacity; if (background_color.opacity != OpaqueOpacity) { (void) SetImageStorageClass(image,DirectClass); image->matte=MagickTrue; } if ((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) { /* Set colormapped or CMYK image. */ for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRGBO(q,&background_color); q++; } indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,0); if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } return; } /* Set DirectClass image. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRGBO(q,&background_color); q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAttribute() searches the list of image attributes and replaces the % attribute value. If it is not found in the list, the attribute name % and value is added to the list. % % Deprecated, replace with: % % SetImageProperty(image,key,value); % % The format of the SetImageAttribute method is: % % MagickBooleanType SetImageAttribute(Image *image,const char *key, % const char *value) % % A description of each parameter follows: % % o image: the image. % % o key: the key. % % o value: the value. % */ MagickExport MagickBooleanType SetImageAttribute(Image *image,const char *key, const char *value) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); return(SetImageProperty(image,key,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageList() inserts an image into the list at the specified position. % % The format of the SetImageList method is: % % unsigned int SetImageList(Image *images,const Image *image, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o offset: the position within the list. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int SetImageList(Image **images,const Image *image, const ssize_t offset,ExceptionInfo *exception) { Image *clone; register ssize_t i; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); clone=CloneImageList(image,exception); while (GetPreviousImageInList(*images) != (Image *) NULL) (*images)=GetPreviousImageInList(*images); for (i=0; i < offset; i++) { if (GetNextImageInList(*images) == (Image *) NULL) return(MagickFalse); (*images)=GetNextImageInList(*images); } InsertImageInList(images,clone); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImagePixels() queues a mutable pixel region. % If the region is successfully initialized a pointer to a PixelPacket % array representing the region is returned, otherwise NULL is returned. % The returned pointer may point to a temporary working buffer for the % pixels or it may point to the final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This useful while the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % SetImagePixels() any way it pleases. SetImagePixels() does not initialize % the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in RAM, or in a % memory-mapped file. The returned pointer should *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain % the black color component or the colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % Deprecated, replace with: % % QueueAuthenticPixels(image,x,y,columns,rows,&image->exception); % % The format of the SetImagePixels() method is: % % PixelPacket *SetImagePixels(Image *image,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o pixels: SetImagePixels returns a pointer to the pixels if they are % transferred, otherwise a NULL is returned. % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *SetImagePixels(Image *image,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows) { return(QueueAuthenticPixels(image,x,y,columns,rows,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMagickRegistry() sets a blob into the registry and returns a unique ID. % If an error occurs, -1 is returned. % % The format of the SetMagickRegistry method is: % % ssize_t SetMagickRegistry(const RegistryType type,const void *blob, % const size_t length,ExceptionInfo *exception) % % A description of each parameter follows: % % o type: the registry type. % % o blob: the address of a Binary Large OBject. % % o length: For a registry type of ImageRegistryType use sizeof(Image) % otherise the blob length in number of bytes. % % o exception: return any errors or warnings in this structure. % */ MagickExport ssize_t SetMagickRegistry(const RegistryType type,const void *blob, const size_t magick_unused(length),ExceptionInfo *exception) { char key[MaxTextExtent]; MagickBooleanType status; static ssize_t id = 0; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); status=SetImageRegistry(type,key,blob,exception); if (status == MagickFalse) return(-1); return(id++); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M o n i t o r H a n d l e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMonitorHandler() sets the monitor handler to the specified method % and returns the previous monitor handler. % % The format of the SetMonitorHandler method is: % % MonitorHandler SetMonitorHandler(MonitorHandler handler) % % A description of each parameter follows: % % o handler: Specifies a pointer to a method to handle monitors. % */ MagickExport MonitorHandler GetMonitorHandler(void) { return(monitor_handler); } MagickExport MonitorHandler SetMonitorHandler(MonitorHandler handler) { MonitorHandler previous_handler; previous_handler=monitor_handler; monitor_handler=handler; return(previous_handler); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h i f t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShiftImageList() removes an image from the beginning of the list. % % Deprecated, replace with: % % RemoveFirstImageFromList(images); % % The format of the ShiftImageList method is: % % Image *ShiftImageList(Image **images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *ShiftImageList(Image **images) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(RemoveFirstImageFromList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S i z e B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SizeBlob() returns the current length of the image file or blob. % % Deprecated, replace with: % % GetBlobSize(image); % % The format of the SizeBlob method is: % % off_t SizeBlob(Image *image) % % A description of each parameter follows: % % o size: Method SizeBlob returns the current length of the image file % or blob. % % o image: the image. % */ MagickExport MagickOffsetType SizeBlob(Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.3"); return((MagickOffsetType) GetBlobSize(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p l i c e I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpliceImageList() removes the images designated by offset and length from % the list and replaces them with the specified list. % % The format of the SpliceImageList method is: % % Image *SpliceImageList(Image *images,const ssize_t offset, % const size_t length,const Image *splices, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % % o length: the length of the image list to remove. % % o splice: Replace the removed image list with this list. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpliceImageList(Image *images,const ssize_t offset, const size_t length,const Image *splices,ExceptionInfo *exception) { Image *clone; register ssize_t i; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); clone=CloneImageList(splices,exception); while (GetPreviousImageInList(images) != (Image *) NULL) images=GetPreviousImageInList(images); for (i=0; i < offset; i++) { if (GetNextImageInList(images) == (Image *) NULL) return((Image *) NULL); images=GetNextImageInList(images); } (void) SpliceImageIntoList(&images,length,clone); return(images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % s R G B C o m p a n d o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % sRGBCompandor() adds the gamma function to a sRGB pixel. % % The format of the sRGBCompandor method is: % % MagickRealType sRGBCompandor(const MagickRealType pixel) % % A description of each parameter follows: % % o pixel: the pixel. % */ MagickExport MagickRealType sRGBCompandor(const MagickRealType pixel) { if (pixel <= (0.0031306684425005883*QuantumRange)) return(12.92*pixel); return(QuantumRange*(1.055*pow(QuantumScale*pixel,1.0/2.4)-0.055)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Strip() strips any whitespace or quotes from the beginning and end of a % string of characters. % % The format of the Strip method is: % % void Strip(char *message) % % A description of each parameter follows: % % o message: Specifies an array of characters. % */ MagickExport void Strip(char *message) { register char *p, *q; assert(message != (char *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*message == '\0') return; if (strlen(message) == 1) return; p=message; while (isspace((int) ((unsigned char) *p)) != 0) p++; if ((*p == '\'') || (*p == '"')) p++; q=message+strlen(message)-1; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; if (q > p) if ((*q == '\'') || (*q == '"')) q--; (void) CopyMagickMemory(message,p,(size_t) (q-p+1)); message[q-p+1]='\0'; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncCacheView() saves the cache view pixels to the in-memory or disk % cache. It returns MagickTrue if the pixel region is synced, otherwise % MagickFalse. % % Deprecated, replace with: % % SyncCacheViewAuthenticPixels(cache_view,GetCacheViewException(cache_view)); % % The format of the SyncCacheView method is: % % MagickBooleanType SyncCacheView(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport MagickBooleanType SyncCacheView(CacheView *cache_view) { MagickBooleanType status; status=SyncCacheViewAuthenticPixels(cache_view, GetCacheViewException(cache_view)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncCacheViewPixels() saves the cache view pixels to the in-memory % or disk cache. It returns MagickTrue if the pixel region is flushed, % otherwise MagickFalse. % % Deprecated, replace with: % % SyncCacheViewAuthenticPixels(cache_view,GetCacheViewException(cache_view)); % % The format of the SyncCacheViewPixels method is: % % MagickBooleanType SyncCacheViewPixels(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncCacheViewPixels(CacheView *cache_view) { MagickBooleanType status; status=SyncCacheViewAuthenticPixels(cache_view, GetCacheViewException(cache_view)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is synced, otherwise % MagickFalse. % % Deprecated, replace with: % % SyncAuthenticPixels(image,&image->exception); % % The format of the SyncImagePixels() method is: % % MagickBooleanType SyncImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType SyncImagePixels(Image *image) { return(SyncAuthenticPixels(image,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e m p o r a r y F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TemporaryFilename() replaces the contents of path by a unique path name. % % The format of the TemporaryFilename method is: % % void TemporaryFilename(char *path) % % A description of each parameter follows. % % o path: Specifies a pointer to an array of characters. The unique path % name is returned in this array. % */ MagickExport void TemporaryFilename(char *path) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); (void) AcquireUniqueFilename(path); (void) RelinquishUniqueFileResource(path); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThresholdImage() changes the value of individual pixels based on % the intensity of each pixel compared to threshold. The result is a % high-contrast, two color image. % % The format of the ThresholdImage method is: % % unsigned int ThresholdImage(Image *image,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value % */ MagickExport unsigned int ThresholdImage(Image *image,const double threshold) { #define ThresholdImageTag "Threshold/Image" IndexPacket index; ssize_t y; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (!AcquireImageColormap(image,2)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", "UnableToThresholdImage"); for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=(IndexPacket) ((MagickRealType) PixelIntensityToQuantum(image,q) <= threshold ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (!SyncAuthenticPixels(image,&image->exception)) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h r e s h o l d I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThresholdImageChannel() changes the value of individual pixels based on % the intensity of each pixel channel. The result is a high-contrast image. % % The format of the ThresholdImageChannel method is: % % unsigned int ThresholdImageChannel(Image *image,const char *threshold) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % */ MagickExport unsigned int ThresholdImageChannel(Image *image, const char *threshold) { #define ThresholdImageTag "Threshold/Image" MagickPixelPacket pixel; GeometryInfo geometry_info; IndexPacket index; ssize_t y; unsigned int flags; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (threshold == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(threshold,&geometry_info); pixel.red=geometry_info.rho; if (flags & SigmaValue) pixel.green=geometry_info.sigma; else pixel.green=pixel.red; if (flags & XiValue) pixel.blue=geometry_info.xi; else pixel.blue=pixel.red; if (flags & PsiValue) pixel.opacity=geometry_info.psi; else pixel.opacity=(MagickRealType) OpaqueOpacity; if (flags & PercentValue) { pixel.red*=QuantumRange/100.0f; pixel.green*=QuantumRange/100.0f; pixel.blue*=QuantumRange/100.0f; pixel.opacity*=QuantumRange/100.0f; } if (!(flags & SigmaValue)) { if (!AcquireImageColormap(image,2)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", "UnableToThresholdImage"); if (pixel.red == 0) (void) GetImageDynamicThreshold(image,2.0,2.0,&pixel,&image->exception); } for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (IsMagickGray(&pixel) != MagickFalse) for (x=0; x < (ssize_t) image->columns; x++) { index=(IndexPacket) ((MagickRealType) PixelIntensityToQuantum(image,q) <= pixel.red ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRed(q,image->colormap[(ssize_t) index].red); SetPixelGreen(q,image->colormap[(ssize_t) index].green); SetPixelBlue(q,image->colormap[(ssize_t) index].blue); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,(MagickRealType) q->red <= pixel.red ? 0 : QuantumRange); SetPixelGreen(q,(MagickRealType) q->green <= pixel.green ? 0 : QuantumRange); SetPixelBlue(q,(MagickRealType) q->blue <= pixel.blue ? 0 : QuantumRange); SetPixelOpacity(q,(MagickRealType) q->opacity <= pixel.opacity ? 0 : QuantumRange); q++; } if (!SyncAuthenticPixels(image,&image->exception)) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a n s f o r m C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformColorspace() converts the image to a specified colorspace. % If the image is already in the requested colorspace, no work is performed. % Note that the current colorspace is stored in the image colorspace member. % The transformation matrices are not necessarily the standard ones: the % weights are rescaled to normalize the range of the transformed values to % be [0..QuantumRange]. % % Deprecated, replace with: % % TransformImageColorspace(image,colorspace); % % The format of the TransformColorspace method is: % % unsigned int (void) TransformColorspace(Image *image, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o image: the image to transform % % o colorspace: the desired colorspace. % */ MagickExport unsigned int TransformColorspace(Image *image, const ColorspaceType colorspace) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); return(TransformImageColorspace(image,colorspace)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m H S L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformHSL() converts a (red, green, blue) to a (hue, saturation, % lightness) triple. % % The format of the TransformHSL method is: % % void TransformHSL(const Quantum red,const Quantum green, % const Quantum blue,double *hue,double *saturation,double *lightness) % % A description of each parameter follows: % % o red, green, blue: A Quantum value representing the red, green, and % blue component of a pixel.. % % o hue, saturation, lightness: A pointer to a double value representing a % component of the HSL color space. % */ static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } MagickExport void TransformHSL(const Quantum red,const Quantum green, const Quantum blue,double *hue,double *saturation,double *lightness) { MagickRealType b, delta, g, max, min, r; /* Convert RGB to HSL colorspace. */ assert(hue != (double *) NULL); assert(saturation != (double *) NULL); assert(lightness != (double *) NULL); r=QuantumScale*red; g=QuantumScale*green; b=QuantumScale*blue; max=MagickMax(r,MagickMax(g,b)); min=MagickMin(r,MagickMin(g,b)); *hue=0.0; *saturation=0.0; *lightness=(double) ((min+max)/2.0); delta=max-min; if (delta == 0.0) return; *saturation=(double) (delta/((*lightness < 0.5) ? (min+max) : (2.0-max-min))); if (r == max) *hue=(double) (g == min ? 5.0+(max-b)/delta : 1.0-(max-g)/delta); else if (g == max) *hue=(double) (b == min ? 1.0+(max-r)/delta : 3.0-(max-b)/delta); else *hue=(double) (r == min ? 3.0+(max-g)/delta : 5.0-(max-r)/delta); *hue/=6.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s l a t e T e x t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TranslateText() replaces any embedded formatting characters with the % appropriate image attribute and returns the translated text. % % Deprecated, replace with: % % InterpretImageProperties(image_info,image,embed_text); % % The format of the TranslateText method is: % % char *TranslateText(const ImageInfo *image_info,Image *image, % const char *embed_text) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o embed_text: the address of a character string containing the embedded % formatting characters. % */ MagickExport char *TranslateText(const ImageInfo *image_info,Image *image, const char *embed_text) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.6"); return(InterpretImageProperties(image_info,image,embed_text)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the TransparentImage method is: % % MagickBooleanType TransparentImage(Image *image, % const PixelPacket target,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the replacement opacity value. % */ MagickExport MagickBooleanType TransparentImage(Image *image, const PixelPacket target,const Quantum opacity) { #define TransparentImageTag "Transparent/Image" MagickBooleanType proceed; ssize_t y; /* Make image color transparent. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.1.0"); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) q->opacity=opacity; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; proceed=SetImageProgress(image,TransparentImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h i f t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnshiftImageList() adds the image to the beginning of the list. % % Deprecated, replace with: % % PrependImageToList(images,CloneImageList(image,exception)); % % The format of the UnshiftImageList method is: % % unsigned int UnshiftImageList(Image *images,const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int UnshiftImageList(Image **images,const Image *image, ExceptionInfo *exception) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); PrependImageToList(images,CloneImageList(image,exception)); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + V a l i d a t e C o l o r m a p I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ValidateColormapIndex() validates the colormap index. If the index does % not range from 0 to the number of colors in the colormap an exception % issued and 0 is returned. % % Deprecated, replace with: % % ConstrainColormapIndex(image,index); % % The format of the ValidateColormapIndex method is: % % IndexPacket ValidateColormapIndex(Image *image,const unsigned int index) % % A description of each parameter follows: % % o index: Method ValidateColormapIndex returns colormap index if it is % valid other an exception issued and 0 is returned. % % o image: the image. % % o index: This integer is the colormap index. % */ MagickExport IndexPacket ValidateColormapIndex(Image *image, const size_t index) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.4"); return(ConstrainColormapIndex(image,index)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z o o m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZoomImage() creates a new image that is a scaled size of an existing one. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. The Point filter gives fast pixel replication, % Triangle is equivalent to bi-linear interpolation, and Mitchel giver slower, % very high-quality results. See Graphic Gems III for details on this % algorithm. % % The filter member of the Image structure specifies which image filter to % use. Blur specifies the blur factor where > 1 is blurry, < 1 is sharp. % % The format of the ZoomImage method is: % % Image *ZoomImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: An integer that specifies the number of columns in the zoom % image. % % o rows: An integer that specifies the number of rows in the scaled % image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ZoomImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { Image *zoom_image; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); zoom_image=ResizeImage(image,columns,rows,image->filter,image->blur, exception); return(zoom_image); } #endif
GB_binop__land_bool.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__land_bool) // A.*B function (eWiseMult): GB (_AemultB_01__land_bool) // A.*B function (eWiseMult): GB (_AemultB_02__land_bool) // A.*B function (eWiseMult): GB (_AemultB_03__land_bool) // A.*B function (eWiseMult): GB (_AemultB_bitmap__land_bool) // A*D function (colscale): GB (_AxD__land_bool) // D*A function (rowscale): GB (_DxB__land_bool) // C+=B function (dense accum): GB (_Cdense_accumB__land_bool) // C+=b function (dense accum): GB (_Cdense_accumb__land_bool) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__land_bool) // C=scalar+B GB (_bind1st__land_bool) // C=scalar+B' GB (_bind1st_tran__land_bool) // C=A+scalar GB (_bind2nd__land_bool) // C=A'+scalar GB (_bind2nd_tran__land_bool) // C type: bool // A type: bool // B,b type: bool // BinaryOp: cij = (aij && bij) #define GB_ATYPE \ bool #define GB_BTYPE \ bool #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ bool aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ bool bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x && y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LAND || GxB_NO_BOOL || GxB_NO_LAND_BOOL) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__land_bool) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__land_bool) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__land_bool) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type bool bool bwork = (*((bool *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__land_bool) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__land_bool) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__land_bool) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__land_bool) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__land_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__land_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__land_bool) ( 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__land_bool) ( 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 ; bool x = (*((bool *) x_input)) ; bool *Bx = (bool *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; bool 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__land_bool) ( 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 ; bool *Ax = (bool *) Ax_input ; bool y = (*((bool *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; bool 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) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x && aij) ; \ } GrB_Info GB (_bind1st_tran__land_bool) ( 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 \ bool #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool x = (*((const bool *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ bool } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij && y) ; \ } GrB_Info GB (_bind2nd_tran__land_bool) ( 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 bool y = (*((const bool *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB046-doall2-orig-no.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor 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 Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* 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.comLLNL/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: Only one loop is associated with the omp for construct. The inner loop's loop iteration variable needs an explicit private() clause, otherwise it will be shared by default. */ int a[100][100]; int main() { int i, j; int _ret_val_0; #pragma cetus private(i, j) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i, j) for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#0#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<100; j ++ ) { a[i][j]=(i+j); } } #pragma cetus private(i, j) #pragma loop name main#1 #pragma cetus parallel #pragma omp parallel for private(i, j) for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#1#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<100; j ++ ) { a[i][j]=(a[i][j]+1); } } #pragma cetus private(i, j) #pragma loop name main#2 for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#2#0 for (j=0; j<100; j ++ ) { printf("%d\n", a[i][j]); } } _ret_val_0=0; return _ret_val_0; }
oskar_auto_correlate_scalar_omp.c
/* * Copyright (c) 2015-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "correlate/oskar_auto_correlate_scalar_omp.h" #include "math/oskar_kahan_sum.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_auto_correlate_scalar_omp_f(const int num_sources, const int num_stations, const float2* jones, const float* source_I, float2* vis) { int i, s; #pragma omp parallel for private(i, s) for (s = 0; s < num_stations; ++s) { float sum = 0.0f, guard = 0.0f; const float2 *const jones_station = &jones[s * num_sources]; for (i = 0; i < num_sources; ++i) { const float2 t = jones_station[i]; const float val = (t.x * t.x + t.y * t.y) * source_I[i]; OSKAR_KAHAN_SUM(float, sum, val, guard) } vis[s].x += sum; } } /* Double precision. */ void oskar_auto_correlate_scalar_omp_d(const int num_sources, const int num_stations, const double2* jones, const double* source_I, double2* vis) { int i, s; #pragma omp parallel for private(i, s) for (s = 0; s < num_stations; ++s) { double sum = 0.0; const double2 *const jones_station = &jones[s * num_sources]; for (i = 0; i < num_sources; ++i) { const double2 t = jones_station[i]; sum += (t.x * t.x + t.y * t.y) * source_I[i]; } vis[s].x += sum; } } #ifdef __cplusplus } #endif
GB_unop__log10_fp64_fp64.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__log10_fp64_fp64) // op(A') function: GB (_unop_tran__log10_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = log10 (aij) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = log10 (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = log10 (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOG10 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__log10_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *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++) { double aij = Ax [p] ; double z = aij ; Cx [p] = log10 (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 ; double aij = Ax [p] ; double z = aij ; Cx [p] = log10 (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__log10_fp64_fp64) ( 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
cancel_worksharing.c
// RUN: %libomp-compile && env OMP_CANCELLATION=true %libomp-run | %sort-threads | FileCheck %s // REQUIRES: ompt // Current GOMP interface implementation does not support cancellation; icc 16 does not distinguish between sections and loops // XFAIL: icc-16 #include "callback.h" #include <unistd.h> int main() { int condition=0; #pragma omp parallel num_threads(2) { int x = 0; int i; #pragma omp for for(i = 0; i < 2; i++) { if(i == 0) { x++; OMPT_SIGNAL(condition); #pragma omp cancel for } else { x++; OMPT_WAIT(condition,1); delay(10000); #pragma omp cancellation point for } } } #pragma omp parallel num_threads(2) { #pragma omp sections { #pragma omp section { OMPT_SIGNAL(condition); #pragma omp cancel sections } #pragma omp section { OMPT_WAIT(condition,2); delay(10000); #pragma omp cancellation point sections } } } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_cancel' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_task_create: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], parent_task_frame.exit=[[NULL]], parent_task_frame.reenter=[[NULL]], new_task_id=[[TASK_ID:[0-9]+]], codeptr_ra=[[NULL]], task_type=ompt_task_initial=1, has_dependences=no // cancel for and sections // CHECK: {{^}}[[MASTER_ID]]: ompt_event_cancel: task_data=[[TASK_ID:[0-9]+]], flags=ompt_cancel_loop|ompt_cancel_activated=20, codeptr_ra={{0x[0-f]*}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_cancel: task_data=[[TASK_ID:[0-9]+]], flags=ompt_cancel_sections|ompt_cancel_{{activated=18|detected=34}}, codeptr_ra={{0x[0-f]*}} // CHECK: {{^}}[[OTHER_THREAD_ID:[0-9]+]]: ompt_event_cancel: task_data=[[TASK_ID:[0-9]+]], flags=ompt_cancel_loop|ompt_cancel_detected=36, codeptr_ra={{0x[0-f]*}} // CHECK: {{^}}[[OTHER_THREAD_ID:[0-9]+]]: ompt_event_cancel: task_data=[[TASK_ID:[0-9]+]], flags=ompt_cancel_sections|ompt_cancel_{{activated=18|detected=34}}, codeptr_ra={{0x[0-f]*}} return 0; }
pngquant.c
/* pngquant.c - quantize the colors in an alphamap down to a specified number ** ** © 2009-2019 by Kornel Lesiński. ** © 1989, 1991 by Jef Poskanzer. ** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. ** ** See COPYRIGHT file for license. */ char *PNGQUANT_USAGE = "\ usage: pngquant [options] [ncolors] -- pngfile [pngfile ...]\n\ pngquant [options] [ncolors] - >stdout <stdin\n\n\ options:\n\ --force overwrite existing output files (synonym: -f)\n\ --skip-if-larger only save converted files if they're smaller than original\n\ --output file destination file path to use instead of --ext (synonym: -o)\n\ --ext new.png set custom suffix/extension for output filenames\n\ --quality min-max don't save below min, use fewer colors below max (0-100)\n\ --speed N speed/quality trade-off. 1=slow, 4=default, 11=fast & rough\n\ --nofs disable Floyd-Steinberg dithering\n\ --posterize N output lower-precision color (e.g. for ARGB4444 output)\n\ --strip remove optional metadata (default on Mac)\n\ --verbose print status messages (synonym: -v)\n\ \n\ Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette.\n\ The output filename is the same as the input name except that\n\ it ends in \"-fs8.png\", \"-or8.png\" or your custom extension (unless the\n\ input is stdin, in which case the quantized image will go to stdout).\n\ If you pass the special output path \"-\" and a single input file, that file\n\ will be processed and the quantized image will go to stdout.\n\ The default behavior if the output file exists is to skip the conversion;\n\ use --force to overwrite. See man page for full list of options.\n"; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <math.h> #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) #include <fcntl.h> /* O_BINARY */ #include <io.h> /* setmode() */ #include <locale.h> /* UTF-8 locale */ #else #include <unistd.h> #endif #ifdef _OPENMP #include <omp.h> #else #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #endif #include "rwpng.h" /* typedefs, common macros, public prototypes */ #include "libimagequant.h" /* if it fails here, run: git submodule update; ./configure; or add -Ilib to compiler flags */ #include "pngquant_opts.h" char *PNGQUANT_VERSION = LIQ_VERSION_STRING " (September 2021)"; static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform tag, png8_image *output_image); static void set_palette(liq_result *result, png8_image *output_image); static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose); static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq); static char *add_filename_extension(const char *filename, const char *newext); static bool file_exists(const char *outname); static void verbose_printf(liq_attr *liq, struct pngquant_options *context, const char *fmt, ...) { if (context->log_callback) { va_list va; va_start(va, fmt); int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0 va_end(va); #if defined(_MSC_VER) char *buf = malloc(required_space); #else char buf[required_space]; #endif va_start(va, fmt); vsnprintf(buf, required_space, fmt, va); va_end(va); context->log_callback(liq, buf, context->log_callback_user_info); #if defined(_MSC_VER) free(buf); #endif } } static void log_callback(const liq_attr *attr, const char *msg, void* user_info) { fprintf(stderr, "%s\n", msg); } #ifdef _OPENMP #define LOG_BUFFER_SIZE 1300 struct buffered_log { int buf_used; char buf[LOG_BUFFER_SIZE]; }; static void log_callback_buferred_flush(const liq_attr *attr, void *context) { struct buffered_log *log = context; if (log->buf_used) { fwrite(log->buf, 1, log->buf_used, stderr); fflush(stderr); log->buf_used = 0; } } static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context) { struct buffered_log *log = context; int len = strlen(msg); if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2; if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log); memcpy(&log->buf[log->buf_used], msg, len); log->buf_used += len+1; log->buf[log->buf_used-1] = '\n'; log->buf[log->buf_used] = '\0'; } #endif void pngquant_internal_print_config(FILE *fd) { fputs("" #ifndef NDEBUG " WARNING: this is a DEBUG (slow) version.\n" /* NDEBUG disables assert() */ #endif #if !USE_SSE && (defined(__SSE__) || defined(__amd64__) || defined(__X86_64__) || defined(__i386__)) " SSE acceleration disabled.\n" #endif #if _OPENMP " Compiled with OpenMP (multicore support).\n" #endif , fd); fflush(fd); } FILE *pngquant_c_stderr() { return stderr; } FILE *pngquant_c_stdout() { return stdout; } static void print_full_version(FILE *fd) { fprintf(fd, "pngquant, %s, by Kornel Lesinski, Greg Roelofs.\n", PNGQUANT_VERSION); pngquant_internal_print_config(fd); rwpng_version_info(fd); fputs("\n", fd); } static void print_usage(FILE *fd) { fputs(PNGQUANT_USAGE, fd); } /** * N = automatic quality, uses limit unless force is set (N-N or 0-N) * -N = no better than N (same as 0-N) * N-M = no worse than N, no better than M * N- = no worse than N, perfect if possible (same as N-100) * * where N,M are numbers between 0 (lousy) and 100 (perfect) */ static bool parse_quality(const char *quality, liq_attr *options, bool *min_quality_limit) { long limit, target; const char *str = quality; char *end; long t1 = strtol(str, &end, 10); if (str == end) return false; str = end; if ('\0' == end[0] && t1 < 0) { // quality="-%d" target = -t1; limit = 0; } else if ('\0' == end[0]) { // quality="%d" target = t1; limit = t1*9/10; } else if ('-' == end[0] && '\0' == end[1]) { // quality="%d-" target = 100; limit = t1; } else { // quality="%d-%d" long t2 = strtol(str, &end, 10); if (str == end || t2 > 0) return false; target = -t2; limit = t1; } *min_quality_limit = (limit > 0); return LIQ_OK == liq_set_quality(options, limit, target); } pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq); static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq); #ifndef PNGQUANT_NO_MAIN int main(int argc, char *argv[]) { struct pngquant_options options = { .floyd = 1.f, // floyd-steinberg dithering .strip = false, }; pngquant_error retval = pngquant_parse_options(argc, argv, &options); if (retval != SUCCESS) { return retval; } if (options.print_version) { puts(PNGQUANT_VERSION); return SUCCESS; } if (options.missing_arguments) { print_full_version(stderr); print_usage(stderr); return MISSING_ARGUMENT; } if (options.print_help) { print_full_version(stdout); print_usage(stdout); return SUCCESS; } #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) setlocale(LC_ALL, ".65001"); // issue #376; set UTF-8 for Unicode filenames #endif liq_attr *liq = liq_attr_create(); if (!liq) { fputs("SSE-capable CPU is required for this build.\n", stderr); return WRONG_ARCHITECTURE; } if (options.quality && !parse_quality(options.quality, liq, &options.min_quality_limit)) { fputs("Quality should be in format min-max where min and max are numbers in range 0-100.\n", stderr); return INVALID_ARGUMENT; } if (options.iebug) { // opacities above 238 will be rounded up to 255, because IE6 truncates <255 to 0. liq_set_min_opacity(liq, 238); fputs(" warning: the workaround for IE6 is deprecated\n", stderr); } if (options.verbose) { liq_set_log_callback(liq, log_callback, NULL); options.log_callback = log_callback; } if (options.last_index_transparent) { liq_set_last_index_transparent(liq, true); } if (options.speed >= 10) { options.fast_compression = true; if (options.speed == 11) { options.floyd = 0; options.speed = 10; } } if (options.speed && LIQ_OK != liq_set_speed(liq, options.speed)) { fputs("Speed should be between 1 (slow) and 11 (fast).\n", stderr); return INVALID_ARGUMENT; } if (options.colors && LIQ_OK != liq_set_max_colors(liq, options.colors)) { fputs("Number of colors must be between 2 and 256.\n", stderr); return INVALID_ARGUMENT; } if (options.posterize && LIQ_OK != liq_set_min_posterization(liq, options.posterize)) { fputs("Posterization should be number of bits in range 0-4.\n", stderr); return INVALID_ARGUMENT; } if (options.extension && options.output_file_path) { fputs("--ext and --output options can't be used at the same time\n", stderr); return INVALID_ARGUMENT; } // new filename extension depends on options used. Typically basename-fs8.png if (options.extension == NULL) { options.extension = options.floyd > 0 ? "-fs8.png" : "-or8.png"; } if (options.output_file_path && options.num_files != 1) { fputs(" error: Only one input file is allowed when --output is used. This error also happens when filenames with spaces are not in quotes.\n", stderr); return INVALID_ARGUMENT; } if (options.using_stdout && !options.using_stdin && options.num_files != 1) { fputs(" error: Only one input file is allowed when using the special output path \"-\" to write to stdout. This error also happens when filenames with spaces are not in quotes.\n", stderr); return INVALID_ARGUMENT; } if (!options.num_files && !options.using_stdin) { fputs("No input files specified.\n", stderr); if (options.verbose) { print_full_version(stderr); } print_usage(stderr); return MISSING_ARGUMENT; } retval = pngquant_main_internal(&options, liq); liq_attr_destroy(liq); return retval; } #endif // Don't use this. This is not a public API. pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq) { if (options->map_file) { png24_image tmp = {.width=0}; if (SUCCESS != read_image(liq, options->map_file, false, &tmp, &options->fixed_palette_image, true, true, false)) { fprintf(stderr, " error: unable to load %s", options->map_file); return INVALID_ARGUMENT; } liq_result *tmp_quantize = liq_quantize_image(liq, options->fixed_palette_image); const liq_palette *pal = liq_get_palette(tmp_quantize); if (!pal) { fprintf(stderr, " error: unable to read colors from %s", options->map_file); return INVALID_ARGUMENT; } for(unsigned int i=0; i < pal->count; i++) { liq_image_add_fixed_color(options->fixed_palette_image, pal->entries[i]); } liq_result_destroy(tmp_quantize); } #ifdef _OPENMP // if there's a lot of files, coarse parallelism can be used if (options->num_files > 2*omp_get_max_threads()) { omp_set_nested(0); omp_set_dynamic(1); } else { omp_set_nested(1); } #endif unsigned int error_count=0, skipped_count=0, file_count=0; pngquant_error latest_error=SUCCESS; #pragma omp parallel for \ schedule(static, 1) reduction(+:skipped_count) reduction(+:error_count) reduction(+:file_count) shared(latest_error) for(int i=0; i < options->num_files; i++) { const char *filename = options->using_stdin ? "stdin" : options->files[i]; struct pngquant_options opts = *options; liq_attr *local_liq = liq_attr_copy(liq); #ifdef _OPENMP struct buffered_log buf = {0}; if (opts.log_callback && omp_get_num_threads() > 1 && opts.num_files > 1) { liq_set_log_callback(local_liq, log_callback_buferred, &buf); liq_set_log_flush_callback(local_liq, log_callback_buferred_flush, &buf); opts.log_callback = log_callback_buferred; opts.log_callback_user_info = &buf; } #endif pngquant_error retval = SUCCESS; const char *outname = opts.output_file_path; char *outname_free = NULL; if (!opts.using_stdout) { if (!outname) { outname = outname_free = add_filename_extension(filename, opts.extension); } if (!opts.force && file_exists(outname)) { fprintf(stderr, " error: '%s' exists; not overwriting\n", outname); retval = NOT_OVERWRITING_ERROR; } } if (SUCCESS == retval) { retval = pngquant_file_internal(filename, outname, &opts, local_liq); } free(outname_free); liq_attr_destroy(local_liq); if (retval) { #pragma omp critical { latest_error = retval; } if (retval == TOO_LOW_QUALITY || retval == TOO_LARGE_FILE) { skipped_count++; } else { error_count++; } } ++file_count; } if (error_count) { verbose_printf(liq, options, "There were errors quantizing %d file%s out of a total of %d file%s.", error_count, (error_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (skipped_count) { verbose_printf(liq, options, "Skipped %d file%s out of a total of %d file%s.", skipped_count, (skipped_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (!skipped_count && !error_count) { verbose_printf(liq, options, "Quantized %d image%s.", file_count, (file_count == 1)? "" : "s"); } if (options->fixed_palette_image) liq_image_destroy(options->fixed_palette_image); return latest_error; } /// Don't hack this. Instead use https://github.com/ImageOptim/libimagequant/blob/f54d2f1a3e1cf728e17326f4db0d45811c63f063/example.c static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq) { pngquant_error retval = SUCCESS; verbose_printf(liq, options, "%s:", filename); liq_image *input_image = NULL; png24_image input_image_rwpng = {.width=0}; bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be output to stdout if (SUCCESS == retval) { retval = read_image(liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->strip, options->verbose); } int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap png8_image output_image = {.width=0}; if (SUCCESS == retval) { verbose_printf(liq, options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL); if (RWPNG_ICCP == input_image_rwpng.input_color) { verbose_printf(liq, options, " used embedded ICC profile to transform image to sRGB colorspace"); } else if (RWPNG_GAMA_CHRM == input_image_rwpng.input_color) { verbose_printf(liq, options, " used gAMA and cHRM chunks to transform image to sRGB colorspace"); } else if (RWPNG_ICCP_WARN_GRAY == input_image_rwpng.input_color) { verbose_printf(liq, options, " warning: ignored ICC profile in GRAY colorspace"); } else if (RWPNG_COCOA == input_image_rwpng.input_color) { // No comment } else if (RWPNG_SRGB == input_image_rwpng.input_color) { verbose_printf(liq, options, " passing sRGB tag from the input"); } else if (input_image_rwpng.gamma != 0.45455) { verbose_printf(liq, options, " converted image from gamma %2.1f to gamma 2.2", 1.0/input_image_rwpng.gamma); } // when using image as source of a fixed palette the palette is extracted using regular quantization liq_result *remap; liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, liq, &remap); if (LIQ_OK == remap_error) { // fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2 // NB: can't change gamma here, because output_color is allowed to be an sRGB tag liq_set_output_gamma(remap, 0.45455); liq_set_dithering_level(remap, options->floyd); retval = prepare_output_image(remap, input_image, input_image_rwpng.output_color, &output_image); if (SUCCESS == retval) { if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) { retval = OUT_OF_MEMORY_ERROR; } set_palette(remap, &output_image); double palette_error = liq_get_quantization_error(remap); if (palette_error >= 0) { quality_percent = liq_get_quantization_quality(remap); verbose_printf(liq, options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent); } } liq_result_destroy(remap); } else if (LIQ_QUALITY_TOO_LOW == remap_error) { retval = TOO_LOW_QUALITY; } else { retval = INVALID_ARGUMENT; // dunno } } if (SUCCESS == retval) { if (options->skip_if_larger) { // this is very rough approximation, but generally avoid losing more quality than is gained in file size. // Quality is raised to 1.5, because even greater savings are needed to justify big quality loss. // but >50% savings are considered always worthwhile in order to allow low quality conversions to work at all const double quality = quality_percent/100.0; const double expected_reduced_size = pow(quality, 1.5); output_image.maximum_file_size = (input_image_rwpng.file_size-1) * (expected_reduced_size < 0.5 ? 0.5 : expected_reduced_size); } output_image.fast_compression = options->fast_compression; output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL; retval = write_image(&output_image, NULL, outname, options, liq); if (TOO_LARGE_FILE == retval) { verbose_printf(liq, options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL); } if (SUCCESS == retval && output_image.metadata_size > 0) { verbose_printf(liq, options, " copied %dKB of additional PNG metadata", (int)(output_image.metadata_size+999)/1000); } } if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) { // when outputting to stdout it'd be nasty to create 0-byte file // so if quality is too low, output 24-bit original pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options, liq); if (write_retval) { retval = write_retval; } } if (input_image) liq_image_destroy(input_image); rwpng_free_image24(&input_image_rwpng); rwpng_free_image8(&output_image); return retval; } static void set_palette(liq_result *result, png8_image *output_image) { const liq_palette *palette = liq_get_palette(result); output_image->num_palette = palette->count; for(unsigned int i=0; i < palette->count; i++) { const liq_color px = palette->entries[i]; output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a}; } } static bool file_exists(const char *outname) { FILE *outfile = fopen(outname, "rb"); if ((outfile ) != NULL) { fclose(outfile); return true; } return false; } /* build the output filename from the input name by inserting "-fs8" or * "-or8" before the ".png" extension (or by appending that plus ".png" if * there isn't any extension), then make sure it doesn't exist already */ static char *add_filename_extension(const char *filename, const char *newext) { size_t x = strlen(filename); char* outname = malloc(x+4+strlen(newext)+1); if (!outname) return NULL; strcpy(outname, filename); if (x > 4 && (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0)) { strcpy(outname+x-4, newext); } else { strcpy(outname+x, newext); } return outname; } static char *temp_filename(const char *basename) { size_t x = strlen(basename); char *outname = malloc(x+1+4); if (!outname) return NULL; strcpy(outname, basename); strcpy(outname+x, ".tmp"); return outname; } static void set_binary_mode(FILE *fp) { #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) setmode(fp == stdout ? 1 : 0, O_BINARY); #endif } static const char *filename_part(const char *path) { const char *outfilename = strrchr(path, '/'); if (outfilename) { return outfilename+1; } else { return path; } } static bool replace_file(const char *from, const char *to, const bool force) { #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) if (force) { // On Windows rename doesn't replace unlink(to); } #endif return (0 == rename(from, to)); } static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq) { FILE *outfile; char *tempname = NULL; if (options->using_stdout) { set_binary_mode(stdout); outfile = stdout; if (output_image) { verbose_printf(liq, options, " writing %d-color image to stdout", output_image->num_palette); } else { verbose_printf(liq, options, " writing truecolor image to stdout"); } } else { tempname = temp_filename(outname); if (!tempname) return OUT_OF_MEMORY_ERROR; if ((outfile = fopen(tempname, "wb")) == NULL) { fprintf(stderr, " error: cannot open '%s' for writing\n", tempname); free(tempname); return CANT_WRITE_ERROR; } if (output_image) { verbose_printf(liq, options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname)); } else { verbose_printf(liq, options, " writing truecolor image as %s", filename_part(outname)); } } pngquant_error retval; #pragma omp critical (libpng) { if (output_image) { retval = rwpng_write_image8(outfile, output_image); } else { retval = rwpng_write_image24(outfile, output_image24); } } if (!options->using_stdout) { fclose(outfile); if (SUCCESS == retval) { // Image has been written to a temporary file and then moved over destination. // This makes replacement atomic and avoids damaging destination file on write error. if (!replace_file(tempname, outname, options->force)) { retval = CANT_WRITE_ERROR; } } if (retval) { unlink(tempname); } } free(tempname); if (retval && retval != TOO_LARGE_FILE) { fprintf(stderr, " error: failed writing image to %s (%d)\n", options->using_stdout ? "stdout" : outname, retval); } return retval; } static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose) { FILE *infile; if (using_stdin) { set_binary_mode(stdin); infile = stdin; } else if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, " error: cannot open %s for reading\n", filename); return READ_ERROR; } pngquant_error retval; #pragma omp critical (libpng) { retval = rwpng_read_image24(infile, input_image_p, strip, verbose); } if (!using_stdin) { fclose(infile); } if (retval) { fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename)); return retval; } *liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma); if (!*liq_image_p) { return OUT_OF_MEMORY_ERROR; } if (!keep_input_pixels) { if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) { return OUT_OF_MEMORY_ERROR; } input_image_p->row_pointers = NULL; input_image_p->rgba_data = NULL; } return SUCCESS; } static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform output_color, png8_image *output_image) { output_image->width = liq_image_get_width(input_image); output_image->height = liq_image_get_height(input_image); output_image->gamma = liq_get_output_gamma(result); output_image->output_color = output_color; /* ** Step 3.7 [GRR]: allocate memory for the entire indexed image */ output_image->indexed_data = malloc((size_t)output_image->height * (size_t)output_image->width); output_image->row_pointers = malloc((size_t)output_image->height * sizeof(output_image->row_pointers[0])); if (!output_image->indexed_data || !output_image->row_pointers) { return OUT_OF_MEMORY_ERROR; } for(size_t row = 0; row < output_image->height; row++) { output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width; } const liq_palette *palette = liq_get_palette(result); // tRNS, etc. output_image->num_palette = palette->count; return SUCCESS; }
GB_binop__land_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__land_uint8) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__land_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__land_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__land_uint8) // A*D function (colscale): GB (_AxD__land_uint8) // D*A function (rowscale): GB (_DxB__land_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__land_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__land_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__land_uint8) // C=scalar+B GB (_bind1st__land_uint8) // C=scalar+B' GB (_bind1st_tran__land_uint8) // C=A+scalar GB (_bind2nd__land_uint8) // C=A'+scalar GB (_bind2nd_tran__land_uint8) // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = ((x != 0) && (y != 0)) ; // 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_LAND || GxB_NO_UINT8 || GxB_NO_LAND_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__land_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__land_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__land_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__land_uint8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__land_uint8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__land_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__land_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__land_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__land_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__land_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__land_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = Bx [p] ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__land_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = Ax [p] ; Cx [p] = ((aij != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__land_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__land_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
kCDensestSamplingMaxFlow.c
/* Info: This program corresponds to the competitor "MaxFlow-Sampling" in the PVLDB 2020 paper. Feel free to use these lines as you wish. This program randomly selects a small fraction of k-cliques to store in main memory, and uses a series of max-flow computations to find the densest subgraph in the sampled hypergraph via a binary search. To compile: "g++ kCDensestSamplingMaxFlow.c BinaryHeap.c Graph.c MaxFlowDouble.cpp -O3 -o kCDensestSamplingMaxFlow -lm -fopenmp" To execute: "./kCDensestSamplingMaxFlow p k num_of_cliques_to_sample edgeListFileName". p is the number of threads. k is the size of a clique considered as in "k-clique". num_of_cliques_to_sample is the approximate number of k-cliques to sample. The sampling probability will be set as this number divided by the total number of k-cliques. edgeListFileName is the name of the file that contains the graph. Each line of the file contains one edge represented by two integers separated by a space. Output: The program will print relevant information throughout the computation, including - the lower and upper bound obtained in each iteration of the binary search; - the number of nodes of the densest subset in the sampled hypergraph; - the number of k-cliques and the k-clique density of that subset in the original graph; - the number of max-flow computations; - the running time. */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <time.h> #include <math.h> #include <omp.h> #include <limits.h> #include "Graph.h" #include "MaxFlowDouble.hpp" static int UnsignedCmp(const void *a, const void *b) { return (long long)*(unsigned *)a - (long long)*(unsigned *)b; } inline int LargeRand() { if (RAND_MAX == 0x7fff) return (rand() << 15) | rand(); return rand(); } inline int GetRandMax() { if (RAND_MAX == 0x7fff) return 0x3fffffff; return RAND_MAX; } typedef enum {COUNT = 1, SAMPLING = 2, COUNT_IN_SUBGRAPH = 3} task_t; static unsigned *original_graph_id_sg2g = NULL, *original_graph_id_g2sg = NULL; // to improve (???) #pragma omp threadprivate(original_graph_id_g2sg, original_graph_id_sg2g) unsigned *densest_subgraph_id_sg2g = NULL, *densest_subgraph_id_g2sg = NULL; Subgraph *AllocSubgraph(Graph *g, unsigned char k) { Subgraph *sg = (Subgraph *)malloc(sizeof(Subgraph)); sg->n = (unsigned *)calloc(k, sizeof(unsigned)); sg->d = (unsigned **)malloc(k * sizeof(unsigned *)); sg->adj = (unsigned *)malloc(g->core * g->core * sizeof(unsigned)); sg->label = (unsigned char *)calloc(g->core, sizeof(unsigned char)); sg->nodes = (unsigned **)malloc(k * sizeof(unsigned *)); sg->core = g->core; for (unsigned i = 1; i < k; ++i){ sg->d[i] = (unsigned *)malloc(g->core * sizeof(unsigned)); sg->nodes[i] = (unsigned *)malloc(g->core * sizeof(unsigned)); } return sg; } void MakeSubgraph(Graph *g, unsigned u, unsigned v, Subgraph *sg, unsigned char k, unsigned *id_sg2g, unsigned *id_g2sg, task_t task) { if (id_sg2g == NULL){ id_g2sg = (unsigned *)malloc(g->n * sizeof(unsigned)); id_sg2g = (unsigned *)malloc(g->core * sizeof(unsigned)); for (unsigned i = 0; i < g->n; ++i) { id_g2sg[i] = UINT_MAX; } } for (unsigned i = 0; i < sg->n[k - 1]; ++i) { sg->label[i] = 0; } for (unsigned i = g->cd[v]; i < g->cd[v + 1]; ++i) { // For each out-neighbor of v id_g2sg[g->adj[i]] = UINT_MAX - 1; } unsigned j = 0; for (unsigned i = g->cd[u]; i < g->cd[u + 1]; ++i) { // For each out-neighbor of u unsigned x = g->adj[i]; if (id_g2sg[x] == UINT_MAX - 1) { id_g2sg[x] = j; id_sg2g[j] = x; sg->label[j] = k - 2; sg->nodes[k - 2][j] = j; sg->d[k - 2][j] = 0; // New degrees ++j; } } sg->n[k - 2] = j; for (unsigned i = 0; i < sg->n[k - 2]; ++i) { // Reorder adjacency list and compute new degrees unsigned x = id_sg2g[i]; for (unsigned l = g->cd[x]; l < g->cd[x + 1]; ++l) { unsigned y = g->adj[l]; j = id_g2sg[y]; if (j < UINT_MAX - 1) { sg->adj[sg->core * i + sg->d[k - 2][i]++] = j; } } } for (unsigned i = g->cd[v]; i < g->cd[v + 1]; ++i) { id_g2sg[g->adj[i]] = -1; } if (task == COUNT || task == SAMPLING) { original_graph_id_g2sg = id_g2sg; original_graph_id_sg2g = id_sg2g; } else { densest_subgraph_id_g2sg = id_g2sg; densest_subgraph_id_sg2g = id_sg2g; } } // ========== // kCList: the clique-listing procedure // ========== unsigned num_of_cliques_to_sample; unsigned sampled_cliques_reserved_size; // Maximum number of cliques for memory allocation; will increase if needed unsigned *cknodes; // Nodes of a clique being formed unsigned *ck; // List of all sampled cliques unsigned *p_ckend; // Pointer to the end of ck[] unsigned long long cnt_clique; // Number of cliques unsigned long long cnt_sampled_clique; // Number of sampled cliques double sampling_prob; // Sampling probability unsigned *is_in_densest_subgraph; // Whether each node is in the densest subgraph unsigned long long cnt_clique_in_densest_subgraph; // Number of cliques in the densest subgraph (without sampling) bool clique_is_in_densest_subgraph(unsigned char clique_size) { for (unsigned i = 0; i < clique_size; ++i) if (!is_in_densest_subgraph[cknodes[i]]) return false; return true; } void KCLIST_CliqueEnumThread(Subgraph *sg, unsigned char clique_size, unsigned char l, task_t task) { if (clique_size == 3) { for (unsigned i = 0; i < sg->n[1]; ++i) { unsigned u = sg->nodes[1][i]; if (task == SAMPLING) cknodes[0] = original_graph_id_sg2g[u]; // When task == COUNT_IN_SUBGRAPH, cknodes is useless switch (task) { case COUNT: { ++cnt_clique; break; } case SAMPLING: { if (LargeRand() >= (GetRandMax() + 1LL) * sampling_prob) // Store this clique with probability sampling_prob break; #pragma omp critical { if (cnt_sampled_clique >= sampled_cliques_reserved_size) { sampled_cliques_reserved_size *= 2; ck = (unsigned *)realloc(ck, sampled_cliques_reserved_size * clique_size * sizeof(unsigned)); p_ckend = ck + cnt_sampled_clique * clique_size; } for (unsigned j = 0; j < clique_size; ++j) *(p_ckend++) = cknodes[j]; ++cnt_sampled_clique; } break; } case COUNT_IN_SUBGRAPH: { ++cnt_clique_in_densest_subgraph; break; } } } return; } if (l == 2) { for (unsigned i = 0; i < sg->n[2]; ++i) { unsigned u = sg->nodes[2][i]; if (task == SAMPLING) cknodes[1] = original_graph_id_sg2g[u]; for (unsigned j = u * sg->core, end = u * sg->core + sg->d[2][u]; j < end; ++j) { unsigned v = sg->adj[j]; if (task == SAMPLING) cknodes[0] = original_graph_id_sg2g[v]; switch (task) { case COUNT: { ++cnt_clique; break; } case SAMPLING: { if (LargeRand() > (GetRandMax() + 1LL) * sampling_prob) // Store this clique with probability sampling_prob break; #pragma omp critical { if (cnt_sampled_clique >= sampled_cliques_reserved_size) { sampled_cliques_reserved_size *= 2; ck = (unsigned *)realloc(ck, sampled_cliques_reserved_size * clique_size * sizeof(unsigned)); p_ckend = ck + cnt_sampled_clique * clique_size; } for (unsigned k = 0; k < clique_size; ++k) *(p_ckend++) = cknodes[k]; ++cnt_sampled_clique; } break; } case COUNT_IN_SUBGRAPH: { ++cnt_clique_in_densest_subgraph; break; } } } } return; } for (unsigned i = 0; i < sg->n[l]; ++i) { // Enumerate in reverse order. Very confusing! "++i" is actually the reverse order. unsigned u = sg->nodes[l][i]; cknodes[l - 1] = original_graph_id_sg2g[u]; sg->n[l - 1] = 0; unsigned end = u * sg->core + sg->d[l][u]; for (unsigned j = u * sg->core; j < end; ++j) { // Relabel nodes and forming U'. unsigned v = sg->adj[j]; if (sg->label[v] == l) { sg->label[v] = l - 1; sg->nodes[l - 1][sg->n[l - 1]++] = v; sg->d[l - 1][v] = 0; // New degrees } } for (unsigned j = 0; j < sg->n[l - 1]; ++j) { // Reorder adjacency list and compute new degrees unsigned v = sg->nodes[l - 1][j]; for (unsigned k = sg->core * v, end = sg->core * v + sg->d[l][v]; k < end; ++k) { unsigned w = sg->adj[k]; if (sg->label[w] == l - 1) { ++sg->d[l - 1][v]; } else{ sg->adj[k--] = sg->adj[--end]; sg->adj[end] = w; } } qsort(sg->adj + sg->core * v, sg->d[l - 1][v], sizeof(unsigned), UnsignedCmp); // Sort the nodes in reverse order } KCLIST_CliqueEnumThread(sg, clique_size, l - 1, task); for (unsigned j = 0; j < sg->n[l - 1]; ++j) { // Restore labels unsigned v = sg->nodes[l - 1][j]; sg->label[v] = l; } } } void KCLIST_CliqueEnum(Graph *g, unsigned char k, task_t task) { Subgraph *sg; switch (task) { case COUNT: { cnt_clique = 0; break; } case SAMPLING: { cnt_sampled_clique = 0; sampled_cliques_reserved_size = 1.1 * num_of_cliques_to_sample; sampling_prob = (num_of_cliques_to_sample < cnt_clique) ? (double)num_of_cliques_to_sample / cnt_clique : 1; p_ckend = ck = (unsigned *)malloc(sampled_cliques_reserved_size * k * sizeof(unsigned)); break; } case COUNT_IN_SUBGRAPH: { cnt_clique_in_densest_subgraph = 0; break; } } if (task == COUNT || task == SAMPLING) { #pragma omp parallel private(sg) reduction(+: cnt_sampled_clique) { cknodes = (unsigned *)malloc(k * sizeof(unsigned)); sg = AllocSubgraph(g, k); #pragma omp for schedule(dynamic, 1) nowait for(unsigned i = 0; i < g->e; ++i) { cknodes[k - 1] = g->edges[i].s; cknodes[k - 2] = g->edges[i].t; MakeSubgraph(g, g->edges[i].s, g->edges[i].t, sg, k, original_graph_id_sg2g, original_graph_id_g2sg, task); KCLIST_CliqueEnumThread(sg, k, k - 2, task); } FreeSubgraph(sg, k); } } else { cknodes = (unsigned *)malloc(k * sizeof(unsigned)); sg = AllocSubgraph(g, k); densest_subgraph_id_g2sg = densest_subgraph_id_sg2g = NULL; for (unsigned i = 0; i < g->e; ++i) { MakeSubgraph(g, g->edges[i].s, g->edges[i].t, sg, k, densest_subgraph_id_sg2g, densest_subgraph_id_g2sg, task); KCLIST_CliqueEnumThread(sg, k, k - 2, task); } free(densest_subgraph_id_g2sg); free(densest_subgraph_id_sg2g); free(cknodes); FreeSubgraph(sg, k); } switch (task) { case COUNT: { printf("Number of %u-cliques: %llu\n", k, cnt_clique); break; } case SAMPLING: { ck = (unsigned *)realloc(ck, cnt_sampled_clique * k * sizeof(unsigned)); printf("Number of sampled %u-cliques: %llu\n", k, cnt_sampled_clique); break; } case COUNT_IN_SUBGRAPH: { break; } } } EdgeList *MakeDensestSubgraphEdgeList(Graph *g, const unsigned char k, const unsigned densest_subset_size) { EdgeList *el = (EdgeList *)malloc(sizeof(EdgeList)); unsigned *new_id = (unsigned *)malloc(g->n * sizeof(unsigned)); for (unsigned i = 0, j = 0; i < g->n; ++i) { if (is_in_densest_subgraph[i]) { new_id[i] = j++; } } el->n = densest_subset_size; el->e = 0; for (unsigned i = 0; i < g->e; ++i) el->e += (is_in_densest_subgraph[g->edges[i].s] && is_in_densest_subgraph[g->edges[i].t]); el->edges = (Edge *)malloc(el->e * sizeof(Edge)); for (unsigned i = 0, j = 0; i < g->e; ++i) { if (is_in_densest_subgraph[g->edges[i].s] && is_in_densest_subgraph[g->edges[i].t]) { el->edges[j].s = new_id[g->edges[i].s]; el->edges[j].t = new_id[g->edges[i].t]; ++j; } } free(new_id); return el; } void Solve(const unsigned char k, Graph *g, time_t *p_t1) { const double EPS = 1e-9; // Count the number of clqiues KCLIST_CliqueEnum(g, k, COUNT); time_t t1 = *p_t1; time_t t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n", (t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); *p_t1 = t2; // Sample k-cliques KCLIST_CliqueEnum(g, k, SAMPLING); t1 = *p_t1; t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n", (t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); *p_t1 = t2; // Compute k-clique degree in the sampled hypergraph unsigned *ckdeg = (unsigned *)calloc(g->n, sizeof(unsigned)); is_in_densest_subgraph = (unsigned *)calloc(g->n, sizeof(unsigned)); for (unsigned long long i = 0; i < cnt_sampled_clique * k; ++i) ++ckdeg[ck[i]]; // Construct the max-flow network double l = (double)cnt_sampled_clique / g->n; double u = 1; for (unsigned i = 1; i < k; ++i) u *= (double)(g->n - i) / (i + 1); Network network; Network::Vertex s = network.AddVertex(); Network::Vertex t = network.AddVertex(); vector<Network::Vertex> L; vector<Network::Edge> edgesToCheck; // Examine these edges later to determine the minimum cut // Construct the network as described in Algorithm 6 of the WWW 2015 paper by Trourakakis for (unsigned i = 0; i < g->n; ++i) { L.push_back(network.AddVertex()); network.AddEdge(s, L[i], ckdeg[i]); // The capacity of the following edge will be modified for each binary search step, and the residual capacity will be checked after max-flow computation edgesToCheck.push_back(network.AddEdge(L[i], t, 0)); } for (unsigned long long i = 0; i < cnt_sampled_clique; ++i) { Network::Vertex v = network.AddVertex(); for (unsigned j = 0; j < k; ++j) { network.AddEdge(L[ck[i * k + j]], v, 1); network.AddEdge(v, L[ck[i * k + j]], k - 1); } } /* // Construct the network as described in Construction B of the KDD 2015 paper by Mitzenmacher et al. for (unsigned i = 0; i < g->n; ++i) { L.push_back(network.AddVertex()); // The capacity of the following edge will be modified for each binary search step, and the residual capacity will be checked after max-flow computation edgesToCheck.push_back(network.AddEdge(s, L[i], 0)); } for (unsigned long long i = 0; i < cnt_sampled_clique; ++i) { Network::Vertex v = network.AddVertex(); for (unsigned j = 0; j < k; ++j) { network.AddEdge(L[ck[i * k + j]], v, u); // Infinite capacity } network.AddEdge(v, t, 1); } */ // Binary search unsigned cnt_max_flow = 0; while (u - l >= 1.0 / g->n / (g->n - 1) && cnt_max_flow < 200) { printf("[Lower Bound, Upper Bound] = [%.12f, %.12f]\n", l, u); // fprintf(ofp, "%.12f\t%.12f\t%u\t%ld\n", l, u, cnt_max_flow, time(NULL) - t0); // fflush(ofp); double guess = (l + u) / 2; for (unsigned i = 0; i < g->n; ++i) { network.capacity[edgesToCheck[i]] = k * guess; // This line is for Algorithm 6 of the WWW 2015 paper by Trourakakis // network.capacity[edgesToCheck[i]] = guess; // This line is for Construction B of the KDD 2015 paper by Mitzenmacher et al. } double max_flow = network.MaxFlow(s, t); if (max_flow < cnt_sampled_clique * k * (1 - EPS)) { // This line is for Algorithm 6 of the WWW 2015 paper by Trourakakis // if (max_flow < cnt_sampled_clique * (1 - EPS)) { // This line is for Construction B of the KDD 2015 paper by Mitzenmacher et al. l = guess; } else u = guess; ++cnt_max_flow; } printf("Binary search completed.\n"); t1 = *p_t1; t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n", (t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); *p_t1 = t2; // Identify the densest subgraph unsigned cnt_node_in_densest_subgraph = 0; for (unsigned i = 0; i < g->n; ++i) { network.capacity[edgesToCheck[i]] = k * l; // This line is for Algorithm 6 of the WWW 2015 paper by Trourakakis // network.capacity[edgesToCheck[i]] = l; // This line is for Construction B of the KDD 2015 paper by Mitzenmacher et al. } network.MaxFlow(s, t); network.BfsOnResidualGraph(s); for (unsigned i = 0; i < g->n; ++i) { is_in_densest_subgraph[i] = network.color[L[i]] == boost::black_color; // This line is for Algorithm 6 of the WWW 2015 paper by Trourakakis // is_in_densest_subgraph[i] = network.color[L[i]] == boost::white_color; // This line is for Construction B of the KDD 2015 paper by Mitzenmacher et al. cnt_node_in_densest_subgraph += is_in_densest_subgraph[i]; } // Count the number of k-cliques in the subgraph of the original graph induced by the densest subset EdgeList *el = MakeDensestSubgraphEdgeList(g, k, cnt_node_in_densest_subgraph); SortByCore(el); Relabel(el); Graph *p_densest_subgraph = MakeGraph(el); KCLIST_CliqueEnum(p_densest_subgraph, k, COUNT_IN_SUBGRAPH); printf("The densest subgraph has %d nodes and %lld %d-cliques.\n", cnt_node_in_densest_subgraph, cnt_clique_in_densest_subgraph, k); printf("Clique density is %.9f\n", (double)cnt_clique_in_densest_subgraph / cnt_node_in_densest_subgraph); printf("Number of max-flows = %d.\n", cnt_max_flow); } int main(int argc, char **argv) { EdgeList *el; Graph *g; unsigned num_threads = atoi(argv[1]); unsigned char k = atoi(argv[2]); num_of_cliques_to_sample = atoi(argv[3]); char *file_name = argv[4]; omp_set_num_threads(num_threads); time_t t0, t1, t2; t0 = t1 = time(NULL); printf("Reading edgelist from file %s\n", file_name); el = ReadEdgeList(file_name); printf("Number of nodes = %u\n", el->n); printf("Number of edges = %u\n", el->e); t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); t1 = t2; printf("Building the graph structure\n"); SortByCore(el); // Do core decomposition and render degeneracy ordering to the nodes Relabel(el); g = MakeGraph(el); printf("Number of nodes (degree > 0) = %u\n", g->n); t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n", (t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); t1 = t2; Solve(k, g, &t1); t2 = time(NULL); printf("- Time = %ldh%ldm%lds\n", (t2 - t1) / 3600, ((t2 - t1) % 3600) / 60, ((t2 - t1) % 60)); t1 = t2; FreeGraph(g); printf("- Overall time = %ldh%ldm%lds\n", (t2 - t0) / 3600, ((t2 - t0) % 3600) / 60, ((t2 - t0) % 60)); //fprintf(ofp, "%ld\n", t2 - t0); //fclose(ofp); return 0; }
sph.h
#ifndef SPH_H #define SPH_H #include <omp.h> #include <vector> #include <cstdlib> #include <cmath> #include <ctime> #include <glm/vec3.hpp> #include <glm/mat3x3.hpp> #include <glm/geometric.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/scalar_multiplication.hpp> #include "sphparticle.h" #include "sphmap.h" #include "sphgrid.h" #define LOG 0 #define SHOW_FPRES 0 #define SHOW_FVISC 0 #define PI 3.14159265358979323846264338327950288f using namespace std; using namespace glm; class SPHSystem { private: SpatialHashTable* table; SpatialGrid* grid; vector<FluidParticle*> Ps; vector<DiffuseParticle*> DPs; vec3 spos; vec3 size; vec3 gap; vec3 m_d; vec3 g_d; vec3 container_lb; vec3 container_ub; vec3 Imax; float k; float g; float dt; float density0; float sptRadius; float smtRadius; float penalty; float itgPenalty; float viscosity; float surfaceTension; float norm_h; float kdiffuse, kb, kd; float f(float q) { float ans; if (0 <= q && q < 1) ans = 2.0 / 3.0 - pow(q, 2) + 0.5 * pow(q, 3); else if (1 <= q && q < 2) ans = 1.0 / 6.0 * pow(2 - q, 3); else ans = 0.0; return ans * 3.0 / 2.0 / PI; } float df(float q) { float ans; if (0 <= q && q < 1) ans = -2 * q + 3.0 / 2.0 * pow(q, 2); else if (1 <= q && q < 2) ans = -0.5 * pow(2 - q, 2); else ans = 0.0; return ans * 3.0 / 2.0 / PI; } float W(FluidParticle* x_i, FluidParticle* x_j) { float q = distance(x_i->getPosition(), x_j->getPosition()) / smtRadius; return 1.0 / pow(smtRadius, 3) * f(q); } vec3 dW(FluidParticle* x_i, FluidParticle* x_j) { float q = distance(x_i->getPosition(), x_j->getPosition()) / smtRadius; vec3 norm = x_i->getPosition() - x_j->getPosition(); norm = norm / sqrt(dot(norm, norm)); return 1.0 / pow(smtRadius, 4) * df(q) * norm; } float C(float r) { if (2 * r > sptRadius && r <= sptRadius) return 32.0f / PI / pow(sptRadius, 9) * (pow(sptRadius - r, 3) * pow(r, 3)); else if (r > 0 && 2 * r <= sptRadius) return 32.0f / PI / pow(sptRadius, 9) * (2 * pow(sptRadius - r, 3) * pow(r, 3) - pow(sptRadius, 6) / 64.0f); else return 0.0f; } float Wdiffuse(float length_x_ij, float influenceRadius) { if (length_x_ij <= influenceRadius) { return (1.0f - length_x_ij / influenceRadius) * 3.0f / (PI * pow(influenceRadius, 3)); } else return 0; } public: SPHSystem( vec3 pos, vec3 vel, vec3 size, vec3 gap, float dt, float m_d, float g_d, vec3 container_lb, vec3 container_ub, float g, float penalty, float itgPenalty, float k, float density0, float sptRadius, float smtRadius, float viscosity, float surfaceTension, float norm_h, float kdiffuse, float kb, float kd, vec3 Imax ) : spos(pos), size(size), gap(gap), dt(dt), m_d(m_d), g_d(g_d), container_lb(container_lb), container_ub(container_ub), g(g), penalty(penalty), itgPenalty(itgPenalty), k(k), density0(density0), sptRadius(sptRadius), smtRadius(smtRadius), viscosity(viscosity), surfaceTension(surfaceTension), norm_h(norm_h), kdiffuse(kdiffuse), kb(kb), kd(kd), Imax(Imax) { this->table = new SpatialHashTable(m_d); this->grid = new SpatialGrid(container_lb, container_ub, g_d, smtRadius); float mass = pow(sptRadius / 2.0, 3) * density0; // pow(2.0 / 3.0 * smtRadius, 3) * density0; vec3 center((size.x-1) * gap.x / 2, (size.y - 1) * gap.y / 2, (size.z - 1) * gap.z / 2); for (int ix = 0; ix < size[0]; ix++) { for (int iy = 0; iy < size[1]; iy++) { for (int iz = 0; iz < size[2]; iz++) { vec3 ppos(gap[0] * ix, gap[1] * iy, gap[2] * iz); if (distance(ppos, center) > (size.x - 1) * gap.x / 2 + 0.1) continue; vec3 rand(0.02 * rand() / RAND_MAX, 0.02 * rand() / RAND_MAX, 0.02 * rand() / RAND_MAX); ppos = ppos + pos + rand; FluidParticle* p = new FluidParticle(ppos, mass); p->setVelocity(vel); Ps.push_back(p); } } } } void integrate() { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) Ps[i]->integrate(dt, itgPenalty); #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) DPs[i]->integrate(dt, itgPenalty); } void build() { table->clear(); table->build(Ps); maintainFluidParticles(); computeDiffusePotentials(); maintainDiffuseParticles(); grid->computeDensityTable(table); printf("Particles:%d\tDiffuse:%d\n", Ps.size(), DPs.size()); } void maintainFluidParticles() { for (int i = 0; i < Ps.size(); i++) computeNeighborBlocks(Ps[i]); #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) computeNeighbors(Ps[i]); #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) computeBasics(Ps[i]); #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) computeNormals(Ps[i]); #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) computeForces(Ps[i]); } void computeNeighborBlocks(FluidParticle* p) { table->computeNeighborBlocks(p); } void computeNeighbors(FluidParticle* p) { table->computeNeighbors(p); p->setBuiltNeighborsFlag(true); } void computeBasics(FluidParticle* p) { float mass = p->getMass(); vec3 pos = p->getPosition(); vector<FluidParticle*>* neighbors = p->getNeighbors(true); // compute density & pressure float dens = 0; for (int j = 0; j < neighbors->size(); j++) { FluidParticle* p_j = neighbors->at(j); dens += p_j->getMass() * W(p, p_j); } p->setDensity(dens); float pres = k * (pow(dens / density0, 7) - 1); p->setPressure(pres); p->setBuiltBasicsFlag(true); } void computeNormals(FluidParticle* p) { vector<FluidParticle*>* neighbors = p->getNeighbors(true); vec3 norm = { 0, 0, 0 }; for (int j = 0; j < neighbors->size(); j++) { FluidParticle* p_j = neighbors->at(j); float mass_j = p_j->getMass(); float dens_j = p_j->getDensity(); norm += norm_h * mass_j / dens_j * dW(p, p_j); // norm += p_j->getMass() * dW(p, p_j); } // printf("%.2f %.2f %.2f\n", norm.x, norm.y, norm.z); p->setNormal(norm); } void computeForces(FluidParticle* p) { vec3 pos = p->getPosition(); vec3 vel = p->getVelocity(); float mass = p->getMass(); float dens = p->getDensity(); float pres = p->getPressure(); vector<FluidParticle*>* neighbors = p->getNeighbors(true); // ----------------------- // compute F_pressure // ----------------------- vec3 dPres(0, 0, 0); if (SHOW_FPRES) { vec3 tpos = p->getPosition(); printf("stats of %.0f-%.0f-%.0f:\tmass: %.2f\tdensity: %.2f\tpressure: %.2f\n", tpos.x, tpos.y, tpos.z, mass, dens, pres); } #pragma omp parallel for for (int j = 0; j < neighbors->size(); j++) { FluidParticle* p_j = neighbors->at(j); float mass_j = p_j->getMass(); float dens_j = p_j->getDensity(); float pres_j = p_j->getPressure(); vec3 dW_ij = dW(p, p_j); vec3 dPres_j = mass_j * (pres / pow(dens, 2) + pres_j / pow(dens_j, 2)) * dW_ij; dPres += dPres_j; if (SHOW_FPRES) { vec3 tpos = p_j->getPosition(); printf("\tstats of %.0f-%.0f-%.0f:\tmass: %.2f density: %.2f pressure: %.2f param: %.2f dW: %.2f-%.2f-%.2f dPres: %.2f-%.2f-%.2f\n", tpos.x, tpos.y, tpos.z, mass_j, dens_j, pres_j, mass_j * (pres / pow(dens, 2) + pres_j / pow(dens_j, 2)), dW_ij.x, dW_ij.y, dW_ij.z, dPres_j.x, dPres_j.y, dPres_j.z ); } } vec3 Fpres = - mass * dPres; if (SHOW_FPRES) { printf("dpres: %.4f %.4f %.4f\n", dPres.x, dPres.y, dPres.z); printf("Fpres: %.4f %.4f %.4f\n", Fpres.x, Fpres.y, Fpres.z); } p->setFpres(Fpres); // ----------------------- // compute F_viscosity // ----------------------- //vec3 ddVisc(0, 0, 0); //if (SHOW_FVISC) { // vec3 tpos = pos; // printf("stats of %.0f-%.0f-%.0f:\tmass: %.2f\tvel: %.2f-%.2f-%.2f\n", // tpos.x, tpos.y, tpos.z, mass, vel.x, vel.y, vel.z); //} //#pragma omp parallel for //for (int j = 0; j < neighbors->size(); j++) { // FluidParticle* p_j = neighbors->at(j); // float mass_j = p_j->getMass(); // float dens_j = p_j->getDensity(); // vec3 x_ij = pos - p_j->getPosition(); // vec3 v_ij = vel - p_j->getVelocity(); // vec3 dW_ij = dW(p, p_j); // vec3 ddVisc_j = mass_j / dens_j * v_ij * (dot(x_ij, dW_ij) / (dot(x_ij, x_ij) + 0.01 * pow(smtRadius, 2))); // ddVisc += ddVisc_j; // if (SHOW_FVISC) { // vec3 tpos = p_j->getPosition(); // printf("\tstats of %.0f-%.0f-%.0f:\tmass: %.2f density: %.2f dW: %.2f-%.2f-%.2f ddVisc: %.2f-%.2f-%.2f\n", // tpos.x, tpos.y, tpos.z, // mass_j, dens_j, // dW_ij.x, dW_ij.y, dW_ij.z, // ddVisc_j.x, ddVisc_j.y, ddVisc_j.z // ); // } //} //vec3 Fvisc = 2 * mass * viscosity * ddVisc; //if (SHOW_FVISC) { // printf("ddVisc: %.4f %.4f %.4f\n", ddVisc.x, ddVisc.y, ddVisc.z); // printf("Fvisc: %.4f %.4f %.4f\n", Fvisc.x, Fvisc.y, Fvisc.z); //} // p->setFvisc(Fvisc); // ----------------------- // compute F_cohesion F_curvature // ----------------------- vec3 Fcohs(0, 0, 0), Fcurv(0, 0, 0); for (int j = 0; j < neighbors->size(); j++) { FluidParticle* p_j = neighbors->at(j); vec3 pos_j = p_j->getPosition(); float mass_j = p_j->getMass(); float dens_j = p_j->getDensity(); float K_ij = 2 * density0 / (dens + dens_j); Fcohs += mass_j * C(length(pos - pos_j)) * normalize(pos - pos_j) * K_ij; Fcurv += (p->getNormal() - p_j->getNormal()) * K_ij; } Fcohs *= -surfaceTension * mass; Fcurv *= -surfaceTension * mass; p->setFvisc(Fcurv + Fcohs); p->setBuiltForcesFlag(true); } void computeDiffusePotential(FluidParticle* p) { vector<FluidParticle*>* neighbors = p->getNeighbors(true); vec3 x_i = p->getPosition(); vec3 v_i = p->getVelocity(); vec3 n_i = p->getNormal(); float vi_diff = 0, ki = 0; // Energy float Eki = 0.5 * p->getMass() * dot(v_i, v_i); for (int j = 0 ; j < neighbors->size() ; j++) { FluidParticle* p_j = neighbors->at(j); vec3 x_j = p_j->getPosition(); vec3 v_j = p_j->getVelocity(); vec3 n_j = p_j->getNormal(); vec3 v_ij = v_i - v_j, x_ij = x_i - x_j; float W_ij = Wdiffuse(length(x_ij), smtRadius); // Trapped Air vi_diff += length(v_ij) * (1.0f - dot(normalize(v_ij), normalize(x_ij))) * W_ij; // Wave Crest if (dot(-x_ij, n_i) < 0 && dot(normalize(v_i), normalize(n_i)) >= 0.6) ki += (1.0f - dot(normalize(n_i), normalize(n_j))) * W_ij; } p->setDiffusePotential(vi_diff, ki, Eki); } float clamp(float I, float Tmin, float Tmax) { return (std::min(I, Tmax) - std::min(I, Tmin)) / (Tmax - Tmin); } void computeDiffusePotentials() { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) computeDiffusePotential(Ps[i]); //vec3 Imax(0, 0, 0); //for (int i = 0; i < Ps.size(); i++) { // vec3 diffusePotential = Ps[i]->getDiffusePotential(); // for (int j = 0 ; j < 3 ; j++) // Imax[j] = std::max(diffusePotential[j], Imax[j]); //} //printf("%.4f %.4f %.4f\n", Imax.x, Imax.y, Imax.z); for (int i = 0; i < Ps.size(); i++) { vec3 I = Ps[i]->getDiffusePotential(); Ps[i]->setDiffusePotential( clamp(I.x, 0.1f * Imax.x, Imax.x), clamp(I.y, 0.1f * Imax.y, Imax.y), clamp(I.z, 0.1f * Imax.z, Imax.z) ); } } void applyImplicitViscosity(FluidParticle* p) { vec3 vel = p->getVelocity(); vector<FluidParticle*>* neighbors = p->getNeighbors(true); vec3 dVel(0, 0, 0); #pragma omp parallel for for (int j = 0; j < neighbors->size(); j++) { FluidParticle* p_j = neighbors->at(j); vec3 vel_j = p_j->getVelocity(); dVel += viscosity * W(p, p_j) * (vel_j - vel); } p->setVelocity(vel + dVel); } void applyImplicitViscosity() { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) applyImplicitViscosity(Ps[i]); } void maintainDiffuseParticles() { auto it = DPs.begin(); while (it != DPs.end()) { if ((*it)->reduceLifetime()) it = DPs.erase(it); else it++; } for (int i = 0; i < Ps.size(); i++) { vec3 I = Ps[i]->getDiffusePotential(); int n = dt* kdiffuse* I.z* (I.x + I.y); // printf("%.2f ", dt * kdiffuse * I.z * (I.x + I.y)); for (int k = 0; k < n; k++) { vec3 pos = Ps[i]->getPosition() + vec3(0.02 * rand() / RAND_MAX, 0.02 * rand() / RAND_MAX, 0.02 * rand() / RAND_MAX); DiffuseParticle* p = new DiffuseParticle(pos, Ps[i]->getMass(), 0, 1); DPs.push_back(p); } } for (int i = 0; i < DPs.size(); i++) computeNeighborBlocks(DPs[i]); #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) computeNeighbors(DPs[i]); #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) computeDiffuseType(DPs[i]); } vec3 computeDiffuseNeighborAvgVel(DiffuseParticle* dp) { vec3 res(0, 0, 0); float totalW = 0.0f; vector<FluidParticle*>* neighbors = dp->getNeighbors(true); for (int i = 0; i < neighbors->size(); i++) { float Wi = W(dp, neighbors->at(i)); res += neighbors->at(i)->getVelocity() * Wi; totalW += Wi; } return res / totalW; } vec3 computeDiffuseFexp(DiffuseParticle* dp) { return vec3(0, 0, 0); } void computeDiffuseType(DiffuseParticle* dp) { int numNeighbors = dp->getNeighbors(true)->size(); if (numNeighbors < 6) dp->setDiffuseType(DiffuseParticle::TYPE_SPRY); else if (numNeighbors > 20) dp->setDiffuseType(DiffuseParticle::TYPE_BUBB); else dp->setDiffuseType(DiffuseParticle::TYPE_FOAM); } void applyDiffuseForces(DiffuseParticle* dp) { vec3 acc(0, 0, 0); if (dp->getDiffuseType() == DiffuseParticle::TYPE_SPRY) { acc = (computeDiffuseFexp(dp) + vec3(0, -g, 0)) / dp->getMass(); dp->applyTempForce(acc * dp->getMass()); } else if (dp->getDiffuseType() == DiffuseParticle::TYPE_FOAM) { dp->setVelocity(computeDiffuseNeighborAvgVel(dp)); } else if (dp->getDiffuseType() == DiffuseParticle::TYPE_BUBB) { acc = -kb * vec3(0, -g, 0) + kd * (computeDiffuseNeighborAvgVel(dp) - dp->getVelocity()); dp->applyTempForce(acc * dp->getMass()); } } void applyGForces() { vec3 g(0.0f, -g, 0.0f); #pragma omp parallel for for (int i = 0 ; i < Ps.size() ; i++) Ps[i]->applyPermForce(Ps[i]->getMass() * g); } void applyTempForces(vec3& f) { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) Ps[i]->applyTempForce(f); } void clearTempForces() { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) Ps[i]->clearTempForce(); #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) DPs[i]->clearTempForce(); } void applySPHForces() { #pragma omp parallel for for (int i = 0 ; i < Ps.size() ; i++) { Ps[i]->applyTempForce(Ps[i]->getFpres()); Ps[i]->applyTempForce(Ps[i]->getFvisc()); } #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) applyDiffuseForces(DPs[i]); } void setContainer(vec3 container_lb, vec3 container_ub) { this->container_lb = container_lb; this->container_ub = container_ub; } void applyPenaltyForces() { #pragma omp parallel for for (int i = 0; i < Ps.size(); i++) { vec3 pos = Ps[i]->getPosition(); if (pos.y <= container_lb.y) { vec3 penalty_force(0, -penalty * (pos.y - container_lb.y), 0); Ps[i]->applyTempForce(penalty_force); } if (pos.y > container_ub.y) { vec3 penalty_force(0, -penalty * (pos.y - container_ub.y), 0); Ps[i]->applyTempForce(penalty_force); } if (pos.x <= container_lb.x) { vec3 penalty_force(-penalty * (pos.x - container_lb.x), 0, 0); Ps[i]->applyTempForce(penalty_force); } if (pos.x > container_ub.x) { vec3 penalty_force(-penalty * (pos.x - container_ub.x), 0, 0); Ps[i]->applyTempForce(penalty_force); } if (pos.z <= container_lb.z) { vec3 penalty_force(0, 0, -penalty * (pos.z - container_lb.z)); Ps[i]->applyTempForce(penalty_force); } if (pos.z > container_ub.z) { vec3 penalty_force(0, 0, -penalty * (pos.z - container_ub.z)); Ps[i]->applyTempForce(penalty_force); } } #pragma omp parallel for for (int i = 0; i < DPs.size(); i++) { vec3 pos = DPs[i]->getPosition(); if (pos.y <= container_lb.y) { vec3 penalty_force(0, -penalty * (pos.y - container_lb.y), 0); DPs[i]->applyTempForce(penalty_force); } if (pos.y > container_ub.y) { vec3 penalty_force(0, -penalty * (pos.y - container_ub.y), 0); DPs[i]->applyTempForce(penalty_force); } if (pos.x <= container_lb.x) { vec3 penalty_force(-penalty * (pos.x - container_lb.x), 0, 0); DPs[i]->applyTempForce(penalty_force); } if (pos.x > container_ub.x) { vec3 penalty_force(-penalty * (pos.x - container_ub.x), 0, 0); DPs[i]->applyTempForce(penalty_force); } if (pos.z <= container_lb.z) { vec3 penalty_force(0, 0, -penalty * (pos.z - container_lb.z)); DPs[i]->applyTempForce(penalty_force); } if (pos.z > container_ub.z) { vec3 penalty_force(0, 0, -penalty * (pos.z - container_ub.z)); DPs[i]->applyTempForce(penalty_force); } } } vector<FluidParticle*>* getFluidParticles() { return &Ps; } vector<DiffuseParticle*>* getDiffuseParticles() { return &DPs; } int getPositions(float* pos) { #pragma omp parallel for for (int i = 0 ; i < Ps.size() ; i++) { vec3 ppos = Ps[i]->getPosition(); for (int j = 0 ; j < 3 ; j++) pos[3 * i + j] = ppos[j]; } return Ps.size(); } void getVelocities(float* vel) { #pragma omp parallel for for (int i = 0 ; i < Ps.size() ; i++) { vec3 pvel = Ps[i]->getVelocity(); for (int j = 0 ; j < 3 ; j++) vel[3 * i + j] = pvel[j]; } } int getDiffusePositions(float* pos, int type) { int cnt = 0; for (int i = 0; i < DPs.size(); i++) { if (DPs[i]->getDiffuseType() != type) continue; vec3 ppos = DPs[i]->getPosition(); for (int j = 0; j < 3; j++) pos[3 * cnt + j] = ppos[j]; cnt++; } return cnt; } void getPosAcc(float* posacc) { #pragma omp parallel for for (int i = 0 ; i < Ps.size() ; i++) { vec3 ppos = Ps[i]->getPosition(); vec3 pacc = ppos + Ps[i]->computeTempAcceleration(); for (int j = 0 ; j < 3 ; j++) posacc[6 * i + 0 + j] = ppos[j]; for (int j = 0 ; j < 3 ; j++) posacc[6 * i + 3 + j] = pacc[j]; } } int getTriangleFacets(float* pos, float isolevel) { return grid->computeTriangleFacets(pos, isolevel); } void printPositions() { printf("\n"); for (int i = 0 ; i < Ps.size() ; i++) { vec3 pos = Ps[i]->getPosition(); printf("%.3f-%.3f-%.3f ", pos[0], pos[1], pos[2]); } } }; #endif
bloom.c
/******************************************************************************* *** *** Author: Tyler Barrus *** email: barrust@gmail.com *** *** Version: 1.9.0 *** *** License: MIT 2015 *** *******************************************************************************/ #include <stdlib.h> #include <math.h> /* pow, exp */ #include <stdio.h> /* printf */ #include <string.h> /* strlen */ #include <fcntl.h> /* O_RDWR */ #include <sys/mman.h> /* mmap, mummap */ #include <sys/types.h> /* */ #include <sys/stat.h> /* fstat */ #include <unistd.h> /* close */ #include "bloom.h" #define CHECK_BIT_CHAR(c, k) ((c) & (1 << (k))) #define CHECK_BIT(A, k) (CHECK_BIT_CHAR(A[((k) / 8)], ((k) % 8))) // #define set_bit(A,k) (A[((k) / 8)] |= (1 << ((k) % 8))) // #define clear_bit(A,k) (A[((k) / 8)] &= ~(1 << ((k) % 8))) /* define some constant magic looking numbers */ #define CHAR_LEN 8 #define LOG_TWO_SQUARED 0.480453013918201388143813800 // 0.4804530143737792968750000 // 0.4804530143737792968750000 #define LOG_TWO 0.693147180559945286226764000 /* https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable */ #define B2(n) n, n+1, n+1, n+2 #define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) #define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) static const unsigned char bits_set_table[256] = {B6(0), B6(1), B6(1), B6(2)}; /******************************************************************************* *** PRIVATE FUNCTIONS *******************************************************************************/ static uint64_t* __default_hash(int num_hashes, const char *str); static uint64_t __fnv_1a(const char *key, int seed); static void __calculate_optimal_hashes(BloomFilter *bf); static void __read_from_file(BloomFilter *bf, FILE *fp, short on_disk, const char *filename); static void __write_to_file(BloomFilter *bf, FILE *fp, short on_disk); static void __update_elements_added_on_disk(BloomFilter *bf); static int __sum_bits_set_char(unsigned char c); static int __check_if_union_or_intersection_ok(BloomFilter *res, BloomFilter *bf1, BloomFilter *bf2); int bloom_filter_init_alt(BloomFilter *bf, uint64_t estimated_elements, float false_positive_rate, BloomHashFunction hash_function) { if(estimated_elements == 0 || estimated_elements > UINT64_MAX || false_positive_rate <= 0.0 || false_positive_rate >= 1.0) { return BLOOM_FAILURE; } bf->estimated_elements = estimated_elements; bf->false_positive_probability = false_positive_rate; __calculate_optimal_hashes(bf); bf->bloom = (unsigned char*)calloc(bf->bloom_length + 1, sizeof(char)); // pad to ensure no running off the end bf->elements_added = 0; bloom_filter_set_hash_function(bf, hash_function); bf->__is_on_disk = 0; // not on disk return BLOOM_SUCCESS; } int bloom_filter_init_on_disk_alt(BloomFilter *bf, uint64_t estimated_elements, float false_positive_rate, const char *filepath, BloomHashFunction hash_function) { if(estimated_elements == 0 || estimated_elements > UINT64_MAX || false_positive_rate <= 0.0 || false_positive_rate >= 1.0) { return BLOOM_FAILURE; } bf->estimated_elements = estimated_elements; bf->false_positive_probability = false_positive_rate; __calculate_optimal_hashes(bf); bf->elements_added = 0; FILE *fp; fp = fopen(filepath, "w+b"); if (fp == NULL) { fprintf(stderr, "Can't open file %s!\n", filepath); return BLOOM_FAILURE; } __write_to_file(bf, fp, 1); fclose(fp); // slightly ineffecient to redo some of the calculations... return bloom_filter_import_on_disk_alt(bf, filepath, hash_function); } void bloom_filter_set_hash_function(BloomFilter *bf, BloomHashFunction hash_function) { bf->hash_function = (hash_function == NULL) ? __default_hash : hash_function; } int bloom_filter_destroy(BloomFilter *bf) { if (bf->__is_on_disk == 0) { free(bf->bloom); } else { fclose(bf->filepointer); munmap(bf->bloom, bf->__filesize); } bf->bloom = NULL; bf->filepointer = NULL; bf->elements_added = 0; bf->estimated_elements = 0; bf->false_positive_probability = 0; bf->number_hashes = 0; bf->number_bits = 0; bf->hash_function = NULL; bf->__is_on_disk = 0; bf->__filesize = 0; return BLOOM_SUCCESS; } int bloom_filter_clear(BloomFilter *bf) { for (unsigned long i = 0; i < bf->bloom_length; ++i) { bf->bloom[i] = 0; } bf->elements_added = 0; __update_elements_added_on_disk(bf); return BLOOM_SUCCESS; } void bloom_filter_stats(BloomFilter *bf) { const char *is_on_disk = (bf->__is_on_disk == 0 ? "no" : "yes"); uint64_t size_on_disk = bloom_filter_export_size(bf); printf("BloomFilter\n\ bits: %" PRIu64 "\n\ estimated elements: %" PRIu64 "\n\ number hashes: %d\n\ max false positive rate: %f\n\ bloom length (8 bits): %ld\n\ elements added: %" PRIu64 "\n\ estimated elements added: %" PRIu64 "\n\ current false positive rate: %f\n\ export size (bytes): %" PRIu64 "\n\ number bits set: %" PRIu64 "\n\ is on disk: %s\n", bf->number_bits, bf->estimated_elements, bf->number_hashes, bf->false_positive_probability, bf->bloom_length, bf->elements_added, bloom_filter_estimate_elements(bf), bloom_filter_current_false_positive_rate(bf), size_on_disk, bloom_filter_count_set_bits(bf), is_on_disk); } int bloom_filter_add_string(BloomFilter *bf, const char *str) { uint64_t *hashes = bloom_filter_calculate_hashes(bf, str, bf->number_hashes); int res = bloom_filter_add_string_alt(bf, hashes, bf->number_hashes); free(hashes); return res; } int bloom_filter_check_string(BloomFilter *bf, const char *str) { uint64_t *hashes = bloom_filter_calculate_hashes(bf, str, bf->number_hashes); int res = bloom_filter_check_string_alt(bf, hashes, bf->number_hashes); free(hashes); return res; } uint64_t* bloom_filter_calculate_hashes(BloomFilter *bf, const char *str, unsigned int number_hashes) { return bf->hash_function(number_hashes, str); } /* Add a string to a bloom filter using the defined hashes */ int bloom_filter_add_string_alt(BloomFilter *bf, uint64_t *hashes, unsigned int number_hashes_passed) { if (number_hashes_passed < bf->number_hashes) { fprintf(stderr, "Error: not enough hashes passed in to correctly check!\n"); return BLOOM_FAILURE; } for (unsigned int i = 0; i < bf->number_hashes; ++i) { unsigned long idx = (hashes[i] % bf->number_bits) / 8; int bit = (hashes[i] % bf->number_bits) % 8; #pragma omp atomic update bf->bloom[idx] |= (1 << bit); // set the bit } #pragma omp atomic update bf->elements_added++; __update_elements_added_on_disk(bf); return BLOOM_SUCCESS; } /* Check if a string is in the bloom filter using the passed hashes */ int bloom_filter_check_string_alt(BloomFilter *bf, uint64_t *hashes, unsigned int number_hashes_passed) { if (number_hashes_passed < bf->number_hashes) { fprintf(stderr, "Error: not enough hashes passed in to correctly check!\n"); return BLOOM_FAILURE; } unsigned int i; int r = BLOOM_SUCCESS; for (i = 0; i < bf->number_hashes; ++i) { int tmp_check = CHECK_BIT(bf->bloom, (hashes[i] % bf->number_bits)); if (tmp_check == 0) { r = BLOOM_FAILURE; break; // no need to continue checking } } return r; } float bloom_filter_current_false_positive_rate(BloomFilter *bf) { int num = bf->number_hashes * bf->elements_added; double d = -num / (float) bf->number_bits; double e = exp(d); return pow((1 - e), bf->number_hashes); } int bloom_filter_export(BloomFilter *bf, const char *filepath) { // if the bloom is initialized on disk, no need to export it if (bf->__is_on_disk == 1) { return BLOOM_SUCCESS; } FILE *fp; fp = fopen(filepath, "w+b"); if (fp == NULL) { fprintf(stderr, "Can't open file %s!\n", filepath); return BLOOM_FAILURE; } __write_to_file(bf, fp, 0); fclose(fp); return BLOOM_SUCCESS; } int bloom_filter_import_alt(BloomFilter *bf, const char *filepath, BloomHashFunction hash_function) { FILE *fp; fp = fopen(filepath, "r+b"); if (fp == NULL) { fprintf(stderr, "Can't open file %s!\n", filepath); return BLOOM_FAILURE; } __read_from_file(bf, fp, 0, NULL); fclose(fp); bloom_filter_set_hash_function(bf, hash_function); bf->__is_on_disk = 0; // not on disk return BLOOM_SUCCESS; } int bloom_filter_import_on_disk_alt(BloomFilter *bf, const char *filepath, BloomHashFunction hash_function) { bf->filepointer = fopen(filepath, "r+b"); if (bf->filepointer == NULL) { fprintf(stderr, "Can't open file %s!\n", filepath); return BLOOM_FAILURE; } __read_from_file(bf, bf->filepointer, 1, filepath); // don't close the file pointer here... bloom_filter_set_hash_function(bf, hash_function); bf->__is_on_disk = 1; // on disk return BLOOM_SUCCESS; } char* bloom_filter_export_hex_string(BloomFilter *bf) { uint64_t i, bytes = sizeof(uint64_t) * 2 + sizeof(float) + (bf->bloom_length); char* hex = (char*)calloc((bytes * 2 + 1), sizeof(char)); for (i = 0; i < bf->bloom_length; ++i) { sprintf(hex + (i * 2), "%02x", bf->bloom[i]); // not the fastest way, but works } i = bf->bloom_length * 2; sprintf(hex + i, "%016" PRIx64 "", bf->estimated_elements); i += 16; // 8 bytes * 2 for hex sprintf(hex + i, "%016" PRIx64 "", bf->elements_added); unsigned int ui; memcpy(&ui, &bf->false_positive_probability, sizeof (ui)); i += 16; // 8 bytes * 2 for hex sprintf(hex + i, "%08x", ui); return hex; } int bloom_filter_import_hex_string_alt(BloomFilter *bf, const char *hex, BloomHashFunction hash_function) { uint64_t len = strlen(hex); if (len % 2 != 0) { fprintf(stderr, "Unable to parse; exiting\n"); return BLOOM_FAILURE; } char fpr[9] = {0}; char est_els[17] = {0}; char ins_els[17] = {0}; memcpy(fpr, hex + (len - 8), 8); memcpy(ins_els, hex + (len - 24), 16); memcpy(est_els, hex + (len - 40), 16); uint32_t t_fpr; bf->estimated_elements = strtoull(est_els, NULL, 16); bf->elements_added = strtoull(ins_els, NULL, 16); sscanf(fpr, "%x", &t_fpr); float f; memcpy(&f, &t_fpr, sizeof(float)); bf->false_positive_probability = f; bloom_filter_set_hash_function(bf, hash_function); __calculate_optimal_hashes(bf); bf->bloom = (unsigned char*)calloc(bf->bloom_length + 1, sizeof(char)); // pad bf->__is_on_disk = 0; // not on disk uint64_t i; for (i = 0; i < bf->bloom_length; ++i) { sscanf(hex + (i * 2), "%2hx", (short unsigned int*)&bf->bloom[i]); } return BLOOM_SUCCESS; } uint64_t bloom_filter_export_size(BloomFilter *bf) { return (uint64_t)(bf->bloom_length * sizeof(unsigned char)) + (2 * sizeof(uint64_t)) + sizeof(float); } uint64_t bloom_filter_count_set_bits(BloomFilter *bf) { uint64_t i, res = 0; for (i = 0; i < bf->bloom_length; ++i) { res += __sum_bits_set_char(bf->bloom[i]); } return res; } uint64_t bloom_filter_estimate_elements(BloomFilter *bf) { return bloom_filter_estimate_elements_by_values(bf->number_bits, bloom_filter_count_set_bits(bf), bf->number_hashes); } uint64_t bloom_filter_estimate_elements_by_values(uint64_t m, uint64_t X, int k) { /* m = number bits; X = count of flipped bits; k = number hashes */ double log_n = log(1 - ((double) X / (double) m)); return (uint64_t)-(((double) m / k) * log_n); } int bloom_filter_union(BloomFilter *res, BloomFilter *bf1, BloomFilter *bf2) { // Ensure the bloom filters can be unioned if (__check_if_union_or_intersection_ok(res, bf1, bf2) == BLOOM_FAILURE) { return BLOOM_FAILURE; } uint64_t i; for (i = 0; i < bf1->bloom_length; ++i) { res->bloom[i] = bf1->bloom[i] | bf2->bloom[i]; } bloom_filter_set_elements_to_estimated(res); return BLOOM_SUCCESS; } uint64_t bloom_filter_count_union_bits_set(BloomFilter *bf1, BloomFilter *bf2) { // Ensure the bloom filters can be unioned if (__check_if_union_or_intersection_ok(bf1, bf1, bf2) == BLOOM_FAILURE) { // use bf1 as res return BLOOM_FAILURE; } uint64_t i, res = 0; for (i = 0; i < bf1->bloom_length; ++i) { res += __sum_bits_set_char(bf1->bloom[i] | bf2->bloom[i]); } return res; } int bloom_filter_intersect(BloomFilter *res, BloomFilter *bf1, BloomFilter *bf2) { // Ensure the bloom filters can be used in an intersection if (__check_if_union_or_intersection_ok(res, bf1, bf2) == BLOOM_FAILURE) { return BLOOM_FAILURE; } uint64_t i; for (i = 0; i < bf1->bloom_length; ++i) { res->bloom[i] = bf1->bloom[i] & bf2->bloom[i]; } bloom_filter_set_elements_to_estimated(res); return BLOOM_SUCCESS; } void bloom_filter_set_elements_to_estimated(BloomFilter *bf) { bf->elements_added = bloom_filter_estimate_elements(bf); __update_elements_added_on_disk(bf); } uint64_t bloom_filter_count_intersection_bits_set(BloomFilter *bf1, BloomFilter *bf2) { // Ensure the bloom filters can be used in an intersection if (__check_if_union_or_intersection_ok(bf1, bf1, bf2) == BLOOM_FAILURE) { // use bf1 as res return BLOOM_FAILURE; } uint64_t i, res = 0; for (i = 0; i < bf1->bloom_length; ++i) { res += __sum_bits_set_char(bf1->bloom[i] & bf2->bloom[i]); } return res; } float bloom_filter_jaccard_index(BloomFilter *bf1, BloomFilter *bf2) { // Ensure the bloom filters can be used in an intersection and union if (__check_if_union_or_intersection_ok(bf1, bf1, bf2) == BLOOM_FAILURE) { // use bf1 as res return (float)BLOOM_FAILURE; } float set_union_bits = (float)bloom_filter_count_union_bits_set(bf1, bf2); if (set_union_bits == 0) { // check for divide by 0 error return 1.0; // they must be both empty for this to occur and are therefore the same } return (float)bloom_filter_count_intersection_bits_set(bf1, bf2) / set_union_bits; } /******************************************************************************* * PRIVATE FUNCTIONS *******************************************************************************/ static void __calculate_optimal_hashes(BloomFilter *bf) { // calc optimized values long n = bf->estimated_elements; float p = bf->false_positive_probability; uint64_t m = ceil((-n * logl(p)) / LOG_TWO_SQUARED); // AKA pow(log(2), 2); unsigned int k = round(LOG_TWO * m / n); // AKA log(2.0); // set paramenters bf->number_hashes = k; // should check to make sure it is at least 1... bf->number_bits = m; long num_pos = ceil(m / (CHAR_LEN * 1.0)); bf->bloom_length = num_pos; } static int __sum_bits_set_char(unsigned char c) { return bits_set_table[c]; } static int __check_if_union_or_intersection_ok(BloomFilter *res, BloomFilter *bf1, BloomFilter *bf2) { if (res->number_hashes != bf1->number_hashes || bf1->number_hashes != bf2->number_hashes) { return BLOOM_FAILURE; } else if (res->number_bits != bf1->number_bits || bf1->number_bits != bf2->number_bits) { return BLOOM_FAILURE; } else if (res->hash_function != bf1->hash_function || bf1->hash_function != bf2->hash_function) { return BLOOM_FAILURE; } return BLOOM_SUCCESS; } /* NOTE: this assumes that the file handler is open and ready to use */ static void __write_to_file(BloomFilter *bf, FILE *fp, short on_disk) { if (on_disk == 0) { fwrite(bf->bloom, bf->bloom_length, 1, fp); } else { // will need to write out everything by hand uint64_t i; for (i = 0; i < bf->bloom_length; ++i) { fputc(0, fp); } } fwrite(&bf->estimated_elements, sizeof(uint64_t), 1, fp); fwrite(&bf->elements_added, sizeof(uint64_t), 1, fp); fwrite(&bf->false_positive_probability, sizeof(float), 1, fp); } /* NOTE: this assumes that the file handler is open and ready to use */ static void __read_from_file(BloomFilter *bf, FILE *fp, short on_disk, const char *filename) { int offset = sizeof(uint64_t) * 2 + sizeof(float); fseek(fp, offset * -1, SEEK_END); fread(&bf->estimated_elements, sizeof(uint64_t), 1, fp); fread(&bf->elements_added, sizeof(uint64_t), 1, fp); fread(&bf->false_positive_probability, sizeof(float), 1, fp); __calculate_optimal_hashes(bf); rewind(fp); if(on_disk == 0) { bf->bloom = (unsigned char*)calloc(bf->bloom_length + 1, sizeof(char)); size_t read; read = fread(bf->bloom, sizeof(char), bf->bloom_length, fp); if (read != bf->bloom_length) { perror("__read_from_file: "); exit(1); } } else { struct stat buf; int fd = open(filename, O_RDWR); if (fd < 0) { perror("open: "); exit(1); } fstat(fd, &buf); bf->__filesize = buf.st_size; bf->bloom = (unsigned char*)mmap((caddr_t)0, bf->__filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (bf->bloom == (unsigned char*) - 1) { perror("mmap: "); exit(1); } // close the file descriptor close(fd); } } static void __update_elements_added_on_disk(BloomFilter* bf) { if (bf->__is_on_disk == 1) { // only do this if it is on disk! int offset = sizeof(uint64_t) + sizeof(float); #pragma omp critical (bloom_filter_critical_on_disk) { fseek(bf->filepointer, offset * -1, SEEK_END); fwrite(&bf->elements_added, sizeof(uint64_t), 1, bf->filepointer); } } } /* NOTE: The caller will free the results */ static uint64_t* __default_hash(int num_hashes, const char *str) { uint64_t *results = (uint64_t*)calloc(num_hashes, sizeof(uint64_t)); int i; for (i = 0; i < num_hashes; ++i) { results[i] = __fnv_1a(str, i); } return results; } static uint64_t __fnv_1a(const char *key, int seed) { // FNV-1a hash (http://www.isthe.com/chongo/tech/comp/fnv/) int i, len = strlen(key); uint64_t h = 14695981039346656037ULL + (31 * seed); // FNV_OFFSET 64 bit with magic number seed for (i = 0; i < len; ++i){ h = h ^ (unsigned char) key[i]; h = h * 1099511628211ULL; // FNV_PRIME 64 bit } return h; }
uniform_grid_environment.h
// ----------------------------------------------------------------------------- // // Copyright (C) 2021 CERN & University of Surrey for the benefit of the // BioDynaMo collaboration. 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef CORE_ENVIRONMENT_UNIFORM_GRID_ENVIRONMENT_H_ #define CORE_ENVIRONMENT_UNIFORM_GRID_ENVIRONMENT_H_ #include <assert.h> #include <omp.h> #include <algorithm> #include <array> #include <atomic> #include <cmath> #include <iostream> #include <limits> #include <memory> #include <mutex> #ifdef LINUX #include <parallel/algorithm> #endif // LINUX #include <utility> #include <vector> #include <morton/morton.h> // NOLINT #include "core/container/agent_vector.h" #include "core/container/fixed_size_vector.h" #include "core/container/inline_vector.h" #include "core/container/math_array.h" #include "core/container/parallel_resize_vector.h" #include "core/environment/environment.h" #include "core/environment/morton_order.h" #include "core/functor.h" #include "core/load_balance_info.h" #include "core/param/param.h" #include "core/resource_manager.h" #include "core/util/log.h" #include "core/util/spinlock.h" namespace bdm { namespace detail { struct InitializeGPUData; } // namespace detail /// A class that represents Cartesian 3D grid class UniformGridEnvironment : public Environment { // MechanicalForcesOpCuda needs access to some UniformGridEnvironment private // members to reconstruct // the grid on GPU (same for MechanicalForcesOpOpenCL) friend struct MechanicalForcesOpCuda; friend struct ::bdm::detail::InitializeGPUData; friend struct MechanicalForcesOpOpenCL; friend class SchedulerTest; public: /// A single unit cube of the grid struct Box { Spinlock lock_; // std::atomic<bool> timestamp_; uint32_t timestamp_; /// start value of the linked list of agents inside this box. /// Next element can be found at `successors_[start_]` AgentHandle start_; /// length of the linked list (i.e. number of agents) /// uint64_t, because sizeof(Box) = 16, for uint16_t and uint64_t uint16_t length_; Box() : timestamp_(0), start_(AgentHandle()), length_(0) {} /// Copy Constructor required for boxes_.resize() /// Since box values will be overwritten afterwards it forwards to the /// default ctor Box(const Box& other) : Box() {} Box& operator=(const Box& other) { // start_ = other.start_.load(std::memory_order_relaxed); // length_ = other.length_.load(std::memory_order_relaxed); start_ = other.start_; length_ = other.length_; return *this; } bool IsEmpty(uint64_t grid_timestamp) const { return grid_timestamp != timestamp_; } uint16_t Size(uint64_t grid_timestamp) const { if (IsEmpty(grid_timestamp)) { return 0; } return length_; } /// @brief Adds an agent to this box /// /// @param[in] agent The object's identifier /// @param AddObject successors The successors void AddObject(AgentHandle ah, AgentVector<AgentHandle>* successors, UniformGridEnvironment* grid) { std::lock_guard<Spinlock> lock_guard(lock_); if (timestamp_ != grid->timestamp_) { timestamp_ = grid->timestamp_; length_ = 1; start_ = ah; } else { length_++; (*successors)[ah] = start_; start_ = ah; } } /// An iterator that iterates over the cells in this box struct Iterator { Iterator(UniformGridEnvironment* grid, const Box* box) : grid_(grid), current_value_(box->start_), countdown_(box->length_) { if (grid->timestamp_ != box->timestamp_) { countdown_ = 0; } } bool IsAtEnd() { return countdown_ <= 0; } Iterator& operator++() { countdown_--; if (countdown_ > 0) { current_value_ = grid_->successors_[current_value_]; } return *this; } AgentHandle operator*() const { return current_value_; } /// Pointer to the neighbor grid; for accessing the successor_ list UniformGridEnvironment* grid_; /// The current agent to be considered AgentHandle current_value_; /// The remain number of agents to consider int countdown_ = 0; }; Iterator begin() const { // NOLINT auto* grid = static_cast<UniformGridEnvironment*>( Simulation::GetActive()->GetEnvironment()); return Iterator(grid, this); } }; /// An iterator that iterates over the boxes in this grid struct NeighborIterator { explicit NeighborIterator( const FixedSizeVector<const Box*, 27>& neighbor_boxes, uint64_t grid_timestamp) : neighbor_boxes_(neighbor_boxes), // start iterator from box 0 box_iterator_(neighbor_boxes_[0]->begin()), grid_timestamp_(grid_timestamp) { // if first box is empty if (neighbor_boxes_[0]->IsEmpty(grid_timestamp)) { ForwardToNonEmptyBox(grid_timestamp); } } bool IsAtEnd() const { return is_end_; } AgentHandle operator*() const { return *box_iterator_; } /// Version where empty neighbor boxes are allowed NeighborIterator& operator++() { ++box_iterator_; // if iterator of current box has come to an end, continue with next box if (box_iterator_.IsAtEnd()) { return ForwardToNonEmptyBox(grid_timestamp_); } return *this; } private: /// The 27 neighbor boxes that will be searched for agents const FixedSizeVector<const Box*, 27>& neighbor_boxes_; /// The box that shall be considered to iterate over for finding simulation /// objects typename Box::Iterator box_iterator_; uint64_t grid_timestamp_; /// The id of the box to be considered (i.e. value between 0 - 26) uint16_t box_idx_ = 0; /// Flag to indicate that all the neighbor boxes have been searched through bool is_end_ = false; /// Forwards the iterator to the next non empty box and returns itself /// If there are no non empty boxes is_end_ is set to true NeighborIterator& ForwardToNonEmptyBox(uint64_t grid_timestamp) { // increment box id until non empty box has been found while (++box_idx_ < neighbor_boxes_.size()) { // box is empty or uninitialized (padding box) -> continue if (neighbor_boxes_[box_idx_]->IsEmpty(grid_timestamp)) { continue; } // a non-empty box has been found box_iterator_ = neighbor_boxes_[box_idx_]->begin(); return *this; } // all remaining boxes have been empty; reached end is_end_ = true; return *this; } }; /// Enum that determines the degree of adjacency in search neighbor boxes // todo(ahmad): currently only kHigh is supported (hardcoded 26 several // places) enum Adjacency { kLow, /**< The closest 8 neighboring boxes */ kMedium, /**< The closest 18 neighboring boxes */ kHigh /**< The closest 26 neighboring boxes */ }; explicit UniformGridEnvironment(Adjacency adjacency = kHigh) : adjacency_(adjacency), lbi_(this) {} UniformGridEnvironment(UniformGridEnvironment const&) = delete; void operator=(UniformGridEnvironment const&) = delete; virtual ~UniformGridEnvironment() {} /// Clears the grid void Clear() override { if (!is_custom_box_length_) { box_length_ = 1; } box_length_squared_ = 1; num_boxes_axis_ = {{0}}; num_boxes_xy_ = 0; int32_t inf = std::numeric_limits<int32_t>::max(); grid_dimensions_ = {inf, -inf, inf, -inf, inf, -inf}; threshold_dimensions_ = {inf, -inf}; successors_.clear(); has_grown_ = false; } struct AssignToBoxesFunctor : public Functor<void, Agent*, AgentHandle> { explicit AssignToBoxesFunctor(UniformGridEnvironment* grid) : grid_(grid) {} void operator()(Agent* agent, AgentHandle ah) override { const auto& position = agent->GetPosition(); auto idx = grid_->GetBoxIndex(position); auto box = grid_->GetBoxPointer(idx); box->AddObject(ah, &(grid_->successors_), grid_); agent->SetBoxIdx(idx); } private: UniformGridEnvironment* grid_ = nullptr; }; void SetBoxLength(int32_t bl) { box_length_ = bl; is_custom_box_length_ = true; } int32_t GetBoxLength() { return box_length_; } /// @brief Calculates the squared euclidian distance between two points /// in 3D /// /// @param[in] pos1 Position of the first point /// @param[in] pos2 Position of the second point /// /// @return The distance between the two points /// inline double SquaredEuclideanDistance(const Double3& pos1, const Double3& pos2) const { const double dx = pos2[0] - pos1[0]; const double dy = pos2[1] - pos1[1]; const double dz = pos2[2] - pos1[2]; return (dx * dx + dy * dy + dz * dz); } inline bool WithinSquaredEuclideanDistance(double squared_radius, const Double3& pos1, const Double3& pos2) const { const double dx = pos2[0] - pos1[0]; const double dx2 = dx * dx; if (dx2 > squared_radius) { return false; } const double dy = pos2[1] - pos1[1]; const double dy2_plus_dx2 = dy * dy + dx2; if (dy2_plus_dx2 > squared_radius) { return false; } const double dz = pos2[2] - pos1[2]; const double distance = dz * dz + dy2_plus_dx2; return distance < squared_radius; } LoadBalanceInfo* GetLoadBalanceInfo() override { lbi_.Update(); return &lbi_; } /// @brief Return the box index in the one dimensional array of the box /// that contains the position /// /// @param[in] position The position of the object /// /// @return The box index. /// size_t GetBoxIndex(const Double3& position) const { std::array<uint64_t, 3> box_coord; box_coord[0] = (floor(position[0]) - grid_dimensions_[0]) / box_length_; box_coord[1] = (floor(position[1]) - grid_dimensions_[2]) / box_length_; box_coord[2] = (floor(position[2]) - grid_dimensions_[4]) / box_length_; return GetBoxIndex(box_coord); } std::array<int32_t, 6> GetDimensions() const override { return grid_dimensions_; } /// Returns true if the provided point is inside the simulation domain. /// Compares the points coordinates against grid_dimensions_ (without bounding /// boxes). bool ContainedInGrid(const Double3& point) const { double xmin = static_cast<double>(grid_dimensions_[0]) + box_length_; double xmax = static_cast<double>(grid_dimensions_[1]) - box_length_; double ymin = static_cast<double>(grid_dimensions_[2]) + box_length_; double ymax = static_cast<double>(grid_dimensions_[3]) - box_length_; double zmin = static_cast<double>(grid_dimensions_[4]) + box_length_; double zmax = static_cast<double>(grid_dimensions_[5]) - box_length_; if (point[0] >= xmin && point[0] <= xmax && point[1] >= ymin && point[1] <= ymax && point[2] >= zmin && point[2] <= zmax) { return true; } else { return false; } } std::array<int32_t, 2> GetDimensionThresholds() const override { return threshold_dimensions_; } void GetNumBoxesAxis(uint32_t* nba) { nba[0] = num_boxes_axis_[0]; nba[1] = num_boxes_axis_[1]; nba[2] = num_boxes_axis_[2]; } uint64_t GetNumBoxes() const { return boxes_.size(); } std::array<uint64_t, 3> GetBoxCoordinates(size_t box_idx) const { std::array<uint64_t, 3> box_coord; box_coord[2] = box_idx / num_boxes_xy_; auto remainder = box_idx % num_boxes_xy_; box_coord[1] = remainder / num_boxes_axis_[0]; box_coord[0] = remainder % num_boxes_axis_[0]; return box_coord; } /// @brief Applies the given lambda to each neighbor of the specified /// agent is within the squared radius. /// /// In simulation code do not use this function directly. Use the same /// function from the execution context (e.g. `InPlaceExecutionContext`) /// /// @param[in] lambda The operation as a lambda /// @param query The query object /// @param squared_radius The squared search radius (type: double*) /// void ForEachNeighbor(Functor<void, Agent*, double>& lambda, const Agent& query, double squared_radius) override { ForEachNeighbor(lambda, query.GetPosition(), squared_radius, &query); } /// @brief Applies the given lambda to each neighbor of the specified /// position within the squared radius. /// /// In simulation code do not use this function directly. Use the same /// function from the execution context (e.g. `InPlaceExecutionContext`) /// /// @param[in] lambda The operation as a lambda /// @param query_position The query position /// @param squared_radius The squared search radius (type: double*) /// void ForEachNeighbor(Functor<void, Agent*, double>& lambda, const Double3& query_position, double squared_radius, const Agent* query_agent = nullptr) override { if (squared_radius > box_length_squared_) { Log::Fatal( "UniformGridEnvironment::ForEachNeighbor", "The requested search radius (", std::sqrt(squared_radius), ")", " of the neighborhood search exceeds the " "box length (", box_length_, "). The resulting neighborhood would be incomplete."); } const auto& position = query_position; uint32_t idx{std::numeric_limits<uint32_t>::max()}; if (query_agent != nullptr) { idx = query_agent->GetBoxIdx(); } // If the point is not inside the inner grid (excluding the bounding boxes) // as well as there was no previous box index assigned to the agent, we // cannot reliably detect the neighbors and warn the user. if (!ContainedInGrid(query_position) && idx == std::numeric_limits<uint32_t>::max()) { Log::Warning( "UniformGridEnvironment::ForEachNeighbor", "You provided a query_position that is outside of the environment. ", "Neighbor search is not supported in this case. \n", "query_position: ", query_position, "\ngrid_dimensions: ", grid_dimensions_[0] + box_length_, ", ", grid_dimensions_[1] - box_length_, ", ", grid_dimensions_[2] + box_length_, ", ", grid_dimensions_[3] - box_length_, ", ", grid_dimensions_[4] + box_length_, ", ", grid_dimensions_[5] - box_length_); return; } // Freshly created agents are initialized with the largest uint32_t number // available. The above line assumes that the agent has already been located // in the grid, but this assumption does not hold for new agents. Hence, for // new agents, we manually compute the box index. This is also necessary if // we want to find the neighbors of a arbitrary 3D coordinate rather than // the neighbors of an agent. if (idx == std::numeric_limits<uint32_t>::max()) { idx = GetBoxIndex(position); } FixedSizeVector<const Box*, 27> neighbor_boxes; GetMooreBoxes(&neighbor_boxes, idx); auto* rm = Simulation::GetActive()->GetResourceManager(); NeighborIterator ni(neighbor_boxes, timestamp_); const unsigned batch_size = 64; uint64_t size = 0; Agent* agents[batch_size] __attribute__((aligned(64))); double x[batch_size] __attribute__((aligned(64))); double y[batch_size] __attribute__((aligned(64))); double z[batch_size] __attribute__((aligned(64))); double squared_distance[batch_size] __attribute__((aligned(64))); auto process_batch = [&]() { #pragma omp simd for (uint64_t i = 0; i < size; ++i) { const double dx = x[i] - position[0]; const double dy = y[i] - position[1]; const double dz = z[i] - position[2]; squared_distance[i] = dx * dx + dy * dy + dz * dz; } for (uint64_t i = 0; i < size; ++i) { if (squared_distance[i] < squared_radius) { lambda(agents[i], squared_distance[i]); } } size = 0; }; while (!ni.IsAtEnd()) { auto ah = *ni; // increment iterator already here to hide memory latency ++ni; auto* agent = rm->GetAgent(ah); if (agent != query_agent) { agents[size] = agent; const auto& pos = agent->GetPosition(); x[size] = pos[0]; y[size] = pos[1]; z[size] = pos[2]; size++; if (size == batch_size) { process_batch(); } } } process_batch(); }; void ForEachNeighbor(Functor<void, Agent*>& lambda, const Agent& query, void* criteria) override { Log::Fatal("UniformGridEnvironment::ForEachNeighbor", "You tried to call a specific ForEachNeighbor in an " "environment that does not yet support it."); } // NeighborMutex --------------------------------------------------------- /// This class ensures thread-safety for the InPlaceExecutionContext for the /// case /// that an agent modifies its neighbors. class GridNeighborMutexBuilder : public Environment::NeighborMutexBuilder { public: /// The NeighborMutex class is a synchronization primitive that can be /// used to protect agents data from being simultaneously accessed by /// multiple threads. class GridNeighborMutex : public Environment::NeighborMutexBuilder::NeighborMutex { public: GridNeighborMutex(const FixedSizeVector<uint64_t, 27>& mutex_indices, GridNeighborMutexBuilder* mutex_builder) : mutex_indices_(mutex_indices), mutex_builder_(mutex_builder) { // Deadlocks occur if mutliple threads try to acquire the same locks, // but in different order. // -> sort to avoid deadlocks - see lock ordering std::sort(mutex_indices_.begin(), mutex_indices_.end()); } virtual ~GridNeighborMutex() {} void lock() override { // NOLINT for (auto idx : mutex_indices_) { auto& mutex = mutex_builder_->mutexes_[idx].mutex_; // acquire lock (and spin if another thread is holding it) while (mutex.test_and_set(std::memory_order_acquire)) { } } } void unlock() override { // NOLINT for (auto idx : mutex_indices_) { auto& mutex = mutex_builder_->mutexes_[idx].mutex_; mutex.clear(std::memory_order_release); } } void SetMutexIndices(const FixedSizeVector<uint64_t, 27>& indices) { mutex_indices_ = indices; std::sort(mutex_indices_.begin(), mutex_indices_.end()); } private: FixedSizeVector<uint64_t, 27> mutex_indices_; GridNeighborMutexBuilder* mutex_builder_; }; /// Used to store mutexes in a vector. /// Always creates a new mutex (even for the copy constructor) struct MutexWrapper { MutexWrapper() {} MutexWrapper(const MutexWrapper&) {} std::atomic_flag mutex_ = ATOMIC_FLAG_INIT; }; virtual ~GridNeighborMutexBuilder() {} void Update() { auto* grid = static_cast<UniformGridEnvironment*>( Simulation::GetActive()->GetEnvironment()); mutexes_.resize(grid->GetNumBoxes()); } NeighborMutex* GetMutex(uint64_t box_idx) override; private: /// one mutex for each box in `UniformGridEnvironment::boxes_` std::vector<MutexWrapper> mutexes_; }; /// Returns the `NeighborMutexBuilder`. The client use it to create a /// `NeighborMutex`. NeighborMutexBuilder* GetNeighborMutexBuilder() override { return nb_mutex_builder_.get(); } protected: /// Updates the grid, as agents may have moved, added or deleted void UpdateImplementation() override; private: class LoadBalanceInfoUG : public LoadBalanceInfo { public: LoadBalanceInfoUG(UniformGridEnvironment* grid); virtual ~LoadBalanceInfoUG(); void Update(); void CallHandleIteratorConsumer( uint64_t start, uint64_t end, Functor<void, Iterator<AgentHandle>*>& f) const override; private: UniformGridEnvironment* grid_; MortonOrder mo_; ParallelResizeVector<Box*> sorted_boxes_; ParallelResizeVector<uint64_t> cummulated_agents_; struct InitializeVectorFunctor : public Functor<void, Iterator<uint64_t>*> { UniformGridEnvironment* grid; uint64_t start; ParallelResizeVector<Box*>& sorted_boxes; ParallelResizeVector<uint64_t>& cummulated_agents; InitializeVectorFunctor(UniformGridEnvironment* grid, uint64_t start, decltype(sorted_boxes) sorted_boxes, decltype(cummulated_agents) cummulated_agents); virtual ~InitializeVectorFunctor(); void operator()(Iterator<uint64_t>* it) override; }; void AllocateMemory(); void InitializeVectors(); }; /// The vector containing all the boxes in the grid /// Using parallel resize vector to enable parallel initialization and thus /// better scalability. ParallelResizeVector<Box> boxes_; /// is incremented at each call to Update /// This is used to decide if boxes should be reinitialized uint32_t timestamp_ = 0; /// Length of a Box int32_t box_length_ = 1; /// Length of a Box squared int32_t box_length_squared_ = 1; /// True when the box length was set manually bool is_custom_box_length_ = false; /// Stores the number of Boxes for each axis std::array<uint64_t, 3> num_boxes_axis_ = {{0}}; /// Number of boxes in the xy plane (=num_boxes_axis_[0] * num_boxes_axis_[1]) size_t num_boxes_xy_ = 0; /// The total number of boxes in the uniform grid uint64_t total_num_boxes_ = 0; /// Implements linked list - array index = key, value: next element /// /// // Usage /// AgentHandle current_element = ...; /// AgentHandle next_element = successors_[current_element]; AgentVector<AgentHandle> successors_; /// Determines which boxes to search neighbors in (see enum Adjacency) Adjacency adjacency_; /// Cube which contains all agents /// {x_min, x_max, y_min, y_max, z_min, z_max} std::array<int32_t, 6> grid_dimensions_; /// Stores the min / max dimension value that need to be surpassed in order /// to trigger a diffusion grid change std::array<int32_t, 2> threshold_dimensions_; LoadBalanceInfoUG lbi_; //! /// Holds instance of NeighborMutexBuilder. /// NeighborMutexBuilder is updated if `Param::thread_safety_mechanism` /// is set to `kAutomatic` std::unique_ptr<GridNeighborMutexBuilder> nb_mutex_builder_ = std::make_unique<GridNeighborMutexBuilder>(); void CheckGridGrowth() { // Determine if the grid dimensions have changed (changed in the sense that // the grid has grown outwards) auto min_gd = *std::min_element(grid_dimensions_.begin(), grid_dimensions_.end()); auto max_gd = *std::max_element(grid_dimensions_.begin(), grid_dimensions_.end()); if (min_gd < threshold_dimensions_[0]) { threshold_dimensions_[0] = min_gd; has_grown_ = true; } if (max_gd > threshold_dimensions_[1]) { Log::Info("UniformGridEnvironment", "Your agents are getting near the edge of " "the simulation space. Be aware of boundary conditions that " "may come into play!"); threshold_dimensions_[1] = max_gd; has_grown_ = true; } } void RoundOffGridDimensions(const std::array<double, 6>& grid_dimensions) { grid_dimensions_[0] = floor(grid_dimensions[0]); grid_dimensions_[2] = floor(grid_dimensions[2]); grid_dimensions_[4] = floor(grid_dimensions[4]); grid_dimensions_[1] = ceil(grid_dimensions[1]); grid_dimensions_[3] = ceil(grid_dimensions[3]); grid_dimensions_[5] = ceil(grid_dimensions[5]); } /// @brief Gets the Moore (i.e adjacent) boxes of the query boxAlso adds /// the /// query box. /// /// @param[out] neighbor_boxes The neighbor boxes /// @param[in] box_idx The query box /// void GetMooreBoxes(FixedSizeVector<const Box*, 27>* neighbor_boxes, size_t box_idx) const { neighbor_boxes->push_back(GetBoxPointer(box_idx)); // Adjacent 6 (top, down, left, right, front and back) if (adjacency_ >= kLow) { neighbor_boxes->push_back(GetBoxPointer(box_idx - num_boxes_xy_)); neighbor_boxes->push_back(GetBoxPointer(box_idx + num_boxes_xy_)); neighbor_boxes->push_back(GetBoxPointer(box_idx - num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx + num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx - 1)); neighbor_boxes->push_back(GetBoxPointer(box_idx + 1)); } // Adjacent 12 if (adjacency_ >= kMedium) { neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ - num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx - num_boxes_xy_ - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ - num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx + num_boxes_xy_ - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ + num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx - num_boxes_xy_ + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_axis_[0] + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ + num_boxes_axis_[0])); neighbor_boxes->push_back(GetBoxPointer(box_idx + num_boxes_xy_ + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_axis_[0] + 1)); } // Adjacent 8 if (adjacency_ >= kHigh) { neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ - num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ - num_boxes_axis_[0] + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ + num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx - num_boxes_xy_ + num_boxes_axis_[0] + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ - num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ - num_boxes_axis_[0] + 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ + num_boxes_axis_[0] - 1)); neighbor_boxes->push_back( GetBoxPointer(box_idx + num_boxes_xy_ + num_boxes_axis_[0] + 1)); } } /// @brief Gets the box indices of all adjacent boxes. Also adds the /// query box index. /// /// @param[out] box_indices Result containing all box indices /// @param[in] box_idx The query box /// void GetMooreBoxIndices(FixedSizeVector<uint64_t, 27>* box_indices, size_t box_idx) const { box_indices->push_back(box_idx); // Adjacent 6 (top, down, left, right, front and back) if (adjacency_ >= kLow) { box_indices->push_back(box_idx - num_boxes_xy_); box_indices->push_back(box_idx + num_boxes_xy_); box_indices->push_back(box_idx - num_boxes_axis_[0]); box_indices->push_back(box_idx + num_boxes_axis_[0]); box_indices->push_back(box_idx - 1); box_indices->push_back(box_idx + 1); } // Adjacent 12 if (adjacency_ >= kMedium) { box_indices->push_back(box_idx - num_boxes_xy_ - num_boxes_axis_[0]); box_indices->push_back(box_idx - num_boxes_xy_ - 1); box_indices->push_back(box_idx - num_boxes_axis_[0] - 1); box_indices->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0]); box_indices->push_back(box_idx + num_boxes_xy_ - 1); box_indices->push_back(box_idx + num_boxes_axis_[0] - 1); box_indices->push_back(box_idx - num_boxes_xy_ + num_boxes_axis_[0]); box_indices->push_back(box_idx - num_boxes_xy_ + 1); box_indices->push_back(box_idx - num_boxes_axis_[0] + 1); box_indices->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0]); box_indices->push_back(box_idx + num_boxes_xy_ + 1); box_indices->push_back(box_idx + num_boxes_axis_[0] + 1); } // Adjacent 8 if (adjacency_ >= kHigh) { box_indices->push_back(box_idx - num_boxes_xy_ - num_boxes_axis_[0] - 1); box_indices->push_back(box_idx - num_boxes_xy_ - num_boxes_axis_[0] + 1); box_indices->push_back(box_idx - num_boxes_xy_ + num_boxes_axis_[0] - 1); box_indices->push_back(box_idx - num_boxes_xy_ + num_boxes_axis_[0] + 1); box_indices->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0] - 1); box_indices->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0] + 1); box_indices->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0] - 1); box_indices->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0] + 1); } } /// Determines current box based on parameter box_idx and adds it together /// with half of the surrounding boxes to the vector. /// Legend: C = center, N = north, E = east, S = south, W = west, F = front, /// B = back /// For each box pair which is centro-symmetric only one box is taken -- /// e.g. E-W: E, or BNW-FSE: BNW /// /// (x-axis to the right \ y-axis up) /// z=1 /// +-----+----+-----+ /// | BNW | BN | BNE | /// +-----+----+-----+ /// | NW | N | NE | /// +-----+----+-----+ /// | FNW | FN | FNE | /// +-----+----+-----+ /// /// z = 0 /// +-----+----+-----+ /// | BW | B | BE | /// +-----+----+-----+ /// | W | C | E | /// +-----+----+-----+ /// | FW | F | FE | /// +-----+----+-----+ /// /// z = -1 /// +-----+----+-----+ /// | BSW | BS | BSE | /// +-----+----+-----+ /// | SW | S | SE | /// +-----+----+-----+ /// | FSW | FS | FSE | /// +-----+----+-----+ /// void GetHalfMooreBoxIndices(FixedSizeVector<size_t, 14>* neighbor_boxes, size_t box_idx) const { // C neighbor_boxes->push_back(box_idx); // BW neighbor_boxes->push_back(box_idx + num_boxes_axis_[0] - 1); // FNW neighbor_boxes->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0] - 1); // NW neighbor_boxes->push_back(box_idx + num_boxes_xy_ - 1); // BNW neighbor_boxes->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0] - 1); // B neighbor_boxes->push_back(box_idx + num_boxes_axis_[0]); // FN neighbor_boxes->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0]); // N neighbor_boxes->push_back(box_idx + num_boxes_xy_); // BN neighbor_boxes->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0]); // E neighbor_boxes->push_back(box_idx + 1); // BE neighbor_boxes->push_back(box_idx + num_boxes_axis_[0] + 1); // FNE neighbor_boxes->push_back(box_idx + num_boxes_xy_ - num_boxes_axis_[0] + 1); // NE neighbor_boxes->push_back(box_idx + num_boxes_xy_ + 1); // BNE neighbor_boxes->push_back(box_idx + num_boxes_xy_ + num_boxes_axis_[0] + 1); } /// @brief Gets the pointer to the box with the given index /// /// @param[in] index The index of the box /// /// @return The pointer to the box /// const Box* GetBoxPointer(size_t index) const { assert(index < boxes_.size()); return &(boxes_[index]); } /// @brief Gets the pointer to the box with the given index /// /// @param[in] index The index of the box /// /// @return The pointer to the box /// Box* GetBoxPointer(size_t index) { assert(index < boxes_.size()); return &(boxes_[index]); } /// Returns the box index in the one dimensional array based on box /// coordinates in space /// /// @param box_coord box coordinates in space (x, y, z) /// /// @return The box index. /// size_t GetBoxIndex(const std::array<uint64_t, 3>& box_coord) const { size_t box_idx = box_coord[2] * num_boxes_xy_ + box_coord[1] * num_boxes_axis_[0] + box_coord[0]; assert(box_idx < boxes_.size()); return box_idx; } }; } // namespace bdm #endif // CORE_ENVIRONMENT_UNIFORM_GRID_ENVIRONMENT_H_
GB_unaryop__identity_int32_bool.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int32_bool // op(A') function: GB_tran__identity_int32_bool // C type: int32_t // A type: bool // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int32_bool ( int32_t *Cx, // Cx and Ax may be aliased bool *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int32_bool ( 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
DRB115-forsimd-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This one has data races due to true dependence. But data races happen at both instruction and thread level. Data race pair: a[i+1]@66:5 vs. a[i]@66:12 */ #include <stdio.h> int main(int argc, char* argv[]) { int i; int len=100; int a[100], b[100]; for (i=0;i<len;i++) { a[i]=i; b[i]=i+1; } #pragma omp parallel for simd for (i=0;i<len-1;i++) a[i+1]=a[i]+b[i]; printf("a[50]=%d\n",a[50]); return 0; }
6_for-par1.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <omp.h> void inicializa(int **v, int size) { (*v) = (int *) malloc(sizeof(int)*size); for (int i = 0; i < size; i++) { (*v)[i] = rand() % 10000; } } float square(int x){ int k = 0; while(k < 5000) k++; return sqrt(x); } int main(int argc, char **argv) { srand(time(NULL)); int *vetor; int size = 1000000; inicializa(&vetor, size); #pragma omp parallel for for(int i = 0; i < size; i++){ vetor[i] = square(vetor[i]); } return 0; }
GB_ijproperties.c
//------------------------------------------------------------------------------ // GB_ijproperties: check I and determine its properties //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // check a list of indices I and determine its properties #include "GB_ij.h" // FUTURE:: if limit=0, print a different message. see also setEl, extractEl. #define GB_ICHECK(i,limit) \ { \ if ((i) < 0 || (i) >= (limit)) \ { \ GB_ERROR (GrB_INDEX_OUT_OF_BOUNDS, \ "index " GBd " out of bounds, must be < " GBd , (i), (limit)) ; \ } \ } GrB_Info GB_ijproperties // check I and determine its properties ( // input: const GrB_Index *I, // list of indices, or special const int64_t ni, // length I, or special const int64_t nI, // actual length from GB_ijlength const int64_t limit, // I must be in the range 0 to limit-1 // input/output: int *Ikind, // kind of I, from GB_ijlength int64_t Icolon [3], // begin:inc:end from GB_ijlength // output: bool *I_is_unsorted, // true if I is out of order bool *I_has_dupl, // true if I has a duplicate entry (undefined // if I is unsorted) bool *I_is_contig, // true if I is a contiguous list, imin:imax int64_t *imin_result, // min (I) int64_t *imax_result, // max (I) GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- // inputs: // I: a list of indices if Ikind is GB_LIST // limit: the matrix dimension (# of rows or # of columns) // ni: only used if Ikind is GB_LIST: the length of the array I // nI: the length of the list I, either actual or implicit // input/output: these can be modified // Ikind: GB_ALL, GB_RANGE, GB_STRIDE (both +/- inc), or GB_LIST // Icolon: begin:inc:end for all but GB_LIST // outputs: // I_is_unsorted: true if Ikind == GB_LIST and not in ascending order // I_is_contig: true if I has the form I = begin:end // imin, imax: min (I) and max (I), but only including actual indices // in the sequence. The end value of I=begin:inc:end may not be // reached. For example if I=1:2:10 then max(I)=9, not 10. ASSERT (I != NULL) ; ASSERT (limit >= 0) ; ASSERT (limit <= GB_NMAX) ; int64_t imin, imax ; //-------------------------------------------------------------------------- // scan I //-------------------------------------------------------------------------- // scan the list of indices: check if OK, determine if they are // unsorted, or contiguous, their min and max index, and actual length bool I_unsorted = false ; bool I_has_duplicates = false ; bool I_contig = true ; if ((*Ikind) == GB_ALL) { //---------------------------------------------------------------------- // I = 0:limit-1 //---------------------------------------------------------------------- imin = 0 ; imax = limit-1 ; ASSERT (Icolon [GxB_BEGIN] == imin) ; ASSERT (Icolon [GxB_INC ] == 1) ; ASSERT (Icolon [GxB_END ] == imax) ; } else if ((*Ikind) == GB_RANGE) { //---------------------------------------------------------------------- // I = imin:imax //---------------------------------------------------------------------- imin = Icolon [GxB_BEGIN] ; ASSERT (Icolon [GxB_INC] == 1) ; imax = Icolon [GxB_END ] ; if (imin > imax) { // imin > imax: list is empty imin = limit ; imax = -1 ; } else { // check the limits GB_ICHECK (imin, limit) ; GB_ICHECK (imax, limit) ; } } else if ((*Ikind) == GB_STRIDE) { //---------------------------------------------------------------------- // I = imin:iinc:imax //---------------------------------------------------------------------- // int64_t ibegin = Icolon [GxB_BEGIN] ; int64_t iinc = Icolon [GxB_INC ] ; // int64_t iend = Icolon [GxB_END ] ; // if iinc == 1 on input, the kind has been changed to GB_RANGE ASSERT (iinc != 1) ; if (iinc == 0) { // stride is zero: list is empty, contiguous, and sorted imin = limit ; imax = -1 ; } else if (iinc > 0) { // stride is positive, get the first and last indices imin = GB_ijlist (I, 0, GB_STRIDE, Icolon) ; imax = GB_ijlist (I, nI-1, GB_STRIDE, Icolon) ; } else { // stride is negative, get the first and last indices imin = GB_ijlist (I, nI-1, GB_STRIDE, Icolon) ; imax = GB_ijlist (I, 0, GB_STRIDE, Icolon) ; } if (imin > imax) { // list is empty: so it is contiguous and sorted imin = limit ; imax = -1 ; // change this to an empty GB_RANGE (*Ikind) = GB_RANGE ; Icolon [GxB_BEGIN] = imin ; Icolon [GxB_INC ] = 1 ; Icolon [GxB_END ] = imax ; } else { // list is contiguous if the stride is 1, not contiguous otherwise I_contig = false ; // check the limits GB_ICHECK (imin, limit) ; GB_ICHECK (imax, limit) ; } } else // (*Ikind) == GB_LIST { //---------------------------------------------------------------------- // determine the number of threads to use //---------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (ni, chunk, nthreads_max) ; int ntasks = (nthreads == 1) ? 1 : (8 * nthreads) ; ntasks = GB_IMIN (ntasks, ni) ; ntasks = GB_IMAX (ntasks, 0) ; //---------------------------------------------------------------------- // I is an array of indices //---------------------------------------------------------------------- // scan I to find imin and imax, and validate the list. Also determine // if it is sorted or not, and contiguous or not. imin = limit ; imax = -1 ; // allocate workspace for imin and imax GB_WERK_DECLARE (Work_imin, int64_t) ; GB_WERK_DECLARE (Work_imax, int64_t) ; GB_WERK_PUSH (Work_imin, ntasks, int64_t) ; GB_WERK_PUSH (Work_imax, ntasks, int64_t) ; if (Work_imin == NULL || Work_imax == NULL) { // out of memory GB_WERK_POP (Work_imax, int64_t) ; GB_WERK_POP (Work_imin, int64_t) ; return (GrB_OUT_OF_MEMORY) ; } int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(||:I_unsorted) reduction(&&:I_contig) \ reduction(||:I_has_duplicates) for (tid = 0 ; tid < ntasks ; tid++) { int64_t my_imin = limit ; int64_t my_imax = -1 ; int64_t istart, iend ; GB_PARTITION (istart, iend, ni, tid, ntasks) ; int64_t ilast = (istart == 0) ? -1 : I [istart-1] ; for (int64_t inew = istart ; inew < iend ; inew++) { int64_t i = I [inew] ; if (inew > 0) { if (i < ilast) { // The list I of row indices is out of order, and // C=A(I,J) will need to use qsort to sort each column. // If C=A(I,J)' is computed, however, this flag will be // set back to false, since qsort is not needed if the // result is transposed. I_unsorted = true ; } else if (i == ilast) { // I has at least one duplicate entry. If I is // unsorted, then it is not known if I has duplicates // or not. But if I is sorted, but with duplicates, // then this flag will be true. I_has_duplicates = true ; } if (i != ilast + 1) { I_contig = false ; } } my_imin = GB_IMIN (my_imin, i) ; my_imax = GB_IMAX (my_imax, i) ; ilast = i ; } Work_imin [tid] = my_imin ; Work_imax [tid] = my_imax ; } // wrapup for (tid = 0 ; tid < ntasks ; tid++) { imin = GB_IMIN (imin, Work_imin [tid]) ; imax = GB_IMAX (imax, Work_imax [tid]) ; } // free workspace GB_WERK_POP (Work_imax, int64_t) ; GB_WERK_POP (Work_imin, int64_t) ; #ifdef GB_DEBUG { // check result with one thread bool I_unsorted2 = false ; bool I_has_dupl2 = false ; bool I_contig2 = true ; int64_t imin2 = limit ; int64_t imax2 = -1 ; int64_t ilast = -1 ; for (int64_t inew = 0 ; inew < ni ; inew++) { int64_t i = I [inew] ; if (inew > 0) { if (i < ilast) I_unsorted2 = true ; else if (i == ilast) I_has_dupl2 = true ; if (i != ilast + 1) I_contig2 = false ; } imin2 = GB_IMIN (imin2, i) ; imax2 = GB_IMAX (imax2, i) ; ilast = i ; } ASSERT (I_unsorted == I_unsorted2) ; ASSERT (I_has_duplicates == I_has_dupl2) ; ASSERT (I_contig == I_contig2) ; ASSERT (imin == imin2) ; ASSERT (imax == imax2) ; } #endif if (ni > 0) { // check the limits GB_ICHECK (imin, limit) ; GB_ICHECK (imax, limit) ; } if (ni == 1) { // a single entry does not need to be sorted ASSERT (I [0] == imin) ; ASSERT (I [0] == imax) ; ASSERT (I_unsorted == false) ; ASSERT (I_contig == true) ; } if (ni == 0) { // the list is empty ASSERT (imin == limit && imax == -1) ; } //---------------------------------------------------------------------- // change I if it is an explicit contiguous list of stride 1 //---------------------------------------------------------------------- if (I_contig) { // I is a contigous list of stride 1, imin:imax. // change Ikind to GB_ALL if 0:limit-1, or GB_RANGE otherwise if (imin == 0 && imax == limit-1) { (*Ikind) = GB_ALL ; } else { (*Ikind) = GB_RANGE ; } Icolon [GxB_BEGIN] = imin ; Icolon [GxB_INC ] = 1 ; Icolon [GxB_END ] = imax ; } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- ASSERT (GB_IMPLIES (I_contig, !I_unsorted)) ; ASSERT (((*Ikind) == GB_ALL || (*Ikind) == GB_RANGE) == I_contig) ; // I_is_contig is true if the list of row indices is a contiguous list, // imin:imax. This is an important special case. // I_is_unsorted is true if I is an explicit list, the list is non-empty, // and the indices are not sorted in ascending order. (*I_is_contig) = I_contig ; (*I_is_unsorted) = I_unsorted ; (*I_has_dupl) = I_has_duplicates ; (*imin_result) = imin ; (*imax_result) = imax ; return (GrB_SUCCESS) ; }
linear_math.c
#include "linear_math.h" #include <stdio.h> /* for fprintf */ #include <string.h> /* for memset and memcpy */ #include <math.h> #ifdef NDEBUG #define HANDLE_ERROR #else #define HANDLE_ERROR /* if it's debugging, abort the program */ #endif #ifdef LB_USE_ROW_MAJOR_MATRIX #define MATRIX_INDEX(mat, i, j) i * mat.nCol + j #define PMATRIX_INDEX(pMat, i, j) i * pMat->nCol + j #else /* use column major matrix */ #define MATRIX_INDEX(mat, i, j) j * mat.nRow + i #define PMATRIX_INDEX(pMat, i, j) j * pMat->nRow + i #endif /* LB_USE_ROW_MAJOR_MATRIX */ static void _defaultErrorReporter(const char *errMsg) { // fprintf(stderr, "LinearMath: %s\n", errMsg); } static lbErrorReportFunc lm_reportError = _defaultErrorReporter; void lbSetLinearMathErrorReporter(lbErrorReportFunc errorReporter) { lm_reportError = errorReporter; } /**** vector functions ****/ lbVector lbAllocVector(int size, lbAllocator alloc) { lbVector vec; if (size > 0) { vec.size = size; vec.data = (lbScalar *) alloc( size * sizeof(lbScalar) ); if (vec.data == 0) { /* allocation failure */ lm_reportError("lbAllocVector(size, allocator): failed to allocate memory"); vec.size = 0; HANDLE_ERROR } } else if (size == 0) { vec.size = 0; vec.data = 0; } else { lm_reportError("lbAllocVector(size, allocator): invalid size"); HANDLE_ERROR } return vec; } void lbFreeVector(lbVector *vec, lbDeallocator dealloc) { if ( !lbVectorEmpty(*vec) ) { vec->size = 0; dealloc(vec->data); vec->data = 0; } } lbVector *lbAllocVectors(int size, int count, lbAllocator alloc) { lbVector *vecs; lbSize i; vecs = 0; if (size < 0) { lm_reportError("lbAllocVectors(size, count, allocator): invalid size"); HANDLE_ERROR return 0; } if (count <= 0) { lm_reportError("lbAllocVectors(size, count, allocator): invalid count"); HANDLE_ERROR return 0; } if (size == 0) { vecs = (lbVector *) alloc(count * sizeof(lbVector)); if (vecs == 0) { lm_reportError("lbAllocVectors(size, count, allocator): failed to allocate memory"); HANDLE_ERROR return 0; } for (i = 0; i < count; ++i) { vecs[i].size = 0; vecs[i].data = 0; } } else { /* alloc for both vectors and their data */ vecs = (lbVector *) alloc(count * ( sizeof(lbVector) + size * sizeof(lbScalar)) ); if (vecs == 0) { lm_reportError("lbAllocVectors(size, count, allocator): failed to allocate memory"); HANDLE_ERROR return 0; } vecs[0].data = (lbScalar *)(vecs + count); for (i = 0; i < count; ++i) { vecs[i].size = size; vecs[i].data = vecs[0].data + i * size; } } return vecs; } void lbFreeVectors(lbVector *vecs, lbDeallocator dealloc) { if ( !lbVectorEmpty(vecs[0]) ) { dealloc(vecs); } } lbBool lbVectorEmpty(const lbVector vec) { if (vec.size > 0 && vec.data != 0) { return LB_FALSE; } else if (vec.size == 0 && vec.data == 0) { return LB_TRUE; } else { lm_reportError("lbVectorEmpty(vec): invalid vector"); HANDLE_ERROR return LB_TRUE; } } lbSize lbVectorSize(const lbVector vec) { #ifndef LB_LM_DISABLE_ARG_CHECK if (vec.size > 0 && vec.data != 0) { return vec.size; } else if (vec.size == 0 && vec.data == 0) { return 0; } else { lm_reportError("lbGetVectorSize(vec): invalid vector"); HANDLE_ERROR return 0; } #else return vec.size; #endif } lbScalar lbGetVectorElem(const lbVector vec, int index) { #ifndef LB_LM_DISABLE_ARG_CHECK if (index >= 0 && (lbSize)index < lbVectorSize(vec)) { return vec.data[index]; } else { lm_reportError("lbGetVectorElem(vec, index): index out of bound"); HANDLE_ERROR return 0; } #else return vec.data[index]; #endif } void lbSetVectorElem(lbVector *vec, int index, lbScalar value) { #ifndef LB_LM_DISABLE_ARG_CHECK if (index >= 0 && (lbSize)index < lbVectorSize(*vec)) { vec->data[index] = value; } else { lm_reportError("lbSetVectorElem(vec, index, value): index out of bound"); HANDLE_ERROR } #else vec->data[index] = value; #endif } void lbVectorClear(lbVector *vec, lbScalar value) { lbSize i, sz; sz = lbVectorSize(*vec); // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { vec->data[i] = value; } } void lbVectorCopy(const lbVector in, lbVector *out) { lbSize sz; sz = lbVectorSize(in); if (lbVectorSize(*out) != sz) { lm_reportError("lbVectorCopy(in, out): in and out do not have the same size"); HANDLE_ERROR return; } memcpy(out->data, in.data, sz * sizeof(lbScalar)); } void lbVectorAddition(const lbVector left, const lbVector right, lbVector *out) { lbSize i, sz; sz = left.size; if (right.size != sz || out->size != sz) { lm_reportError("lbVectorAddition(left, right, out): left, right and out do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = left.data[i] + right.data[i]; } } void lbVectorSubtraction(const lbVector left, const lbVector right, lbVector *out) { lbSize i, sz; sz = left.size; if (right.size != sz || out->size != sz) { lm_reportError("lbVectorSubtraction(left, right, out): left, right and out do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = left.data[i] - right.data[i]; } } lbScalar lbVectorDotProduct(const lbVector left, const lbVector right) { lbScalar sum = 0; lbSize i, sz = left.size; if (right.size != sz) { lm_reportError("lbVectorDotProduct(left, right): left and right do not have the same size"); HANDLE_ERROR return 0; } // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { sum += left.data[i] * right.data[i]; } return sum; } lbScalar lbVectorNorm(const lbVector vec) { lbScalar sum = 0; lbSize i, sz = vec.size; // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { sum += vec.data[i] * vec.data[i]; } return sqrt(sum); } void lbVectorProduct(const lbVector left, const lbVector right, lbVector *out) { lbSize i, sz = left.size; if (right.size != out->size) { lm_reportError("lbVectorProduct(vec, scalar, out): vec and out do not have the same size"); HANDLE_ERROR return; } if (right.size != sz) { lm_reportError("lbVectorProduct(left, right): left and right do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < right.size; ++i) { out->data[i] = right.data[i] * left.data[i]; } } void lbVectorScalarProduct(const lbVector vec, lbScalar scalar, lbVector *out) { lbSize i; if (vec.size != out->size) { lm_reportError("lbVectorScalarProduct(vec, scalar, out): vec and out do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < vec.size; ++i) { out->data[i] = vec.data[i] * scalar; } } lbScalar lbVectorSumElem(const lbVector vec) { lbSize i; lbScalar sum; sum = 0; // #pragma omp parallel for private(i) for (i = 0; i < vec.size; ++i) { sum += vec.data[i]; } return sum; } void lbVectorForeach(const lbVector in, lbVector *out, lbUnaryOperation uOper, void *params) { lbSize i; if (in.size != out->size) { lm_reportError("lbVectorForeach(in, out, uOper, params): in and out do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < in.size; ++i) { out->data[i] = uOper(in.data[i], params); } } void lbVectorBiForeach(const lbVector vec1, const lbVector vec2, lbVector *out, lbBinaryOperation biOper, void *params) { lbSize i, sz; sz = vec1.size; if (vec2.size != sz || out->size != sz) { lm_reportError("lbVectorBiForeach(vec1, vec2, out, biOper, params): vec1, vec2 and out" " do not have the same size"); HANDLE_ERROR return; } // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = biOper(vec1.data[i], vec2.data[i], params); } } /**** matrix functions ****/ lbBool lbMatrixRowMajor() { #ifdef LB_USE_ROW_MAJOR_MATRIX return LB_TRUE; #else return LB_FALSE; #endif } lbMatrix lbAllocMatrix(int nRow, int nCol, lbAllocator alloc) { lbMatrix mat; if (nRow > 0 && nCol > 0) { mat.nRow = nRow; mat.nCol = nCol; mat.data = (lbScalar* ) alloc( nRow * nCol * sizeof(lbScalar) ); if (mat.data == 0) { /* allocation failure */ mat.nRow = mat.nCol = 0; } } else if (nRow == 0 && nCol == 0) { mat.nRow = mat.nCol = 0; mat.data = 0; } else { mat.nRow = mat.nCol = 0; mat.data = 0; lm_reportError("lbAllocMatrix(nRow, nCol, allocator): nRow and nCol invalid"); HANDLE_ERROR } return mat; } void lbFreeMatrix(lbMatrix *mat, lbDeallocator dealloc) { if ( !lbMatrixEmpty(*mat) ) { mat->nRow = mat->nCol = 0; dealloc(mat->data); mat->data = 0; } } lbBool lbMatrixEmpty(const lbMatrix mat) { if (mat.nRow > 0 && mat.nCol > 0 && mat.data != 0) { return LB_FALSE; } else if (mat.nRow == 0 && mat.nCol == 0 && mat.data == 0) { return LB_TRUE; } else { lm_reportError("lbMatrixEmpty(mat): invalid matrix"); HANDLE_ERROR return LB_TRUE; } } lbSize lbMatrixRowCount(const lbMatrix mat) { if (mat.nRow > 0 && mat.nCol > 0 && mat.data != 0) { return mat.nRow; } else if (mat.nRow == 0 && mat.nCol == 0 && mat.data == 0) { return 0; } else { lm_reportError("lbMatrixRowCount(mat): invalid matrix"); HANDLE_ERROR return 0; } } lbSize lbMatrixColumnCount(const lbMatrix mat) { if (mat.nRow > 0 && mat.nCol > 0 && mat.data != 0) { return mat.nCol; } else if (mat.nRow == 0 && mat.nCol == 0 && mat.data == 0) { return 0; } else { lm_reportError("lbMatrixColumnCount(mat): invalid matrix"); HANDLE_ERROR return 0; } } lbScalar lbGetMatrixElem(const lbMatrix mat, int row, int col) { if ((lbSize)row < mat.nRow && (lbSize)col < mat.nCol) { return mat.data[MATRIX_INDEX(mat, row, col)]; } else { lm_reportError("lbGetMatrixElem(mat, row, col): row or col out of bound"); HANDLE_ERROR return 0; } } void lbSetMatrixElem(lbMatrix *mat, int row, int col, lbScalar value) { if ((lbSize)row < mat->nRow && (lbSize)col < mat->nCol) { mat->data[PMATRIX_INDEX(mat, row, col)] = value; } else { lm_reportError("lbSetMatrixElem(mat, row, col, value): row or col out of bound"); HANDLE_ERROR } } lbBool lbMatrixSquare(const lbMatrix mat) { if (mat.nRow == mat.nCol && mat.nRow != 0) { return LB_TRUE; } else { return LB_FALSE; } } lbBool lbMatrixSameSize(const lbMatrix mat1, const lbMatrix mat2) { if (mat1.nRow == mat2.nRow && mat1.nCol == mat2.nCol) { return LB_TRUE; } else { return LB_FALSE; } } void lbMatrixCopy(const lbMatrix in, lbMatrix *out) { lbSize sz; if (!lbMatrixSameSize(in, *out)) { lm_reportError("lbMatrixCopy(in, out): in and out do not have the same size"); HANDLE_ERROR } sz = in.nRow * in.nCol; memcpy(out->data, in.data, sz * sizeof(lbScalar)); } void lbMatrixTranspose(const lbMatrix in, lbMatrix *out) { lbSize i, j; if (in.nRow != out->nCol || in.nCol != out->nRow) { lm_reportError("lbMatrixTranspose(in, out): the row or col of in and out matrix are not match"); HANDLE_ERROR return; } // #pragma omp parallel for private(i,j) for (i = 0; i < out->nRow; ++i) { for (j = 0; j < out->nCol; ++j) { out->data[PMATRIX_INDEX(out, i, j)] = in.data[MATRIX_INDEX(in, j, i)]; } } } void lbMatrixAddition(const lbMatrix matL, const lbMatrix matR, lbMatrix *out) { lbSize i, sz; if (!lbMatrixSameSize(matL, matR) || !lbMatrixSameSize(matL, *out)) { lm_reportError("lbMatrixAddition(matL, matR, out): matL, matR and out do not have the same size"); HANDLE_ERROR return; } sz = matL.nRow * matL.nCol; // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = matL.data[i] + matR.data[i]; } } void lbMatrixSubtraction(const lbMatrix matL, const lbMatrix matR, lbMatrix *out) { lbSize i, sz; if (!lbMatrixSameSize(matL, matR) || !lbMatrixSameSize(matL, *out)) { lm_reportError("lbMatrixSubtraction(matL, matR, out): matL, matR and out do not have the same size"); HANDLE_ERROR return; } sz = matL.nRow * matL.nCol; // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = matL.data[i] - matR.data[i]; } } void lbVectorMatrixMultiply(const lbVector vec, const lbMatrix mat, lbVector *out) { lbSize i, j; lbScalar sum; if (vec.size != mat.nRow) { lm_reportError("lbVectorMatrixMultiply(vec, mat, out): the size of vec does not " "match the number of rows of the matrix"); HANDLE_ERROR return; } if (out->size != mat.nCol) { lm_reportError("lbVectorMatrixMultiply(vec, mat, out): size of out does not match " "the number of columns of the matrix"); HANDLE_ERROR return; } // #pragma omp parallel for private(i,j) for (i = 0; i < out->size; ++i) { sum = 0; for (j = 0; j < vec.size; ++j) { sum += vec.data[j] * mat.data[MATRIX_INDEX(mat, j, i)]; } out->data[i] = sum; } } void lbVectorMatrixProduct(const lbVector vec, const lbMatrix mat, lbMatrix *out) { lbSize i, j; if (vec.size != mat.nRow) { lm_reportError("lbVectorMatrixMultiply(vec, mat, out): the size of vec does not " "match the number of rows of the matrix"); HANDLE_ERROR return; } if (!lbMatrixSameSize(mat, *out)) { lm_reportError("lbVectorMatrixProduct(vec, mat, *out): mat and out matrix do not have same size"); HANDLE_ERROR } // #pragma omp parallel for private(i,j) for (i = 0; i < mat.nRow; ++i) { for (j = 0; j < mat.nCol; ++j) { out->data[PMATRIX_INDEX(out, i, j)] = vec.data[i] * mat.data[MATRIX_INDEX(mat, i, j)]; } } } void lbMatrixVectorMultiply(const lbMatrix mat, const lbVector vec, lbVector *out) { lbSize i, j; lbScalar sum; if (mat.nCol != vec.size) { lm_reportError("lbMatrixVectorMultiply(vec, mat, out): the size of vec does not " "match the number of columns of the matrix"); HANDLE_ERROR return; } if (out->size != mat.nRow) { lm_reportError("lbVectorMatrixMultiply(vec, mat, out): size of out does not match " "the number of rows of the matrix"); HANDLE_ERROR return; } // #pragma omp parallel for private(i,j) for (i = 0; i < out->size; ++i) { sum = 0; for (j = 0; j < mat.nCol; ++j) { sum += mat.data[MATRIX_INDEX(mat, i, j)] * vec.data[j]; } out->data[i] = sum; } } void lbMatrixMultiply(const lbMatrix left, const lbMatrix right, lbMatrix *out) { lbSize i, j, k; lbScalar sum; if (left.nCol != right.nRow) { lm_reportError("lbMatrixMultiply(left, right, out): the number of columns of left does not match" "the number of rows of right"); HANDLE_ERROR return; } if (out->nRow != left.nRow) { lm_reportError("lbMatrixMultiply(left, right, out): the number of rows of out does not match " "the number of rows of left"); HANDLE_ERROR; return; } if (out->nCol != right.nCol) { lm_reportError("lbMatrixMultiply(left, right, out): the number of columns of out does not match " "the number of columns of right"); HANDLE_ERROR; return; } // #pragma omp parallel for private(i,j,k) for (i = 0; i < left.nRow; ++i) { for (j = 0; j < right.nCol; ++j) { sum = 0; for (k = 0; k < left.nCol; ++k) { sum += left.data[MATRIX_INDEX(left, i, k)] * right.data[MATRIX_INDEX(right, k, j)]; } out->data[PMATRIX_INDEX(out, i, j)] = sum; } } } void lbMatrixColSum(const lbMatrix mat, lbVector *out) { lbSize i, j; lbScalar sum; if (out->size != mat.nCol) { lm_reportError("lbMatrixColSum(mat, out): size of out does not match " "the number of cols of the matrix"); HANDLE_ERROR; return; } // #pragma omp parallel for private(i,j) for (i = 0; i < mat.nCol; ++i) { sum = 0; for (j = 0; j < mat.nRow; ++j) { sum += mat.data[MATRIX_INDEX(mat, j, i)]; } out->data[i] = sum; } } void lbMatrixBiForeach(const lbMatrix mat1, const lbMatrix mat2, lbMatrix *out, lbBinaryOperation biOper, void *params) { lbSize i, sz; if (!lbMatrixSameSize(mat1, mat2) || !lbMatrixSameSize(mat1, *out)) { lm_reportError("lbMatrixBiForeach(mat1, mat2, out): mat1, mat2 and out do not have the same size"); HANDLE_ERROR return; } sz = mat1.nRow * mat1.nCol; // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { out->data[i] = biOper(mat1.data[i], mat2.data[i], params); } } void lbMatrixSetDiag(lbMatrix *mat, const lbVector values) { lbSize i, sz; if ( !lbMatrixSquare(*mat) ) { lm_reportError("lbMatrixSetDiag(mat, value): mat should be a square matrix"); HANDLE_ERROR return; } sz = lbVectorSize(values); if (sz != mat->nRow) { lm_reportError("lbMatrixSetDiag(mat, values): size of values does match the " "demension of mat"); HANDLE_ERROR return; } memset(mat->data, 0, mat->nRow * mat->nCol * sizeof(lbScalar)); // #pragma omp parallel for private(i) for (i = 0; i < sz; ++i) { mat->data[PMATRIX_INDEX(mat, i, i)] = values.data[i]; } } void lbMatrixClearDiag(lbMatrix *mat, lbScalar value) { lbSize i; if ( !lbMatrixSquare(*mat) ) { lm_reportError("lbMatrixSetDiag(mat, value): mat should be a square matrix"); HANDLE_ERROR return; } memset(mat->data, 0, mat->nRow * mat->nCol * sizeof(lbScalar)); // #pragma omp parallel for private(i) for (i = 0; i < mat->nRow; ++i) { mat->data[PMATRIX_INDEX(mat, i, i)] = value; } }
GB_binop__eq_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__eq_uint64 // A.*B function (eWiseMult): GB_AemultB__eq_uint64 // A*D function (colscale): GB_AxD__eq_uint64 // D*A function (rowscale): GB_DxB__eq_uint64 // C+=B function (dense accum): GB_Cdense_accumB__eq_uint64 // C+=b function (dense accum): GB_Cdense_accumb__eq_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__eq_uint64 // C=scalar+B GB_bind1st__eq_uint64 // C=scalar+B' GB_bind1st_tran__eq_uint64 // C=A+scalar GB_bind2nd__eq_uint64 // C=A'+scalar GB_bind2nd_tran__eq_uint64 // C type: bool // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ 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) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x == y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_UINT64 || GxB_NO_EQ_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__eq_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__eq_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__eq_uint64 ( 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 uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__eq_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__eq_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__eq_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__eq_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__eq_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__eq_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = Ax [p] ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB_bind1st_tran__eq_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB_bind2nd_tran__eq_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
solver.h
#include "mesh.h" #include "arap.h" #include "elastic.h" #include <LBFGS.h> using namespace LBFGSpp; using json = nlohmann::json; using namespace Eigen; using namespace std; class Rosenbrock { private: int n; Mesh* mesh; Arap* arap; Elastic* elas; double alpha_arap = 1; double alpha_neo = 1; double eps = 1.5e-8; bool stest = false; public: Rosenbrock(int n_, Mesh* m, Arap* a, Elastic* e, json& j_input, bool test=false) : n(n_) { mesh = m; arap = a; elas = e; alpha_arap = j_input["alpha_arap"]; alpha_neo = j_input["alpha_neo"]; stest = test; } VectorXd get_w(VectorXd& r0, VectorXd& r){ VectorXd w = VectorXd::Zero(r0.size()/3); for(int i=0; i<r0.size()/9; i++){ Matrix3d R0, R; R0<<r0[9*i+0],r0[9*i+1],r0[9*i+2], r0[9*i+3],r0[9*i+4],r0[9*i+5], r0[9*i+6],r0[9*i+7],r0[9*i+8]; R<<r[9*i+0],r[9*i+1],r[9*i+2], r[9*i+3],r[9*i+4],r[9*i+5], r[9*i+6],r[9*i+7],r[9*i+8]; Matrix3d exp_brac_w = R0.transpose()*R; Matrix3d brac_w = exp_brac_w.log(); w[3*i+0] = brac_w(2,1); w[3*i+1] = brac_w(0,2); w[3*i+2] = brac_w(1,0); } return w; } //CHECK E,x------------- VectorXd Ex(Mesh& mesh, Arap& arap, double E0, double eps){ VectorXd z = mesh.red_x(); VectorXd fake = VectorXd::Zero(z.size()); #pragma omp parallel for for(int i=0; i<fake.size(); i++){ z[i] += 0.5*eps; double Eleft = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] -= 0.5*eps; z[i] -= 0.5*eps; double Eright = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] += 0.5*eps; fake[i] = (Eleft - Eright)/eps; } return fake; } //----------------------- //CHECK E,r------------- VectorXd Er(Mesh& mesh, Arap& arap, double E0, double eps){ VectorXd z = mesh.red_x(); VectorXd fake = VectorXd::Zero(mesh.red_w().size()); for(int i=0; i<fake.size(); i++){ mesh.red_w()[i] += 0.5*eps; // mesh.setGlobalF(true, false, false); double Eleft = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[i] -= 0.5*eps; mesh.red_w()[i] -= 0.5*eps; // mesh.setGlobalF(true, false, false); double Eright = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[i] += 0.5*eps; fake[i] = (Eleft - Eright)/(eps); } // mesh.setGlobalF(true, false, false); return fake; } //----------------------- //CHECK E,s------------- VectorXd Es(Mesh& mesh, Arap& arap, double E0, double eps){ VectorXd z = mesh.red_x(); VectorXd fake = VectorXd::Zero(mesh.red_s().size()); for(int i=0; i<fake.size(); i++){ mesh.red_s()[i] += 0.5*eps; // mesh.setGlobalF(false, true, false); double Eleft = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[i] -= 0.5*eps; mesh.red_s()[i] -= 0.5*eps; // mesh.setGlobalF(false, true, false); double Eright = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[i] += 0.5*eps; fake[i] = (Eleft - Eright)/eps; } // mesh.setGlobalF(false, true, false); return fake; } //----------------------- //CHECK Exx-------------- MatrixXd Exx(Mesh& mesh, Arap& arap, double E0, double eps){ MatrixXd fake = MatrixXd::Zero(mesh.red_x().size(), mesh.red_x().size()); VectorXd z = mesh.red_x(); for(int i=0; i<fake.rows(); i++){ for(int j=0; j<fake.cols(); j++){ z[i] += eps; z[j] += eps; double Eij = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] -= eps; z[j] -= eps; z[i] += eps; double Ei = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] -= eps; z[j] += eps; double Ej = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[j] -= eps; fake(i,j) = ((Eij - Ei - Ej + E0)/(eps*eps)); } } return fake; } //----------------------- //CHECK Exr/Erx------------- MatrixXd Exr(Mesh& mesh, Arap& arap, double E0, double eps){ MatrixXd fake = MatrixXd::Zero(mesh.red_x().size(), mesh.red_w().size()); VectorXd z = mesh.red_x(); for(int i=0; i<fake.rows(); i++){ for(int j=0; j<fake.cols(); j++){ mesh.red_w()[j] += eps; z[i] += eps; // mesh.setGlobalF(true, false, false); double Eij = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[j] -= eps; z[i] -= eps; mesh.red_w()[j] += eps; // mesh.setGlobalF(true, false, false); double Ei = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[j] -= eps; z[i] += eps; // mesh.setGlobalF(true, false, false); double Ej = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] -= eps; fake(i,j) = ((Eij - Ei - Ej + E0)/(eps*eps)); } } // mesh.setGlobalF(true, false, false); return fake; } //----------------------- //CHECK Exs------------- MatrixXd Exs(Mesh& mesh, Arap& arap, double E0, double eps){ MatrixXd fake = MatrixXd::Zero(mesh.red_x().size(), mesh.red_s().size()); VectorXd z = mesh.red_x(); for(int i=0; i<fake.rows(); i++){ for(int j=0; j<fake.cols(); j++){ mesh.red_s()[j] += eps; z[i] += eps; // mesh.setGlobalF(false, true, false); double Eij = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[j] -= eps; z[i] -= eps; mesh.red_s()[j] += eps; // mesh.setGlobalF(false, true, false); double Ei = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[j] -= eps; z[i] += eps; // mesh.setGlobalF(false, true, false); double Ej = arap.Energy(mesh, z, mesh.red_w(), mesh.red_r(), mesh.red_s()); z[i] -= eps; fake(i,j) = ((Eij - Ei - Ej + E0)/(eps*eps)); } } // mesh.setGlobalF(false, true, false); return fake; } //----------------------- //CHECK Err-------------- MatrixXd Err(Mesh& mesh, Arap& arap, double E0, double eps){ MatrixXd fake = MatrixXd::Zero(mesh.red_w().size(), mesh.red_w().size()); for(int i=0; i<fake.rows(); i++){ for(int j=0; j<fake.cols(); j++){ mesh.red_w()[j] += eps; mesh.red_w()[i] += eps; // mesh.setGlobalF(true, false, false); double Eij = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[j] -= eps; mesh.red_w()[i] -= eps; mesh.red_w()[j] += eps; // mesh.setGlobalF(true, false, false); double Ei = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[j] -= eps; mesh.red_w()[i] += eps; // mesh.setGlobalF(true, false, false); double Ej = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[i] -= eps; fake(i,j) = ((Eij - Ei - Ej + E0)/(eps*eps)); } } // mesh.setGlobalF(true, false, false); return fake; } //----------------------- //CHECK Ers-------------- MatrixXd Ers(Mesh& mesh, Arap& arap, double E0, double eps){ MatrixXd fake = MatrixXd::Zero(mesh.red_w().size(), mesh.red_s().size()); for(int i=0; i<fake.rows(); i++){ for(int j=0; j<fake.cols(); j++){ mesh.red_w()[i] += eps; mesh.red_s()[j] += eps; // mesh.setGlobalF(true, true, false); double Eij = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[j] -= eps; mesh.red_w()[i] -= eps; mesh.red_w()[i] += eps; // mesh.setGlobalF(true, true, false); double Ei = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_w()[i] -= eps; mesh.red_s()[j] += eps; // mesh.setGlobalF(true, true, false); double Ej = arap.Energy(mesh, mesh.red_x(), mesh.red_w(), mesh.red_r(), mesh.red_s()); mesh.red_s()[j] -= eps; fake(i,j) = ((Eij - Ei - Ej + E0)/(eps*eps)); } } // mesh.setGlobalF(true, true, false); return fake; } //----------------------- VectorXd Full_ARAP_Grad(Mesh& mesh, Arap& arap, Elastic& elas, double E0, double eps){ VectorXd fake = VectorXd::Zero(mesh.red_s().size()); for(int i=0; i<fake.size(); i++){ mesh.red_s()[i] += 0.5*eps; // mesh.setGlobalF(false, true, false); arap.minimize(mesh); double Eleft = alpha_arap*arap.Energy(mesh); mesh.red_s()[i] -= 0.5*eps; mesh.red_s()[i] -= 0.5*eps; // mesh.setGlobalF(false, true, false); arap.minimize(mesh); double Eright = alpha_arap*arap.Energy(mesh); mesh.red_s()[i] += 0.5*eps; fake[i] = (Eleft - Eright)/eps; } arap.minimize(mesh); // mesh.setGlobalF(false, true, false); // std::cout<<"FUll fake: "<<fake.transpose()<<std::endl; return fake; } // VectorXd Full_NEO_Grad(Mesh& mesh, Arap& arap, Elastic& elas, double E0, double eps){ // VectorXd fake = VectorXd::Zero(mesh.red_s().size()); // for(int i=0; i<fake.size(); i++){ // mesh.red_s()[i] += 0.5*eps; // // mesh.setGlobalF(false, true, false); // double Eleft = alpha_neo*elas.Energy(mesh); // mesh.red_s()[i] -= 0.5*eps; // mesh.red_s()[i] -= 0.5*eps; // // mesh.setGlobalF(false, true, false); // double Eright = alpha_neo*elas.Energy(mesh); // mesh.red_s()[i] += 0.5*eps; // fake[i] = (Eleft - Eright)/eps; // } // // mesh.setGlobalF(false, true, false); // // std::cout<<"FUll fake: "<<fake.transpose()<<std::endl; // return fake; // } VectorXd WikipediaEnergy_grad(Mesh& mesh, Elastic& elas, double eps){ VectorXd fake = VectorXd::Zero(mesh.red_s().size()); for(int i=0; i<fake.size(); i++){ mesh.red_s()[i] += 0.5*eps; double Eleft = elas.WikipediaEnergy(mesh); mesh.red_s()[i] -= 0.5*eps; mesh.red_s()[i] -= 0.5*eps; double Eright = elas.WikipediaEnergy(mesh); mesh.red_s()[i] += 0.5*eps; fake[i] = (Eleft - Eright)/eps; } // mesh.setGlobalF(false, true, false); // std::cout<<"FUll fake: "<<fake.transpose()<<std::endl; return fake; } double operator()(const VectorXd& x, VectorXd& grad, bool computeGrad = true) { VectorXd reds = mesh->N()*x + mesh->AN()*mesh->AN().transpose()*mesh->red_s(); for(int i=0; i<reds.size(); i++){ mesh->red_s()[i] = reds[i]; } double Eneo = alpha_neo*elas->Energy(*mesh); int arap_iters = arap->minimize(*mesh); double Earap = alpha_arap*arap->Energy(*mesh); double fx = Eneo + Earap; if(computeGrad){ VectorXd pegrad = alpha_neo*mesh->N().transpose()*elas->PEGradient(*mesh); VectorXd arapgrad = alpha_arap*mesh->N().transpose()*arap->Jacobians(*mesh); if(stest){ VectorXd fake_arap = mesh->N().transpose()*Full_ARAP_Grad(*mesh, *arap,*elas, fx, eps); if ((arapgrad-fake_arap).norm()>10){ double E0 = arap->Energy(*mesh); std::cout<<"fake arap issues"<<std::endl; std::cout<<arapgrad.transpose()<<std::endl<<std::endl; std::cout<<fake_arap.transpose()<<std::endl<<std::endl; cout<<"s"<<endl; std::cout<<x.transpose()<<endl<<endl; cout<<"r"<<endl; cout<<mesh->red_r().transpose()<<endl<<endl; cout<<"x"<<endl; cout<<mesh->red_x().transpose()<<endl<<endl; cout<<"-------------------------------------"<<endl; cout<<"Ex"<<endl; VectorXd fakeEx = Ex(*mesh, *arap, E0, eps); cout<<(arap->Ex().transpose()-fakeEx.transpose()).norm()<<endl<<endl; cout<<"Er"<<endl; VectorXd fakeEr = Er(*mesh, *arap, E0, eps); cout<<(arap->Er().transpose()-fakeEr.transpose()).norm()<<endl<<endl; cout<<"Es"<<endl; VectorXd fakeEs = Es(*mesh, *arap,E0, eps); cout<<(arap->Es().transpose() - fakeEs.transpose()).norm()<<endl<<endl; MatrixXd fakeExx = Exx(*mesh, *arap, E0, eps); cout<<"Exx"<<endl; cout<<(fakeExx-MatrixXd(arap->Exx())).norm()<<endl<<endl; cout<<endl<<endl; MatrixXd fakeExr = Exr(*mesh, *arap, E0, eps); cout<<"Exr"<<endl; cout<<(fakeExr-MatrixXd(arap->Exr())).norm()<<endl<<endl; cout<<endl<<endl; cout<<"Exs"<<endl; MatrixXd fakeExs = Exs(*mesh, *arap, E0, eps); cout<<(fakeExs-MatrixXd(arap->Exs())).norm()<<endl<<endl; cout<<endl; cout<<"Err"<<endl; MatrixXd fakeErr = Err(*mesh, *arap, E0, eps); cout<<(fakeErr-MatrixXd(arap->Err())).norm()<<endl<<endl; cout<<endl; cout<<"Ers"<<endl; MatrixXd fakeErs = Ers(*mesh, *arap, E0, eps); cout<<(fakeErs-MatrixXd(arap->Ers())).norm()<<endl<<endl; cout<<endl; exit(0); } } // VectorXd fake = alpha_neo*WikipediaEnergy_grad(*mesh, *elas, 1e-5); // if ((pegrad-fake_neo).norm()>0.001){ // std::cout<<"fake physics issues"<<std::endl; // std::cout<<x.transpose()<<std::endl; // std::cout<<arapgrad.transpose()<<std::endl<<std::endl; // std::cout<<fake_neo.transpose()<<std::endl<<std::endl; // exit(0); // } for(int i=0; i< x.size(); i++){ grad[i] = pegrad[i]; grad[i] += arapgrad[i]; } std::cout<<"BFGS: "<<Eneo<<", "<<Earap<<", "<<pegrad.norm()<<", "<<arapgrad.norm()<<","<<grad.norm()<<std::endl; cout<< arapgrad.transpose()<<endl; } return fx; } };
lca_comms.h
/* //@HEADER // ***************************************************************************** // // XtraPuLP: Xtreme-Scale Graph Partitioning using Label Propagation // Copyright (2016) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact George M. Slota (gmslota@sandia.gov) // Siva Rajamanickam (srajama@sandia.gov) // Kamesh Madduri (madduri@cse.psu.edu) // // ***************************************************************************** //@HEADER */ #ifndef _LCA_COMMS_H_ #define _LCA_COMMS_H_ #include <mpi.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include "comms.h" #include "bicc_dist.h" #include "util.h" extern int procid, nprocs; extern bool verbose, debug, verify; #define MAX_SEND_SIZE 2147483648 #define LCA_THREAD_QUEUE_SIZE 6144 struct lca_thread_data_t { int32_t tid; uint64_t* thread_queue; uint64_t* thread_finish; uint64_t thread_queue_size; uint64_t thread_finish_size; }; struct lca_queue_data_t { uint64_t* queue; uint64_t* queue_next; uint64_t* finish; uint64_t queue_size; uint64_t next_size; uint64_t finish_size; uint64_t queue_length; }; inline void init_queue_lca(dist_graph_t* g, lca_queue_data_t* lcaq){ if (debug) { printf("Task %d init_queue_lca() start\n", procid);} lcaq->queue_length = g->m_local*10;//g->n_local + g->n_ghost; lcaq->queue = (uint64_t*)malloc(lcaq->queue_length*sizeof(uint64_t)); lcaq->queue_next = (uint64_t*)malloc(lcaq->queue_length*sizeof(uint64_t)); lcaq->finish = (uint64_t*)malloc(10); if (lcaq->queue == NULL || lcaq->queue_next == NULL || lcaq->finish == NULL) throw_err("init_queue_lca(), unable to allocate resources\n",procid); lcaq->queue_size = 0; lcaq->next_size = 0; lcaq->finish_size = 0; if(debug){printf("Task %d init_queue_lca() success\n", procid); } } inline void clear_queue_lca(lca_queue_data_t* lcaq){ if(debug){ printf("Task %d clear_queue_lca() start\n",procid); } free(lcaq->queue); free(lcaq->queue_next); free(lcaq->finish); if(debug) {printf("Task %d clear_queue_lca() success\n", procid); } } inline void init_thread_lca(lca_thread_data_t* lcat) { if (debug) { printf("Task %d init_thread_queue() start\n", procid);} lcat->tid = omp_get_thread_num(); lcat->thread_queue = (uint64_t*)malloc(LCA_THREAD_QUEUE_SIZE*sizeof(uint64_t)); lcat->thread_finish = (uint64_t*)malloc(LCA_THREAD_QUEUE_SIZE*sizeof(uint64_t)); if (lcat->thread_queue == NULL || lcat->thread_finish == NULL) throw_err("init_thread_lca(), unable to allocate resources\n", procid, lcat->tid); lcat->tid = omp_get_thread_num(); lcat->thread_queue_size = 0; lcat->thread_finish_size = 0; if (debug) {printf("Task %d init_thread_queue() success\n", procid); } } inline void clear_thread_lca(lca_thread_data_t* lcat){ free(lcat->thread_queue); free(lcat->thread_finish); } inline void init_sendbuf_lca(mpi_data_t* comm){ comm->sdispls_temp[0] = 0; comm->total_send = comm->sendcounts_temp[0]; for (int32_t i = 1; i < nprocs; ++i){ comm->sdispls_temp[i] = comm->sdispls_temp[i-1] + comm->sendcounts_temp[i-1]; comm->total_send += comm->sendcounts_temp[i]; } if (debug) printf("Task %d total_send %lu\n", procid, comm->total_send); comm->sendbuf_vert = (uint64_t*)malloc(comm->total_send*sizeof(uint64_t)); if (comm->sendbuf_vert == NULL) throw_err("init_sendbuf_lca(), unable to allocate resources\n", procid); } inline void clear_recvbuf_lca(mpi_data_t* comm){ free(comm->recvbuf_vert); for (int32_t i = 0; i < nprocs; ++i) comm->sendcounts[i] = 0; for (int32_t i = 0; i < nprocs; ++i) comm->sendcounts_temp[i] = 0; } inline void add_to_lca(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1, uint64_t vert2, uint64_t pred2, uint64_t level2); inline void empty_lca_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq); inline void add_to_lca_bridge( lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert); inline void empty_lca_queue_bridge( lca_thread_data_t* lcat, lca_queue_data_t* lcaq); // inline void add_to_finish(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, // uint64_t vert1, uint64_t pred1, uint64_t level1); // inline void empty_finish_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq); inline void update_lca_send( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); inline void empty_lca_send( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq); inline void update_lca_send_bridge( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); inline void empty_lca_send_bridge( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq); // inline void update_lca_finish(dist_graph_t* g, // thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); //(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); // inline void empty_lca_finish(dist_graph_t* g, // thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq); inline void exchange_lca(dist_graph_t* g, mpi_data_t* comm); inline void add_to_lca(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1, uint64_t vert2, uint64_t pred2, uint64_t level2) { lcat->thread_queue[lcat->thread_queue_size++] = vert1; lcat->thread_queue[lcat->thread_queue_size++] = pred1; lcat->thread_queue[lcat->thread_queue_size++] = level1; lcat->thread_queue[lcat->thread_queue_size++] = vert2; lcat->thread_queue[lcat->thread_queue_size++] = pred2; lcat->thread_queue[lcat->thread_queue_size++] = level2; if (lcat->thread_queue_size+6 >= LCA_THREAD_QUEUE_SIZE) empty_lca_queue(lcat, lcaq); } inline void empty_lca_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq) { uint64_t start_offset; #pragma omp atomic capture start_offset = lcaq->next_size += lcat->thread_queue_size; start_offset -= lcat->thread_queue_size; for (uint64_t i = 0; i < lcat->thread_queue_size; ++i) lcaq->queue_next[start_offset + i] = lcat->thread_queue[i]; lcat->thread_queue_size = 0; } inline void add_to_lca_bridge( lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert) { lcat->thread_queue[lcat->thread_queue_size++] = vert; if (lcat->thread_queue_size+1 >= LCA_THREAD_QUEUE_SIZE) empty_lca_queue_bridge(lcat, lcaq); } inline void empty_lca_queue_bridge( lca_thread_data_t* lcat, lca_queue_data_t* lcaq) { uint64_t start_offset; #pragma omp atomic capture start_offset = lcaq->next_size += lcat->thread_queue_size; start_offset -= lcat->thread_queue_size; for (uint64_t i = 0; i < lcat->thread_queue_size; ++i) lcaq->queue_next[start_offset + i] = lcat->thread_queue[i]; lcat->thread_queue_size = 0; } // inline void add_to_finish(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, // uint64_t vert1, uint64_t pred1, uint64_t level1) // { // lcat->thread_finish[lcat->thread_finish_size++] = vert1; // lcat->thread_finish[lcat->thread_finish_size++] = pred1; // lcat->thread_finish[lcat->thread_finish_size++] = level1; // if (lcat->thread_finish_size+3 >= LCA_THREAD_QUEUE_SIZE) // empty_finish_queue(lcat, lcaq); // } // inline void empty_finish_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq) // { // uint64_t start_offset; // #pragma omp atomic capture // start_offset = lcaq->finish_size += lcat->thread_finish_size; // start_offset -= lcat->thread_finish_size; // for (uint64_t i = 0; i < lcat->thread_finish_size; ++i) // lcaq->finish[start_offset + i] = lcat->thread_finish[i]; // lcat->thread_finish_size = 0; // } inline void update_lca_send( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) { tc->sendbuf_rank_thread[tc->thread_queue_size/6] = send_rank; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+1]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+2]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+3]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+4]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+5]; //++tc->thread_queue_size; //++tc->sendcounts_thread[send_rank]; if (tc->thread_queue_size+6 >= LCA_THREAD_QUEUE_SIZE) empty_lca_send(tc, comm, lcaq); } inline void empty_lca_send( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; i+=6) { int32_t cur_rank = tc->sendbuf_rank_thread[i/6]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+1] = tc->sendbuf_vert_thread[i+1]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+2] = tc->sendbuf_vert_thread[i+2]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+3] = tc->sendbuf_vert_thread[i+3]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+4] = tc->sendbuf_vert_thread[i+4]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+5] = tc->sendbuf_vert_thread[i+5]; tc->thread_starts[cur_rank] += 6; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } inline void update_lca_send_bridge( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) { tc->sendbuf_rank_thread[tc->thread_queue_size] = send_rank; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index]; if (tc->thread_queue_size+1 >= LCA_THREAD_QUEUE_SIZE) empty_lca_send_bridge(tc, comm, lcaq); } inline void empty_lca_send_bridge( thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; ++i) { int32_t cur_rank = tc->sendbuf_rank_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; tc->thread_starts[cur_rank] += 1; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } // inline void update_lca_finish(dist_graph_t* g, // thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) // { // // for (int32_t i = 0; i < nprocs; ++i) // // tc->v_to_rank[i] = false; // // uint64_t out_degree = out_degree(g, vert_index); // // uint64_t* outs = out_vertices(g, vert_index); // // for (uint64_t j = 0; j < out_degree; ++j) // // { // // uint64_t out_index = outs[j]; // // if (out_index >= g->n_local) // // { // // int32_t out_rank = g->ghost_tasks[out_index - g->n_local]; // // if (!tc->v_to_rank[out_rank]) // // { // // tc->v_to_rank[out_rank] = true; // // add_vid_data_to_send(tc, comm, // // g->local_unmap[vert_index], data, out_rank); // // } // // } // // } // //tc->sendbuf_rank_thread[tc->thread_queue_size/3] = send_rank; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index+1]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index+2]; // //++tc->thread_queue_size; // //++tc->sendcounts_thread[send_rank]; // if (tc->thread_queue_size+6 >= LCA_THREAD_QUEUE_SIZE) // empty_lca_finish(g, tc, comm, lcaq); // } // inline void add_data_to_finish(thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) // { // tc->sendbuf_rank_thread[tc->thread_queue_size/3] = send_rank; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+1]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+2]; // ++tc->thread_queue_size; // ++tc->sendcounts_thread[send_rank]; // if (tc->thread_queue_size+3 >= LCA_THREAD_QUEUE_SIZE) // empty_lca_finish(tc, comm, lcaq); // } // inline void empty_lca_finish(dist_graph_t* g, // thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq) // { // for (int32_t i = 0; i < nprocs; ++i) // { // #pragma omp atomic capture // tc->thread_starts[i] = comm->sdispls_temp[i] += tc->sendcounts_thread[i]; // tc->thread_starts[i] -= tc->sendcounts_thread[i]; // } // for (uint64_t i = 0; i < tc->thread_queue_size; i+=3) // { // int32_t cur_rank = get_rank(g, tc->sendbuf_vert_thread[i]); // comm->sendbuf_vert[tc->thread_starts[cur_rank]] = // tc->sendbuf_vert_thread[i]; // comm->sendbuf_vert[tc->thread_starts[cur_rank]+1] = // tc->sendbuf_vert_thread[i+1]; // comm->sendbuf_vert[tc->thread_starts[cur_rank]+2] = // tc->sendbuf_vert_thread[i+2]; // tc->thread_starts[cur_rank] += 3; // } // for (int32_t i = 0; i < nprocs; ++i) // { // tc->thread_starts[i] = 0; // tc->sendcounts_thread[i] = 0; // } // tc->thread_queue_size = 0; // } inline void exchange_lca(dist_graph_t* g, mpi_data_t* comm) { for (int32_t i = 0; i < nprocs; ++i) comm->recvcounts_temp[i] = 0; for (int32_t i = 0; i < nprocs; ++i) comm->sdispls_temp[i] -= comm->sendcounts_temp[i]; MPI_Alltoall(comm->sendcounts_temp, 1, MPI_UINT64_T, comm->recvcounts_temp, 1, MPI_UINT64_T, MPI_COMM_WORLD); comm->total_recv = 0; for (int i = 0; i < nprocs; ++i) comm->total_recv += comm->recvcounts_temp[i]; if (debug) printf("Task %d total_recv %lu\n", procid, comm->total_recv); comm->recvbuf_vert = (uint64_t*)malloc(comm->total_recv*sizeof(uint64_t)); if (comm->recvbuf_vert == NULL) throw_err("exchange_lca() unable to allocate recv buffers", procid); uint64_t task_queue_size = comm->total_send; uint64_t current_global_size = 0; MPI_Allreduce(&task_queue_size, &current_global_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); uint64_t num_comms = current_global_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; uint64_t* buf_v = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); if (buf_v == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { uint64_t data = comm->sendbuf_vert[comm->sdispls_temp[i]+j]; buf_v[comm->sdispls_cpy[i]++] = data; } } MPI_Alltoallv(buf_v, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_vert+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(buf_v); sum_recv += cur_recv; sum_send += cur_send; } free(comm->sendbuf_vert); assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); } #endif
lockarray.c
/* test fine grained locks instead of critical section by Chunhua Liao */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #define LOCKNUM 100 #endif #define SIZE 5000 int main(void) { int a[SIZE]; int i,j,sum,lock_index; #ifdef _OPENMP omp_lock_t lck[LOCKNUM]; for (i=0;i<LOCKNUM;i++) omp_init_lock(&(lck[i])); #endif for (i=0;i<SIZE;i++) a[i]=0; #pragma omp parallel private (i,j,lock_index) { /*critical version*/ #pragma omp for schedule(dynamic,1) for (i=0;i<SIZE;i++) { j=(i*i)%SIZE; #pragma omp critical { a[j]=a[j]+5; } } /* fine grained lock version*/ #pragma omp for schedule(dynamic,1) for (i=0;i<SIZE;i++) { j=(i*i)%SIZE; #ifdef _OPENMP lock_index= j%LOCKNUM; // omp_set_lock(lck[lock_index]); #endif a[j]=a[j]-5; #ifdef _OPENMP // omp_unset_lock(lck[lock_index]); #endif } /*verify the result*/ sum=0; #pragma omp for reduction (+:sum) for (i=0;i<SIZE;i++) { sum+=a[i]; } } /* destroy locks*/ #ifdef _OPENMP for (i=0;i<LOCKNUM;i++) omp_destroy_lock(&(lck[i])); #endif printf("sum of a[] = %d\n",sum); }
ompfor7.c
/* * test #define * Liao 12/1/2010 */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif #define P 4 void foo(int iend, int ist) { int i=0; i= i+P; #pragma omp parallel { #pragma omp single printf ("Using %d threads.\n",omp_get_num_threads()); #pragma omp for nowait schedule(static,P) for (i=iend;i>=ist;i--) { printf("Iteration %d is carried out by thread %d\n",i, omp_get_thread_num()); } } }
depthwise_conv2d.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_DEPTHWISE_CONV2D_H_ #define MACE_KERNELS_DEPTHWISE_CONV2D_H_ #if defined(MACE_ENABLE_NEON) && defined(__aarch64__) #include <arm_neon.h> #endif #include <algorithm> #include <memory> #include <vector> #include "mace/core/future.h" #include "mace/kernels/conv_pool_2d_util.h" #include "mace/kernels/activation.h" #include "mace/kernels/arm/depthwise_conv2d_neon.h" #include "mace/public/mace.h" #ifdef MACE_ENABLE_OPENCL #include "mace/core/runtime/opencl/cl2_header.h" #endif // MACE_ENABLE_OPENCL namespace mace { namespace kernels { struct DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctorBase(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : strides_(strides), padding_type_(padding_type), paddings_(paddings), dilations_(dilations), activation_(activation), relux_max_limit_(relux_max_limit) {} const int *strides_; // [stride_h, stride_w] const Padding padding_type_; std::vector<int> paddings_; const int *dilations_; // [dilation_h, dilation_w] const ActivationType activation_; const float relux_max_limit_; }; template<DeviceType D, typename T> struct DepthwiseConv2dFunctor; template<> struct DepthwiseConv2dFunctor<DeviceType::CPU, float> : public DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctor(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : DepthwiseConv2dFunctorBase(strides, padding_type, paddings, dilations, activation, relux_max_limit) {} void DepthwiseConv2dGeneral(const float *input, const float *filter, const index_t *in_shape, const index_t *out_shape, const index_t *filter_shape, const int *stride_hw, const int *dilation_hw, const int *pad_hw, float *output) { const index_t multiplier = filter_shape[0] / filter_shape[1]; #pragma omp parallel for collapse(2) for (index_t b = 0; b < in_shape[0]; ++b) { for (index_t m = 0; m < filter_shape[0]; ++m) { for (index_t h = 0; h < out_shape[2]; ++h) { for (index_t w = 0; w < out_shape[3]; ++w) { const index_t out_channels = filter_shape[0]; const index_t in_channels = filter_shape[1]; const index_t filter_height = filter_shape[2]; const index_t filter_width = filter_shape[3]; const index_t in_height = in_shape[2]; const index_t in_width = in_shape[3]; const index_t out_height = out_shape[2]; const index_t out_width = out_shape[3]; index_t out_offset = ((b * out_channels + m) * out_height + h) * out_width + w; index_t c = m / multiplier; index_t o = m % multiplier; float sum = 0; for (index_t kh = 0; kh < filter_height; ++kh) { for (index_t kw = 0; kw < filter_width; ++kw) { index_t ih = h * stride_hw[0] + kh * dilation_hw[0] - pad_hw[0]; index_t iw = w * stride_hw[1] + kw * dilation_hw[1] - pad_hw[1]; if (ih >= 0 && ih < in_height && iw >= 0 && iw < in_width) { index_t in_offset = ((b * in_channels + c) * in_height + ih) * in_width + iw; index_t filter_offset = (((o * in_channels) + c) * filter_height + kh) * filter_width + kw; sum += input[in_offset] * filter[filter_offset]; } } } output[out_offset] = sum; } } } } } MaceStatus operator()(const Tensor *input, const Tensor *filter, const Tensor *bias, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); MACE_CHECK_NOTNULL(input); MACE_CHECK_NOTNULL(filter); MACE_CHECK_NOTNULL(output); std::vector<index_t> output_shape(4); std::vector<int> paddings(2); std::vector<index_t> filter_shape {filter->dim(0) * filter->dim(1), filter->dim(1), filter->dim(2), filter->dim(3)}; if (paddings_.empty()) { CalcNCHWPaddingAndOutputSize(input->shape().data(), filter_shape.data(), dilations_, strides_, padding_type_, output_shape.data(), paddings.data()); } else { paddings = paddings_; CalcNCHWOutputSize(input->shape().data(), filter_shape.data(), paddings_.data(), dilations_, strides_, RoundType::FLOOR, output_shape.data()); } MACE_RETURN_IF_ERROR(output->Resize(output_shape)); output->Clear(); index_t batch = output->dim(0); index_t channels = output->dim(1); index_t height = output->dim(2); index_t width = output->dim(3); index_t input_batch = input->dim(0); index_t input_channels = input->dim(1); index_t input_height = input->dim(2); index_t input_width = input->dim(3); index_t filter_h = filter_shape[2]; index_t filter_w = filter_shape[3]; MACE_CHECK(filter_shape[0] == channels, filter_shape[0], " != ", channels); MACE_CHECK(filter_shape[1] == input_channels, filter_shape[1], " != ", input_channels); index_t stride_h = strides_[0]; index_t stride_w = strides_[1]; index_t dilation_h = dilations_[0]; index_t dilation_w = dilations_[1]; MACE_CHECK(batch == input_batch, "Input/Output batch size mismatch"); int pad_top = paddings[0] >> 1; int pad_bottom = paddings[0] - pad_top; int pad_left = paddings[1] >> 1; int pad_right = paddings[1] - pad_left; index_t valid_h_start = pad_top == 0 ? 0 : (pad_top - 1) / stride_h + 1; index_t valid_h_stop = pad_bottom == 0 ? height : height - ((pad_bottom - 1) / stride_h + 1); index_t valid_w_start = pad_left == 0 ? 0 : (pad_left - 1) / stride_w + 1; index_t valid_w_stop = pad_right == 0 ? width : width - ((pad_right - 1) / stride_w + 1); std::function<void(const float *input, float *output)> conv_func; Tensor::MappingGuard input_guard(input); Tensor::MappingGuard filter_guard(filter); Tensor::MappingGuard bias_guard(bias); Tensor::MappingGuard output_guard(output); auto input_data = input->data<float>(); auto filter_data = filter->data<float>(); auto bias_data = bias == nullptr ? nullptr : bias->data<float>(); auto output_data = output->mutable_data<float>(); const int pad_hw[2] = {pad_top, pad_left}; const index_t input_shape[4] = {batch, input_channels, input_height, input_width}; // make host compiler happy MACE_UNUSED(pad_hw); MACE_UNUSED(input_shape); if (filter_h == 3 && filter_w == 3 && stride_h == 1 && stride_w == 1 && dilation_h == 1 && dilation_w == 1) { conv_func = [=](const float *input, float *output) { DepthwiseConv2dNeonK3x3S1(input, filter_data, input_shape, output_shape.data(), pad_hw, valid_h_start, valid_h_stop, valid_w_start, valid_w_stop, output); }; } else if (filter_h == 3 && filter_w == 3 && stride_h == 2 && stride_w == 2 && dilation_h == 1 && dilation_w == 1) { conv_func = [=](const float *input, float *output) { DepthwiseConv2dNeonK3x3S2(input, filter_data, input_shape, output_shape.data(), pad_hw, valid_h_start, valid_h_stop, valid_w_start, valid_w_stop, output); }; } else { conv_func = [=](const float *input, float *output) { DepthwiseConv2dGeneral(input, filter_data, input_shape, output_shape.data(), filter_shape.data(), strides_, dilations_, pad_hw, output); }; } conv_func(input_data, output_data); if (bias_data != nullptr) { #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch; ++b) { for (index_t c = 0; c < channels; ++c) { for (index_t i = 0; i < height * width; ++i) { output_data[(b * channels + c) * height * width + i] += bias_data[c]; } } } } DoActivation(output_data, output_data, output->size(), activation_, relux_max_limit_); return MACE_SUCCESS; } }; #ifdef MACE_ENABLE_OPENCL template<typename T> struct DepthwiseConv2dFunctor<DeviceType::GPU, T> : DepthwiseConv2dFunctorBase { DepthwiseConv2dFunctor(const int *strides, const Padding padding_type, const std::vector<int> &paddings, const int *dilations, const ActivationType activation, const float relux_max_limit) : DepthwiseConv2dFunctorBase(strides, padding_type, paddings, dilations, activation, relux_max_limit) {} MaceStatus operator()(const Tensor *input, const Tensor *filter, const Tensor *bias, Tensor *output, StatsFuture *future); cl::Kernel kernel_; uint32_t kwg_size_; std::unique_ptr<BufferBase> kernel_error_; std::vector<index_t> input_shape_; }; #endif // MACE_ENABLE_OPENCL } // namespace kernels } // namespace mace #endif // MACE_KERNELS_DEPTHWISE_CONV2D_H_
scalability.c
/** * \file * \brief libbomp test. */ /* * Copyright (c) 2007, 2008, 2009, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. */ #include <stdio.h> #include <omp.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #ifdef POSIX static inline uint64_t rdtsc(void) { uint32_t eax, edx; __asm volatile ("rdtsc" : "=a" (eax), "=d" (edx)); return ((uint64_t)edx << 32) | eax; } #endif #define N 10000000 int main(int argc, char *argv[]) { uint64_t begin, end; int i; static int a[N]; assert(argc == 2); #ifndef POSIX bomp_bomp_init(atoi(argv[1])); #endif omp_set_num_threads(atoi(argv[1])); for (i=0;i<N;i++) a[i]= 2*i; begin = rdtsc(); #pragma omp parallel for for (i=0;i<N;i++) a[i]= 2*i; end = rdtsc(); printf("Value of sum is %d, time taken %lu\n", 0, end - begin); }
7.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> #define N 1000000 #define MAX_ITER 25 /* Ускорить выполнение цикла for в программе, вычисляющей покоординатную функцию от элементов массива a: a[i]=F(a[i]); */ float func(float element){ return element * element * element - element * 0.15; } int main() { srand(time(0)); float a[N]; float full_time = 0.; struct timeval start_s, end_s; for (int iter = 0; iter < MAX_ITER; iter++){ for (int i = 0; i < N; i++){ a[i] = (float)rand()/(float)RAND_MAX; } gettimeofday(&start_s, NULL); #pragma omp parallel for for (int i = 0; i < N; i++){ a[i] = func(a[i]); } gettimeofday(&end_s, NULL); full_time += ((end_s.tv_sec - start_s.tv_sec) * 1000000u + end_s.tv_usec - start_s.tv_usec) / 1.e6; } printf("time: %f sec\n", full_time / MAX_ITER); }
support_func.h
#include <random> #include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include <cstring> #include <unordered_map> #include <unordered_set> #include <map> #include <cmath> #include <ctime> #include <queue> #include <vector> #include <omp.h> #include <cassert> #include <limits> #include <sys/time.h> using namespace std; float EPS = 1e-10; struct neighbor { int number; float dist; size_t operator()(const neighbor &n) const { size_t x = std::hash<int>()(n.number); return x; } }; bool operator<(const neighbor& x, const neighbor& y) { return x.dist < y.dist; } class Metric { public: virtual float Dist(const float *x, const float *y, size_t d) = 0; }; class L2Metric : public Metric { public: float Dist(const float *x, const float *y, size_t d) { float res = 0; for (int i = 0; i < d; ++i) { res += pow(*x - *y, 2); ++x; ++y; } return sqrt(res); } }; class LikeL2Metric : public Metric { public: float Dist(const float *x, const float *y, size_t d) { float res = 0; for (int i = 0; i < d; ++i) { res += pow(*x - *y, 2); ++x; ++y; } return res; } }; class CosMetric : public Metric { public: float Dist(const float *x, const float *y, size_t d) { float cos = 0; for (int i = 0; i < d; ++i) { cos += *x * *y; ++x; ++y; } if (abs(cos - 1) < EPS ) { cos = 1;} if (abs(cos + 1) < EPS ) { cos = -1;} float res = acos(cos); return res; } }; template<typename T> void readXvec(std::ifstream &in, T *data, const size_t d, const size_t n = 1) { uint32_t dim = d; for (size_t i = 0; i < n; i++) { in.read((char *) &dim, sizeof(uint32_t)); if (dim != d) { std::cout << "file error\n"; std::cout << "dim " << dim << ", d " << d << std::endl; std::cout << "our fault\n"; exit(1); } in.read((char *) (data + i * dim), dim * sizeof(T)); } } template<typename T> void writeXvec(std::ofstream &out, T *data, const size_t d, const size_t n = 1) { const uint32_t dim = d; for (size_t i = 0; i < n; i++) { out.write((char *) &dim, sizeof(uint32_t)); out.write((char *) (data + i * dim), dim * sizeof(T)); } } void write_edges(const char *location, const std::vector<std::vector<uint32_t>> &edges) { std::cout << "Saving edges to " << location << std::endl; std::ofstream output(location, std::ios::binary); for (uint32_t i = 0; i < edges.size(); i++) { const uint32_t *data = edges[i].data(); uint32_t size = edges[i].size(); output.write((char *) &size, sizeof(uint32_t)); output.write((char *) data, sizeof(uint32_t) * size); } } vector<std::vector<uint32_t>> load_edges(const char *location, std::vector<std::vector<uint32_t>> edges) { // std::cout << "Loading edges from " << location << std::endl; std::ifstream input(location, std::ios::binary); uint32_t size; for (int i = 0; i < edges.size(); i++) { input.read((char *) &size, sizeof(uint32_t)); vector<uint32_t> vec(size); uint32_t *data = vec.data(); input.read((char *) data, sizeof(uint32_t)*size); for (int j = 0; j < size; ++j) { edges[i].push_back(vec[j]); } } return edges; } vector<float> create_uniform_data(int N, int d, std::mt19937 random_gen) { vector<float> ds(N*d); normal_distribution<float> norm_distr(0, 1); for (int i=0; i < N; ++i) { vector<float> point(d); float norm_coeff = 0; for (int j=0; j < d; ++j) { point[j] = norm_distr(random_gen); norm_coeff += point[j] * point[j]; } norm_coeff = pow(norm_coeff, 0.5); for (int j=0; j < d; ++j) { ds[i * d + j] = point[j] / norm_coeff; } } return ds; } vector<uint32_t> get_truth(vector<float> ds, vector<float> query, int N, int d, int N_q, Metric *metric) { vector<uint32_t> truth(N_q); #pragma omp parallel for for (int i=0; i < N_q; ++i) { const float* tendered_d = ds.data(); const float* goal = query.data() + i*d; float dist = metric->Dist(tendered_d, goal, d); float new_dist = dist; int tendered_num = 0; for (int j=1; j<N; ++j) { tendered_d += d; new_dist = metric->Dist(tendered_d, goal, d); if (new_dist < dist) { dist = new_dist; tendered_num = j; } } truth[i] = tendered_num; } return truth; } vector< vector <uint32_t>> CutKNNbyThreshold(vector< vector <uint32_t>> &knn, vector<float> &ds, float thr, int N, int d, Metric *metric) { vector< vector <uint32_t>> knn_cut(N); #pragma omp parallel for for (int i=0; i < N; ++i) { const float* point_i = ds.data() + i*d; for (int j=0; j < knn[i].size(); ++j) { int cur = knn[i][j]; const float *point_cur = ds.data() + cur*d; if (metric->Dist(point_i, point_cur, d) < thr) { knn_cut[i].push_back(cur); } } } return knn_cut; } vector< vector <uint32_t>> CutKNNbyK(vector< vector <uint32_t>> &knn, vector<float> &ds, int knn_size, int N, int d, Metric *metric) { vector< vector <uint32_t>> knn_cut(N); bool small_size = false; #pragma omp parallel for for (int i=0; i < N; ++i) { vector<neighbor> neigs; const float* point_i = ds.data() + i*d; for (int j=0; j < knn[i].size(); ++j) { int cur = knn[i][j]; const float *point_cur = ds.data() + cur*d; neighbor neig{cur, metric->Dist(point_i, point_cur, d)}; neigs.push_back(neig); } if (not small_size and knn_size > knn[i].size()) { cout << "Size knn less than you want" << endl; cout << knn[i].size() << endl; //exit(1); small_size = true; } sort(neigs.begin(), neigs.end()); int cur_size = knn_size; if (knn[i].size() < cur_size) { cur_size = knn[i].size(); } for (int j=0; j < cur_size; ++j) { knn_cut[i].push_back(neigs[j].number); } } return knn_cut; } vector< vector <uint32_t>> CutKL_brute(vector< vector <uint32_t>> &kl, int l, int N) { vector< vector <uint32_t>> kl_cut(N); #pragma omp parallel for for (int i=0; i < N; ++i) { if (l > kl[i].size()) { cout << "Graph have less edges that you want" << endl; exit(1); } vector <uint32_t> kl_sh = kl[i]; random_shuffle(kl_sh.begin(), kl_sh.end()); for (int j = 0; j < l; ++j) { kl_cut[i].push_back(kl_sh[j]); } } return kl_cut; } vector< vector <uint32_t>> CutKL_smart(vector< vector <uint32_t>> &kl, int l, int N, vector< vector <uint32_t>> &knn) { vector< vector <uint32_t>> kl_cut(N); #pragma omp parallel for for (int i=0; i < N; ++i) { if (l > kl[i].size()) { cout << "Graph have less edges that you want" << endl; exit(1); } vector <uint32_t> kl_sh = kl[i]; random_shuffle(kl_sh.begin(), kl_sh.end()); int it = 0; while (kl_cut[i].size() < l and it < kl_sh.size()) { if (find(knn[i].begin(), knn[i].end(), kl_sh[it]) == knn[i].end()) { kl_cut[i].push_back(kl_sh[it]); } ++it; } } return kl_cut; } int FindGraphAverageDegree(vector< vector <uint32_t>> &graph) { float ans = 0; int n = graph.size(); for (int i=0; i < n; ++i) { ans += graph[i].size(); } return float(ans / n); } inline bool FileExist (std::string& name) { ifstream f(name.c_str()); return f.good(); } vector< vector<uint32_t> > GraphMerge(vector< vector<uint32_t> > &graph_f, vector< vector<uint32_t> > &graph_s) { int n = graph_f.size(); vector <vector<uint32_t> > union_graph(n); #pragma omp parallel for for (int i=0; i < n; ++i) { for (int j =0; j < graph_f[i].size(); ++j) { union_graph[i].push_back(graph_f[i][j]); } for (int j =0; j < graph_s[i].size(); ++j) { if (find(union_graph[i].begin(), union_graph[i].end(), graph_s[i][j]) == union_graph[i].end()) { union_graph[i].push_back(graph_s[i][j]); } } } return union_graph; } void FindDistanceToKNeighbor(int n, int d, int k, int distr_size, vector<float> &ds, const char* output_txt, Metric *metric, bool normalize) { vector<float> distr(distr_size); std::ofstream outfile; outfile.open(output_txt, std::ios_base::app); float tmp_sum = 0; for (int i=0; i < d; ++i) { tmp_sum += ds[i] * ds[i]; } float norm = sqrt(tmp_sum); #pragma omp parallel for for (int i=0; i < distr_size; ++i) { priority_queue<float> topResults; const float *point_q = ds.data() + i * d; const float *point_can = ds.data() + 0 * d; for (int j = 0; j < n; ++j) { if (i != j) { point_can = ds.data() + j * d; float dist = metric->Dist(point_q, point_can, d); topResults.emplace(dist); if (topResults.size() > k) { topResults.pop(); } } } if (normalize) { distr[i] = topResults.top() / norm; } else { distr[i] = topResults.top(); } } for(int i=0; i < distr.size(); ++i) { outfile << distr[i] << ' '; } outfile << endl; }
primordial.c
/** @file primordial.c Documented primordial module. * * Julien Lesgourgues, 24.08.2010 * * This module computes the primordial spectra. It can be used in different modes: * simple parametric form, evolving inflaton perturbations, etc. So far only * the mode corresponding to a simple analytic form in terms of amplitudes, tilts * and runnings has been developed. * * The following functions can be called from other modules: * * -# primordial_init() at the beginning (anytime after perturb_init() and before spectra_init()) * -# primordial_spectrum_at_k() at any time for computing P(k) at any k * -# primordial_free() at the end */ #include "primordial.h" /** * Primordial spectra for arbitrary argument and for all initial conditions. * * This routine evaluates the primordial spectrum at a given value of k by * interpolating in the pre-computed table. * * When k is not in the pre-computed range but the spectrum can be found * analytically, it finds it. Otherwise returns an error. * * Can be called in two modes; linear or logarithmic: * * - linear: takes k, returns P(k) * * - logarithmic: takes ln(k), return ln(P(k)) * * One little subtlety: in case of several correlated initial conditions, * the cross-correlation spectrum can be negative. Then, in logarithmic mode, * the non-diagonal elements contain the cross-correlation angle \f$ P_{12}/\sqrt{P_{11} P_{22}}\f$ * (from -1 to 1) instead of \f$\ln{P_{12}}\f$ * * This function can be * called from whatever module at whatever time, provided that * primordial_init() has been called before, and primordial_free() has not * been called yet. * * @param ppm Input: pointer to primordial structure containing tabulated primordial spectrum * @param index_md Input: index of mode (scalar, tensor, ...) * @param mode Input: linear or logarithmic * @param input Input: wavenumber in 1/Mpc (linear mode) or its logarithm (logarithmic mode) * @param output Output: for each pair of initial conditions, primordial spectra P(k) in \f$Mpc^3\f$ (linear mode), or their logarithms and cross-correlation angles (logarithmic mode) * @return the error status */ int primordial_spectrum_at_k( struct primordial * ppm, int index_md, enum linear_or_logarithmic mode, double input, double * output /* array with argument output[index_ic1_ic2] (must be already allocated) */ ) { /** Summary: */ /** - define local variables */ int index_ic1,index_ic2,index_ic1_ic2; double lnk; int last_index; /** - infer ln(k) from input. In linear mode, reject negative value of input k value. */ if (mode == linear) { class_test(input<=0., ppm->error_message, "k = %e",input); lnk=log(input); } else { lnk = input; } /** - if ln(k) is not in the interpolation range, return an error, unless we are in the case of a analytic spectrum, for which a direct computation is possible */ if ((lnk > ppm->lnk[ppm->lnk_size-1]) || (lnk < ppm->lnk[0])) { class_test(ppm->primordial_spec_type != analytic_Pk, ppm->error_message, "k=%e out of range [%e : %e]",exp(lnk),exp(ppm->lnk[0]),exp(ppm->lnk[ppm->lnk_size-1])); /* direct computation */ for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { for (index_ic2 = index_ic1; index_ic2 < ppm->ic_size[index_md]; index_ic2++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic2,ppm->ic_size[index_md]); if (ppm->is_non_zero[index_md][index_ic1_ic2] == _TRUE_) { class_call(primordial_analytic_spectrum(ppm, index_md, index_ic1_ic2, exp(lnk), &(output[index_ic1_ic2])), ppm->error_message, ppm->error_message); } else { output[index_ic1_ic2] = 0.; } } } /* if mode==linear, output is already in the correct format. Otherwise, apply necessary transformation. */ if (mode == logarithmic) { for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md]); output[index_ic1_ic2] = log(output[index_ic1_ic2]); } for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { for (index_ic2 = index_ic1+1; index_ic2 < ppm->ic_size[index_md]; index_ic2++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic2,ppm->ic_size[index_md]); if (ppm->is_non_zero[index_md][index_ic1_ic2] == _TRUE_) { output[index_ic1_ic2] /= sqrt(output[index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md])]* output[index_symmetric_matrix(index_ic2,index_ic2,ppm->ic_size[index_md])]); } } } } } /** - otherwise, interpolate in the pre-computed table */ else { class_call(array_interpolate_spline( ppm->lnk, ppm->lnk_size, ppm->lnpk[index_md], ppm->ddlnpk[index_md], ppm->ic_ic_size[index_md], lnk, &last_index, output, ppm->ic_ic_size[index_md], ppm->error_message), ppm->error_message, ppm->error_message); /* if mode==logarithmic, output is already in the correct format. Otherwise, apply necessary transformation. */ if (mode == linear) { for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md]); output[index_ic1_ic2]=exp(output[index_ic1_ic2]); } for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { for (index_ic2 = index_ic1+1; index_ic2 < ppm->ic_size[index_md]; index_ic2++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic2,ppm->ic_size[index_md]); if (ppm->is_non_zero[index_md][index_ic1_ic2] == _TRUE_) { output[index_ic1_ic2] *= sqrt(output[index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md])]* output[index_symmetric_matrix(index_ic2,index_ic2,ppm->ic_size[index_md])]); } else { output[index_ic1_ic2] = 0.; } } } } } return _SUCCESS_; } /** * This routine initializes the primordial structure (in particular, it computes table of primordial spectrum values) * * @param ppr Input: pointer to precision structure (defines method and precision for all computations) * @param ppt Input: pointer to perturbation structure (useful for knowing k_min, k_max, etc.) * @param ppm Output: pointer to initialized primordial structure * @return the error status */ int primordial_init( struct precision * ppr, struct perturbs * ppt, struct primordial * ppm ) { /** Summary: */ /** - define local variables */ double k,k_min,k_max; int index_md,index_ic1,index_ic2,index_ic1_ic2,index_k; double pk,pk1,pk2; double dlnk,lnpk_pivot,lnpk_minus,lnpk_plus,lnpk_minusminus,lnpk_plusplus; /* uncomment if you use optional test below (for correlated isocurvature modes) */ //double cos_delta_k; /** - check that we really need to compute the primordial spectra */ if (ppt->has_perturbations == _FALSE_) { ppm->lnk_size=0; if (ppm->primordial_verbose > 0) printf("No perturbations requested. Primordial module skipped.\n"); return _SUCCESS_; } else { if (ppm->primordial_verbose > 0) printf("Computing primordial spectra"); } /** - get kmin and kmax from perturbation structure. Test that they make sense. */ k_min = ppt->k_min; /* first value, inferred from perturbations structure */ k_max = ppt->k_max; /* last value, inferred from perturbations structure */ class_test(k_min <= 0., ppm->error_message, "k_min negative or null: stop to avoid segmentation fault"); class_test(k_max <= 0., ppm->error_message, "k_max negative or null: stop to avoid segmentation fault"); class_test(ppm->k_pivot <= 0., ppm->error_message, "k_pivot negative or null: stop to avoid segmentation fault"); class_test(ppr->k_per_decade_primordial <= 0., ppm->error_message, "k_per_decade_primordial negative or null: stop to avoid segmentation fault"); class_test(ppr->k_per_decade_primordial <= _K_PER_DECADE_PRIMORDIAL_MIN_, ppm->error_message, "k_per_decade_primordial = %e: you ask for such a sparse sampling of the primordial spectrum that this is probably a mistake", ppr->k_per_decade_primordial); /** - allocate and fill values of \f$ \ln{k}\f$'s */ class_call(primordial_get_lnk_list(ppm, k_min, k_max, ppr->k_per_decade_primordial ), ppm->error_message, ppm->error_message); /** - define indices and allocate tables in primordial structure */ class_call(primordial_indices(ppt, ppm), ppm->error_message, ppm->error_message); /** - deal with case of analytic primordial spectra (with amplitudes, tilts, runnings, etc.) */ if (ppm->primordial_spec_type == analytic_Pk) { if (ppm->primordial_verbose > 0) printf(" (analytic spectrum)\n"); class_call_except(primordial_analytic_spectrum_init(ppt, ppm), ppm->error_message, ppm->error_message, primordial_free(ppm)); for (index_k = 0; index_k < ppm->lnk_size; index_k++) { k=exp(ppm->lnk[index_k]); for (index_md = 0; index_md < ppt->md_size; index_md++) { for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { for (index_ic2 = index_ic1; index_ic2 < ppm->ic_size[index_md]; index_ic2++) { index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic2,ppm->ic_size[index_md]); if (ppm->is_non_zero[index_md][index_ic1_ic2] == _TRUE_) { class_call(primordial_analytic_spectrum(ppm, index_md, index_ic1_ic2, k, &pk), ppm->error_message, ppm->error_message); if (index_ic1 == index_ic2) { /* diagonal coefficients: ln[P(k)] */ ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = log(pk); } else { /* non-diagonal coefficients: cosDelta(k) = P(k)_12/sqrt[P(k)_1 P(k)_2] */ class_call(primordial_analytic_spectrum(ppm, index_md, index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md]), k, &pk1), ppm->error_message, ppm->error_message); class_call(primordial_analytic_spectrum(ppm, index_md, index_symmetric_matrix(index_ic2,index_ic2,ppm->ic_size[index_md]), k, &pk2), ppm->error_message, ppm->error_message); /* either return an error if correlation is too large... */ /* cos_delta_k = pk/sqrt(pk1*pk2); class_test_except((cos_delta_k < -1.) || (cos_delta_k > 1.), ppm->error_message, primordial_free(ppm), "correlation angle between IC's takes unphysical values"); ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = cos_delta_k; */ /* ... or enforce definite positive correlation matrix */ if (pk > sqrt(pk1*pk2)) ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = 1.; else if (pk < -sqrt(pk1*pk2)) ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = -1.; else ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = pk/sqrt(pk1*pk2); } } else { /* non-diagonal coefficients when ic's are uncorrelated */ ppm->lnpk[index_md][index_k*ppm->ic_ic_size[index_md]+index_ic1_ic2] = 0.; } } } } } } /** - deal with case of inflation with given \f$V(\phi)\f$ or \f$H(\phi)\f$ */ else if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_H) || (ppm->primordial_spec_type == inflation_V_end)) { class_call(primordial_inflation_indices(ppm), ppm->error_message, ppm->error_message); if (ppm->primordial_verbose > 0) printf(" (simulating inflation)\n"); class_call_except(primordial_inflation_solve_inflation(ppt,ppm,ppr), ppm->error_message, ppm->error_message, primordial_free(ppm)); } /** - deal with the case of external calculation of \f$ P_k \f$*/ else if (ppm->primordial_spec_type == external_Pk) { class_test(ppt->has_scalars == _FALSE_, ppm->error_message, "external Pk module cannot work if you do not ask for scalar modes"); class_test(ppt->has_vectors == _TRUE_, ppm->error_message, "external Pk module cannot work if you ask for vector modes"); class_test(ppt->has_bi == _TRUE_ || ppt->has_cdi == _TRUE_ || ppt->has_nid == _TRUE_ || ppt->has_niv == _TRUE_, ppm->error_message, "external Pk module cannot work if you ask for isocurvature modes (but that could be implemented easily in the future!)"); if (ppm->primordial_verbose > 0) printf(" (Pk calculated externally)\n"); class_call_except(primordial_external_spectrum_init(ppt,ppm), ppm->error_message, ppm->error_message, primordial_free(ppm)); } else { class_test(0==0, ppm->error_message, "primordial spectrum type not recognized"); } /** - compute second derivative of each \f$ \ln{P_k} \f$ versus lnk with spline, in view of interpolation */ for (index_md = 0; index_md < ppm->md_size; index_md++) { class_call(array_spline_table_lines(ppm->lnk, ppm->lnk_size, ppm->lnpk[index_md], ppm->ic_ic_size[index_md], ppm->ddlnpk[index_md], _SPLINE_EST_DERIV_, ppm->error_message), ppm->error_message, ppm->error_message); } /** - derive spectral parameters from numerically computed spectra (not used by the rest of the code, but useful to keep in memory for several types of investigation) */ if (ppm->primordial_spec_type != analytic_Pk) { dlnk = log(10.)/ppr->k_per_decade_primordial; if (ppt->has_scalars == _TRUE_) { class_call(primordial_spectrum_at_k(ppm, ppt->index_md_scalars, logarithmic, log(ppm->k_pivot), &lnpk_pivot), ppm->error_message, ppm->error_message); class_call(primordial_spectrum_at_k(ppm, ppt->index_md_scalars, logarithmic, log(ppm->k_pivot)+dlnk, &lnpk_plus), ppm->error_message, ppm->error_message); class_call(primordial_spectrum_at_k(ppm, ppt->index_md_scalars, logarithmic, log(ppm->k_pivot)-dlnk, &lnpk_minus), ppm->error_message, ppm->error_message); ppm->A_s = exp(lnpk_pivot); ppm->n_s = (lnpk_plus-lnpk_minus)/(2.*dlnk)+1.; ppm->alpha_s = (lnpk_plus-2.*lnpk_pivot+lnpk_minus)/pow(dlnk,2); /** - expression for alpha_s comes from: `ns_2 = (lnpk_plus-lnpk_pivot)/(dlnk)+1` `ns_1 = (lnpk_pivot-lnpk_minus)/(dlnk)+1` `alpha_s = dns/dlnk = (ns_2-ns_1)/dlnk = (lnpk_plus-lnpk_pivot-lnpk_pivot+lnpk_minus)/(dlnk)/(dlnk)` **/ class_call(primordial_spectrum_at_k(ppm, ppt->index_md_scalars, logarithmic, log(ppm->k_pivot)+2.*dlnk, &lnpk_plusplus), ppm->error_message, ppm->error_message); class_call(primordial_spectrum_at_k(ppm, ppt->index_md_scalars, logarithmic, log(ppm->k_pivot)-2.*dlnk, &lnpk_minusminus), ppm->error_message, ppm->error_message); /** - expression for beta_s: `ppm->beta_s = (alpha_plus-alpha_minus)/dlnk = (lnpk_plusplus-2.*lnpk_plus+lnpk_pivot - (lnpk_pivot-2.*lnpk_minus+lnpk_minusminus)/pow(dlnk,3)` **/ /* Simplification of the beta_s expression: */ ppm->beta_s = (lnpk_plusplus-2.*lnpk_plus+2.*lnpk_minus-lnpk_minusminus)/pow(dlnk,3); if (ppm->primordial_verbose > 0) printf(" -> A_s=%g n_s=%g alpha_s=%g\n",ppm->A_s,ppm->n_s,ppm->alpha_s); } if (ppt->has_tensors == _TRUE_) { class_call(primordial_spectrum_at_k(ppm, ppt->index_md_tensors, logarithmic, log(ppm->k_pivot), &lnpk_pivot), ppm->error_message, ppm->error_message); class_call(primordial_spectrum_at_k(ppm, ppt->index_md_tensors, logarithmic, log(ppm->k_pivot)+dlnk, &lnpk_plus), ppm->error_message, ppm->error_message); class_call(primordial_spectrum_at_k(ppm, ppt->index_md_tensors, logarithmic, log(ppm->k_pivot)-dlnk, &lnpk_minus), ppm->error_message, ppm->error_message); ppm->r = exp(lnpk_pivot)/ppm->A_s; ppm->n_t = (lnpk_plus-lnpk_minus)/(2.*dlnk); ppm->alpha_t = (lnpk_plus-2.*lnpk_pivot+lnpk_minus)/pow(dlnk,2); if (ppm->primordial_verbose > 0) printf(" -> r=%g n_t=%g alpha_t=%g\n",ppm->r,ppm->n_t,ppm->alpha_t); } } return _SUCCESS_; } /** * This routine frees all the memory space allocated by primordial_init(). * * To be called at the end of each run. * * @param ppm Input: pointer to primordial structure (which fields must be freed) * @return the error status */ int primordial_free( struct primordial * ppm ) { int index_md; if (ppm->lnk_size > 0) { if (ppm->primordial_spec_type == analytic_Pk) { for (index_md = 0; index_md < ppm->md_size; index_md++) { free(ppm->amplitude[index_md]); free(ppm->tilt[index_md]); free(ppm->running[index_md]); } free(ppm->amplitude); free(ppm->tilt); free(ppm->running); } else if (ppm->primordial_spec_type == external_Pk) { free(ppm->command); } for (index_md = 0; index_md < ppm->md_size; index_md++) { free(ppm->lnpk[index_md]); free(ppm->ddlnpk[index_md]); free(ppm->is_non_zero[index_md]); } free(ppm->lnpk); free(ppm->ddlnpk); free(ppm->is_non_zero); free(ppm->ic_size); free(ppm->ic_ic_size); free(ppm->lnk); } return _SUCCESS_; } /** * This routine defines indices and allocates tables in the primordial structure * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @return the error status */ int primordial_indices( struct perturbs * ppt, struct primordial * ppm ) { int index_md; ppm->md_size = ppt->md_size; class_alloc(ppm->lnpk,ppt->md_size*sizeof(double*),ppm->error_message); class_alloc(ppm->ddlnpk,ppt->md_size*sizeof(double*),ppm->error_message); class_alloc(ppm->ic_size,ppt->md_size*sizeof(int*),ppm->error_message); class_alloc(ppm->ic_ic_size,ppt->md_size*sizeof(int*),ppm->error_message); class_alloc(ppm->is_non_zero,ppm->md_size*sizeof(short *),ppm->error_message); for (index_md = 0; index_md < ppt->md_size; index_md++) { ppm->ic_size[index_md] = ppt->ic_size[index_md]; ppm->ic_ic_size[index_md] = (ppm->ic_size[index_md]*(ppm->ic_size[index_md]+1))/2; class_alloc(ppm->lnpk[index_md], ppm->lnk_size*ppm->ic_ic_size[index_md]*sizeof(double), ppm->error_message); class_alloc(ppm->ddlnpk[index_md], ppm->lnk_size*ppm->ic_ic_size[index_md]*sizeof(double), ppm->error_message); class_alloc(ppm->is_non_zero[index_md], ppm->ic_ic_size[index_md]*sizeof(short), ppm->error_message); } return _SUCCESS_; } /** * This routine allocates and fills the list of wavenumbers k * * * @param ppm Input/output: pointer to primordial structure * @param kmin Input: first value * @param kmax Input: last value that we should encompass * @param k_per_decade Input: number of k per decade * @return the error status */ int primordial_get_lnk_list( struct primordial * ppm, double kmin, double kmax, double k_per_decade ) { int i; class_test((kmin <= 0.) || (kmax <= kmin), ppm->error_message, "inconsistent values of kmin=%e, kmax=%e",kmin,kmax); ppm->lnk_size = (int)(log(kmax/kmin)/log(10.)*k_per_decade) + 2; class_alloc(ppm->lnk,ppm->lnk_size*sizeof(double),ppm->error_message); for (i=0; i<ppm->lnk_size; i++) ppm->lnk[i]=log(kmin)+i*log(10.)/k_per_decade; return _SUCCESS_; } /** * This routine interprets and stores in a condensed form the input parameters * in the case of a simple analytic spectra with amplitudes, tilts, runnings, * in such way that later on, the spectrum can be obtained by a quick call to * the routine primordial_analytic_spectrum(() * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @return the error status */ int primordial_analytic_spectrum_init( struct perturbs * ppt, struct primordial * ppm ) { int index_md,index_ic1,index_ic2; int index_ic1_ic2,index_ic1_ic1,index_ic2_ic2; double one_amplitude=0.; double one_tilt=0.; double one_running=0.; double one_correlation=0.; class_alloc(ppm->amplitude, ppm->md_size*sizeof(double *), ppm->error_message); class_alloc(ppm->tilt, ppm->md_size*sizeof(double *), ppm->error_message); class_alloc(ppm->running, ppm->md_size*sizeof(double *), ppm->error_message); for (index_md = 0; index_md < ppm->md_size; index_md++) { class_alloc(ppm->amplitude[index_md], ppm->ic_ic_size[index_md]*sizeof(double), ppm->error_message); class_alloc(ppm->tilt[index_md], ppm->ic_ic_size[index_md]*sizeof(double), ppm->error_message); class_alloc(ppm->running[index_md], ppm->ic_ic_size[index_md]*sizeof(double), ppm->error_message); } for (index_md = 0; index_md < ppm->md_size; index_md++) { /* diagonal coefficients */ for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { if (_scalars_) { if ((ppt->has_ad == _TRUE_) && (index_ic1 == ppt->index_ic_ad)) { one_amplitude = ppm->A_s; one_tilt = ppm->n_s; one_running = ppm->alpha_s; } if ((ppt->has_bi == _TRUE_) && (index_ic1 == ppt->index_ic_bi)) { one_amplitude = ppm->A_s*ppm->f_bi*ppm->f_bi; one_tilt = ppm->n_bi; one_running = ppm->alpha_bi; } if ((ppt->has_cdi == _TRUE_) && (index_ic1 == ppt->index_ic_cdi)) { one_amplitude = ppm->A_s*ppm->f_cdi*ppm->f_cdi; one_tilt = ppm->n_cdi; one_running = ppm->alpha_cdi; } if ((ppt->has_nid == _TRUE_) && (index_ic1 == ppt->index_ic_nid)) { one_amplitude = ppm->A_s*ppm->f_nid*ppm->f_nid; one_tilt = ppm->n_nid; one_running = ppm->alpha_nid; } if ((ppt->has_niv == _TRUE_) && (index_ic1 == ppt->index_ic_niv)) { one_amplitude = ppm->A_s*ppm->f_niv*ppm->f_niv; one_tilt = ppm->n_niv; one_running = ppm->alpha_niv; } } if (_tensors_) { if (index_ic1 == ppt->index_ic_ten) { one_amplitude = ppm->A_s*ppm->r; one_tilt = ppm->n_t+1.; /* +1 to match usual definition of n_t (equivalent to n_s-1) */ one_running = ppm->alpha_t; } } class_test(one_amplitude <= 0., ppm->error_message, "inconsistent input for primordial amplitude: %g for index_md=%d, index_ic=%d\n", one_amplitude,index_md,index_ic1); index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md]); ppm->is_non_zero[index_md][index_ic1_ic2] = _TRUE_; ppm->amplitude[index_md][index_ic1_ic2] = one_amplitude; ppm->tilt[index_md][index_ic1_ic2] = one_tilt; ppm->running[index_md][index_ic1_ic2] = one_running; } /* non-diagonal coefficients */ for (index_ic1 = 0; index_ic1 < ppm->ic_size[index_md]; index_ic1++) { for (index_ic2 = index_ic1+1; index_ic2 < ppm->ic_size[index_md]; index_ic2++) { if (_scalars_) { if ((ppt->has_ad == _TRUE_) && (ppt->has_bi == _TRUE_) && (((index_ic1 == ppt->index_ic_ad) && (index_ic2 == ppt->index_ic_bi)) || ((index_ic1 == ppt->index_ic_ad) && (index_ic1 == ppt->index_ic_bi)))) { one_correlation = ppm->c_ad_bi; one_tilt = ppm->n_ad_bi; one_running = ppm->alpha_ad_bi; } if ((ppt->has_ad == _TRUE_) && (ppt->has_cdi == _TRUE_) && (((index_ic1 == ppt->index_ic_ad) && (index_ic2 == ppt->index_ic_cdi)) || ((index_ic2 == ppt->index_ic_ad) && (index_ic1 == ppt->index_ic_cdi)))) { one_correlation = ppm->c_ad_cdi; one_tilt = ppm->n_ad_cdi; one_running = ppm->alpha_ad_cdi; } if ((ppt->has_ad == _TRUE_) && (ppt->has_nid == _TRUE_) && (((index_ic1 == ppt->index_ic_ad) && (index_ic2 == ppt->index_ic_nid)) || ((index_ic2 == ppt->index_ic_ad) && (index_ic1 == ppt->index_ic_nid)))) { one_correlation = ppm->c_ad_nid; one_tilt = ppm->n_ad_nid; one_running = ppm->alpha_ad_nid; } if ((ppt->has_ad == _TRUE_) && (ppt->has_niv == _TRUE_) && (((index_ic1 == ppt->index_ic_ad) && (index_ic2 == ppt->index_ic_niv)) || ((index_ic2 == ppt->index_ic_ad) && (index_ic1 == ppt->index_ic_niv)))) { one_correlation = ppm->c_ad_niv; one_tilt = ppm->n_ad_niv; one_running = ppm->alpha_ad_niv; } if ((ppt->has_bi == _TRUE_) && (ppt->has_cdi == _TRUE_) && (((index_ic1 == ppt->index_ic_bi) && (index_ic2 == ppt->index_ic_cdi)) || ((index_ic2 == ppt->index_ic_bi) && (index_ic1 == ppt->index_ic_cdi)))) { one_correlation = ppm->c_bi_cdi; one_tilt = ppm->n_bi_cdi; one_running = ppm->alpha_bi_cdi; } if ((ppt->has_bi == _TRUE_) && (ppt->has_nid == _TRUE_) && (((index_ic1 == ppt->index_ic_bi) && (index_ic2 == ppt->index_ic_nid)) || ((index_ic2 == ppt->index_ic_bi) && (index_ic1 == ppt->index_ic_nid)))) { one_correlation = ppm->c_bi_nid; one_tilt = ppm->n_bi_nid; one_running = ppm->alpha_bi_nid; } if ((ppt->has_bi == _TRUE_) && (ppt->has_niv == _TRUE_) && (((index_ic1 == ppt->index_ic_bi) && (index_ic2 == ppt->index_ic_niv)) || ((index_ic2 == ppt->index_ic_bi) && (index_ic1 == ppt->index_ic_niv)))) { one_correlation = ppm->c_bi_niv; one_tilt = ppm->n_bi_niv; one_running = ppm->alpha_bi_niv; } if ((ppt->has_cdi == _TRUE_) && (ppt->has_nid == _TRUE_) && (((index_ic1 == ppt->index_ic_cdi) && (index_ic2 == ppt->index_ic_nid)) || ((index_ic2 == ppt->index_ic_cdi) && (index_ic1 == ppt->index_ic_nid)))) { one_correlation = ppm->c_cdi_nid; one_tilt = ppm->n_cdi_nid; one_running = ppm->alpha_cdi_nid; } if ((ppt->has_cdi == _TRUE_) && (ppt->has_niv == _TRUE_) && (((index_ic1 == ppt->index_ic_cdi) && (index_ic2 == ppt->index_ic_niv)) || ((index_ic2 == ppt->index_ic_cdi) && (index_ic1 == ppt->index_ic_niv)))) { one_correlation = ppm->c_cdi_niv; one_tilt = ppm->n_cdi_niv; one_running = ppm->alpha_cdi_niv; } if ((ppt->has_nid == _TRUE_) && (ppt->has_niv == _TRUE_) && (((index_ic1 == ppt->index_ic_nid) && (index_ic2 == ppt->index_ic_niv)) || ((index_ic2 == ppt->index_ic_nid) && (index_ic1 == ppt->index_ic_niv)))) { one_correlation = ppm->c_nid_niv; one_tilt = ppm->n_nid_niv; one_running = ppm->alpha_nid_niv; } } class_test((one_correlation < -1) || (one_correlation > 1), ppm->error_message, "inconsistent input for isocurvature cross-correlation\n"); index_ic1_ic2 = index_symmetric_matrix(index_ic1,index_ic2,ppm->ic_size[index_md]); index_ic1_ic1 = index_symmetric_matrix(index_ic1,index_ic1,ppm->ic_size[index_md]); index_ic2_ic2 = index_symmetric_matrix(index_ic2,index_ic2,ppm->ic_size[index_md]); if (one_correlation == 0.) { ppm->is_non_zero[index_md][index_ic1_ic2] = _FALSE_; ppm->amplitude[index_md][index_ic1_ic2] = 0.; ppm->tilt[index_md][index_ic1_ic2] = 0.; ppm->running[index_md][index_ic1_ic2] = 0.; } else { ppm->is_non_zero[index_md][index_ic1_ic2] = _TRUE_; ppm->amplitude[index_md][index_ic1_ic2] = sqrt(ppm->amplitude[index_md][index_ic1_ic1]* ppm->amplitude[index_md][index_ic2_ic2])* one_correlation; ppm->tilt[index_md][index_ic1_ic2] = 0.5*(ppm->tilt[index_md][index_ic1_ic1] +ppm->tilt[index_md][index_ic2_ic2]) + one_tilt; ppm->running[index_md][index_ic1_ic2] = 0.5*(ppm->running[index_md][index_ic1_ic1] +ppm->running[index_md][index_ic2_ic2]) + one_running; } } } } return _SUCCESS_; } /** * This routine returns the primordial spectrum in the simple analytic case with * amplitudes, tilts, runnings, for each mode (scalar/tensor...), * pair of initial conditions, and wavenumber. * * @param ppm Input/output: pointer to primordial structure * @param index_md Input: index of mode (scalar, tensor, ...) * @param index_ic1_ic2 Input: pair of initial conditions (ic1, ic2) * @param k Input: wavenumber in same units as pivot scale, i.e. in 1/Mpc * @param pk Output: primordial power spectrum A (k/k_pivot)^(n+...) * @return the error status */ int primordial_analytic_spectrum( struct primordial * ppm, int index_md, int index_ic1_ic2, double k, double * pk ) { if (ppm->is_non_zero[index_md][index_ic1_ic2] == _TRUE_) { *pk = ppm->amplitude[index_md][index_ic1_ic2] *exp((ppm->tilt[index_md][index_ic1_ic2]-1.)*log(k/ppm->k_pivot) + 0.5 * ppm->running[index_md][index_ic1_ic2] * pow(log(k/ppm->k_pivot), 2.)); } else { *pk = 0.; } return _SUCCESS_; } /** * This routine encodes the inflaton scalar potential * * @param ppm Input: pointer to primordial structure * @param phi Input: background inflaton field value in units of Mp * @param V Output: inflaton potential in units of \f$ Mp^4\f$ * @param dV Output: first derivative of inflaton potential wrt the field * @param ddV Output: second derivative of inflaton potential wrt the field * @return the error status */ int primordial_inflation_potential( struct primordial * ppm, double phi, double * V, double * dV, double * ddV ) { double e,de,dde,mu,dmu,ddmu,l,dl,ddl,p,dp,ddp; switch (ppm->potential) { /* V(phi)=polynomial in phi */ case polynomial: *V = ppm->V0+phi*ppm->V1+pow(phi,2)/2.*ppm->V2+pow(phi,3)/6.*ppm->V3+pow(phi,4)/24.*ppm->V4; *dV = ppm->V1+phi*ppm->V2+pow(phi,2)/2.*ppm->V3+pow(phi,3)/6.*ppm->V4; *ddV = ppm->V2+phi*ppm->V3+pow(phi,2)/2.*ppm->V4; break; /* V(phi) = Lambda^4(1+cos(phi/f)) = V0 (1+cos(phi/V1)) */ case natural: *V = ppm->V0*(1.+cos(phi/ppm->V1)); *dV = -ppm->V0/ppm->V1*sin(phi/ppm->V1); *ddV = -ppm->V0/ppm->V1/ppm->V1*cos(phi/ppm->V1); break; /* Higgs inflation from arXiv:1403.6078 */ case higgs_inflation: // correspondence with 1403.6078: // V0 = b // V1 = ksi // V2 = kappa // V3 = delta_lambda // mu = bar(mu)/M_P // phi = -chi/M_P e = exp(2./sqrt(6.)*sqrt(8.*_PI_)*phi); de = 2./sqrt(6.)*sqrt(8.*_PI_)*e; dde = 2./3. * 8.*_PI_ * e; mu = pow(1.-e,0.5); dmu = -0.5*de*pow(1.-e,-0.5); ddmu = -0.5*dde*pow(1.-e,-0.5)-0.25*de*de*pow(1.-e,-1.5); l = log(mu/ppm->V2); dl = dmu/mu; ddl = ddmu/mu - dl*dl; p = 1./16. + ppm->V3/ppm->V0 + l*l; dp = 2.*dl*l; ddp = 2.*ddl*l+2.*dl*dl; *V = ppm->V0/4./pow(8.*_PI_,2)/ppm->V1/ppm->V1*p*pow(mu,4); *dV = ppm->V0/4./pow(8.*_PI_,2)/ppm->V1/ppm->V1*(dp*pow(mu,4)+4.*p*dmu*pow(mu,3)); *ddV = ppm->V0/4./pow(8.*_PI_,2)/ppm->V1/ppm->V1*(ddp*pow(mu,4)+8.*dp*dmu*pow(mu,3)+4.*p*ddmu*pow(mu,3)+12.*p*pow(dmu*mu,2)); //fprintf(stderr,"%e %e %e\n",*V,p,mu); break; /* code here other shapes */ default: class_stop(ppm->error_message,"ppm->potential=%d different from all known cases",ppm->potential); break; } return _SUCCESS_; } /** * This routine encodes the function \f$ H(\phi)\f$ * * @param ppm Input: pointer to primordial structure * @param phi Input: background inflaton field value in units of Mp * @param H Output: Hubble parameters in units of Mp * @param dH Output: \f$ dH / d\phi \f$ * @param ddH Output: \f$ d^2H / d\phi^2 \f$ * @param dddH Output: \f$ d^3H / d\phi^3 \f$ * @return the error status */ int primordial_inflation_hubble( struct primordial * ppm, double phi, double * H, double * dH, double * ddH, double * dddH ) { *H = ppm->H0 + phi*ppm->H1 + pow(phi,2)/2.*ppm->H2 + pow(phi,3)/6.*ppm->H3 + pow(phi,4)/24.*ppm->H4; *dH = ppm->H1 + phi*ppm->H2 + pow(phi,2)/2.*ppm->H3 + pow(phi,3)/6.*ppm->H4; *ddH = ppm->H2 + phi*ppm->H3 + pow(phi,2)/2.*ppm->H4; *dddH = ppm->H3 + phi*ppm->H4; return _SUCCESS_; } /** * This routine defines indices used by the inflation simulator * * @param ppm Input/output: pointer to primordial structure * @return the error status */ int primordial_inflation_indices( struct primordial * ppm ) { int index_in; index_in = 0; /* indices for background quantities */ ppm->index_in_a = index_in; index_in ++; ppm->index_in_phi = index_in; index_in ++; if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) { ppm->index_in_dphi = index_in; index_in ++; } /* size of background vector */ ppm->in_bg_size = index_in; /* indices for perturbations */ ppm->index_in_ksi_re = index_in; index_in ++; ppm->index_in_ksi_im = index_in; index_in ++; ppm->index_in_dksi_re = index_in; index_in ++; ppm->index_in_dksi_im = index_in; index_in ++; ppm->index_in_ah_re = index_in; index_in ++; ppm->index_in_ah_im = index_in; index_in ++; ppm->index_in_dah_re = index_in; index_in ++; ppm->index_in_dah_im = index_in; index_in ++; /* size of perturbation vector */ ppm->in_size = index_in; return _SUCCESS_; } /** * Main routine of inflation simulator. Its goal is to check the * background evolution before and after the pivot value * phi=phi_pivot, and then, if this evolution is suitable, to call the * routine primordial_inflation_spectra(). * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @param ppr Input: pointer to precision structure * @return the error status */ int primordial_inflation_solve_inflation( struct perturbs * ppt, struct primordial * ppm, struct precision *ppr ) { /** Summary: */ /** - define local variables */ double * y; double * y_ini; double * dy; double a_pivot; double a_try; double H_pivot; double H_try; double phi_try; double dphidt_pivot; double dphidt_try; double aH_ini,aH_end; double k_max,k_min; int counter; double dH,ddH,dddH; /** - allocate vectors for background/perturbed quantities */ class_alloc(y,ppm->in_size*sizeof(double),ppm->error_message); class_alloc(y_ini,ppm->in_size*sizeof(double),ppm->error_message); class_alloc(dy,ppm->in_size*sizeof(double),ppm->error_message); /** - eventually, needs first to find phi_pivot */ if (ppm->primordial_spec_type == inflation_V_end) { class_call(primordial_inflation_find_phi_pivot(ppm,ppr,y,dy), ppm->error_message, ppm->error_message); } else { ppm->phi_pivot = 0.; } // uncomment these lines if for checking, you want first-order slow-roll predictions /* if (ppm->primordial_verbose>0) { if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) { double V,dV,ddV; class_call(primordial_inflation_check_potential(ppm,ppm->phi_pivot,&V,&dV,&ddV), ppm->error_message, ppm->error_message); fprintf(stdout," -> 1st-order slow-roll prediction for A_s: %g\n",128.*_PI_/3.*pow(V,3)/pow(dV,2)); fprintf(stdout," -> 1st-order slow-roll prediction for T/S: %g\n",pow(dV/V,2)/_PI_); fprintf(stdout," -> 1st-order slow-roll prediction for A_T: %g\n",pow(dV/V,2)/_PI_*128.*_PI_/3.*pow(V,3)/pow(dV,2)); fprintf(stdout," -> 1st-order slow-roll prediction for n_s: %g\n",1.-6./16./_PI_*pow(dV/V,2)+2./8./_PI_*(ddV/V)); fprintf(stdout," -> 1st-order slow-roll prediction for n_t: %g\n",-2./16./_PI_*pow(dV/V,2)); } } */ /** - compute H_pivot at phi_pivot */ switch (ppm->primordial_spec_type) { case inflation_V: case inflation_V_end: /** - check positivity and negative slope of potential in field pivot value, and find value of phi_dot and H for field's pivot value, assuming slow-roll attractor solution has been reached. If no solution, code will stop there. */ if (ppm->primordial_verbose > 1) printf(" (search attractor at pivot)\n"); class_call_except(primordial_inflation_find_attractor(ppm, ppr, ppm->phi_pivot, ppr->primordial_inflation_attractor_precision_pivot, y, dy, &H_pivot, &dphidt_pivot), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); break; case inflation_H: /** - check positivity and negative slope of \f$ H(\phi)\f$ in field pivot value, and get H_pivot */ class_call_except(primordial_inflation_check_hubble(ppm, ppm->phi_pivot, &H_pivot, &dH, &ddH, &dddH), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); break; default: free(y);free(y_ini);free(dy); class_stop(ppm->error_message,"ppm->primordial_spec_type=%d different from possible relevant cases",ppm->primordial_spec_type); break; } /** - find a_pivot, value of scale factor when k_pivot crosses horizon while phi=phi_pivot */ a_pivot = ppm->k_pivot/H_pivot; /** - integrate background solution starting from phi_pivot and until k_max>>aH. This ensures that the inflationary model considered here is valid and that the primordial spectrum can be computed. Otherwise, if slow-roll brakes too early, model is not suitable and run stops. */ if (ppm->primordial_verbose > 1) printf(" (check inflation duration after phi_pivot=%e)\n",ppm->phi_pivot); k_max = exp(ppm->lnk[ppm->lnk_size-1]); aH_end = k_max/ppr->primordial_inflation_ratio_max; y[ppm->index_in_a] = a_pivot; y[ppm->index_in_phi] = ppm->phi_pivot; if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) y[ppm->index_in_dphi] = a_pivot*dphidt_pivot; class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, aH_end, _TRUE_, forward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); /* we need to do the opposite: to check that there is an initial time such that k_min << (aH)_ini. A guess is made by integrating backward in time. This can be done exactly for inflation_H, or only approximately for inflation_V (using the first-order approximation to the attractor inflationary solution). However this approximation is irrelevant because nevertheless, later on, we compute the attractor solution at the initial time with high accuracy, and then we integrate the background equations forward in time. Hence the approximation made here introduces zero mistake on the final result. It is just a way to find quickly a reasonable initial phi value. In the inflation_V case, if the exact forward integration reveals that the guess was not good (i.e. does not correspond to "early enough"), we iterate over sequences of backward/forward integration, until a correct time is found. For potential such that no solution exists (no long-enough slow-roll period before the pivot scale), the run stops. */ if (ppm->primordial_verbose > 1) printf(" (check inflation duration before pivot)\n"); k_min = exp(ppm->lnk[0]); aH_ini = k_min/ppr->primordial_inflation_ratio_min; switch (ppm->primordial_spec_type) { case inflation_V: case inflation_V_end: counter = 0; y[ppm->index_in_a] = a_pivot; y[ppm->index_in_phi] = ppm->phi_pivot; do { /* counter to avoid infinite loop */ counter ++; class_test_except(counter >= ppr->primordial_inflation_phi_ini_maxit, ppm->error_message, free(y);free(y_ini);free(dy), "when searching for an initial value of phi just before observable inflation takes place, could not converge after %d iterations. The potential does not allow eough inflationary e-folds before reaching the pivot scale", counter); /* try to find a value phi_try such that aH=aH_ini*(ppr->primordial_inflation_aH_ini_target) (default: aH_ini*0.9). But this is using the approximate backward solution. So, anyway, we will check using the exact forward solution that at this phi_try, we really have aH < aH_ini; if this is not the case, we will iterate until a correct phi_try is found. */ class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, aH_ini*ppr->primordial_inflation_aH_ini_target, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); phi_try = y[ppm->index_in_phi]; /* in inflation_V case, find the accurate attractor solution for phi_ini', and then the correct value of a_ini, and finally of dphi/dtau_ini */ /* find dphi/dt_ini (unlike dphi/dtau_ini, this does not depend on normalization of a) */ class_call_except(primordial_inflation_find_attractor(ppm, ppr, phi_try, ppr->primordial_inflation_attractor_precision_initial, y, dy, &H_try, &dphidt_try), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); /* we need to normalize a properly so that a=a_pivot when phi=phi_pivot. To do so, we evolve starting arbitrarily from a_ini=1, and then we rescale a_ini appropriately. */ y[ppm->index_in_a] = 1.; y[ppm->index_in_phi] = phi_try; y[ppm->index_in_dphi] = y[ppm->index_in_a]*dphidt_try; // dphi/dtau = a dphi/dt class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _phi_, ppm->phi_pivot, _TRUE_, forward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); /* now impose the correct a_ini */ a_try = a_pivot/y[ppm->index_in_a]; /* in case another iteration will be needed, set a new starting point for the routine primordial_inflation_evolve_background(...,backward) */ y[ppm->index_in_a] = a_try; y[ppm->index_in_phi] = phi_try; } while (a_try*H_try > aH_ini); y_ini[ppm->index_in_a] = a_try; y_ini[ppm->index_in_phi] = phi_try; y_ini[ppm->index_in_dphi] = y_ini[ppm->index_in_a]*dphidt_try; // dphi/dtau = a dphi/dt break; case inflation_H: y[ppm->index_in_a] = a_pivot; y[ppm->index_in_phi] = ppm->phi_pivot; class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, aH_ini, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); y_ini[ppm->index_in_a] = y[ppm->index_in_a]; y_ini[ppm->index_in_phi] = y[ppm->index_in_phi]; break; default: free(y);free(y_ini);free(dy); class_stop(ppm->error_message,"ppm->primordial_spec_type=%d different from possible relevant cases",ppm->primordial_spec_type); break; } /** - starting from this time, i.e. from y_ini[ ], we run the routine which takes care of computing the primordial spectrum. */ if (ppm->primordial_verbose > 1) printf(" (compute spectrum)\n"); if (ppm->behavior == numerical) { class_call_except(primordial_inflation_spectra(ppt, ppm, ppr, y_ini), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); } else if (ppm->behavior == analytical) { class_call_except(primordial_inflation_analytic_spectra(ppt, ppm, ppr, y_ini), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); } else { class_stop(ppm->error_message,"Uncomprehensible value of the flag ppm->behavior=%d",ppm->behavior); } /** - before ending, we want to compute and store the values of \f$ \phi \f$ corresponding to k=aH for k_min and k_max */ y[ppm->index_in_a] = y_ini[ppm->index_in_a]; y[ppm->index_in_phi] = y_ini[ppm->index_in_phi]; if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) y[ppm->index_in_dphi] = y_ini[ppm->index_in_dphi]; class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, k_min, _FALSE_, forward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); ppm->phi_min=y[ppm->index_in_phi]; class_call_except(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, k_max, _FALSE_, forward, conformal), ppm->error_message, ppm->error_message, free(y);free(y_ini);free(dy)); ppm->phi_max=y[ppm->index_in_phi]; if (ppm->primordial_verbose > 1) printf(" (observable power spectrum goes from %e to %e)\n", ppm->phi_min, ppm->phi_max); /** - finally, we can de-allocate */ free(y); free(y_ini); free(dy); return _SUCCESS_; } /** * Routine for the computation of an analytic apporoximation to the * the primordial spectrum. In general, should be used only for * comparing with exact numerical computation performed by * primordial_inflation_spectra(). * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param y_ini Input: initial conditions for the vector of background/perturbations, already allocated and filled * @return the error status */ int primordial_inflation_analytic_spectra( struct perturbs * ppt, struct primordial * ppm, struct precision * ppr, double * y_ini ) { double * y; double * dy; int index_k; double k,phi_k; double curvature,tensors; double V,dV,ddV; /** Summary */ /** - allocate vectors for background/perturbed quantities */ class_alloc(y,ppm->in_size*sizeof(double),ppm->error_message); class_alloc(dy,ppm->in_size*sizeof(double),ppm->error_message); /** - initialize the background part of the running vector */ y[ppm->index_in_a] = y_ini[ppm->index_in_a]; y[ppm->index_in_phi] = y_ini[ppm->index_in_phi]; if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) y[ppm->index_in_dphi] = y_ini[ppm->index_in_dphi]; /** - loop over Fourier wavenumbers */ for (index_k=0; index_k < ppm->lnk_size; index_k++) { k = exp(ppm->lnk[index_k]); /* evolve background until k=aH is reached */ class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, k, _FALSE_, forward, conformal), ppm->error_message, ppm->error_message); /** - read value of phi at time when k=aH */ phi_k = y[ppm->index_in_phi]; /** - get potential (and its derivatives) at this value */ class_call(primordial_inflation_check_potential(ppm,phi_k,&V,&dV,&ddV), ppm->error_message, ppm->error_message); /** - calculate the analytic slow-roll formula for the spectra */ curvature = 128.*_PI_/3.*pow(V,3)/pow(dV,2); tensors = pow(dV/V,2)/_PI_*128.*_PI_/3.*pow(V,3)/pow(dV,2); /** - store the obtained result for curvature and tensor perturbations */ ppm->lnpk[ppt->index_md_scalars][index_k] = log(curvature); ppm->lnpk[ppt->index_md_tensors][index_k] = log(tensors); } ppm->is_non_zero[ppt->index_md_scalars][ppt->index_ic_ad] = _TRUE_; ppm->is_non_zero[ppt->index_md_tensors][ppt->index_ic_ten] = _TRUE_; return _SUCCESS_; } /** * Routine with a loop over wavenumbers for the computation of the primordial * spectrum. For each wavenumber it calls primordial_inflation_one_wavenumber() * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param y_ini Input: initial conditions for the vector of background/perturbations, already allocated and filled * @return the error status */ int primordial_inflation_spectra( struct perturbs * ppt, struct primordial * ppm, struct precision * ppr, double * y_ini ) { int index_k; /* number of threads (always one if no openmp) */ int number_of_threads=1; /* index of the thread (always 0 if no openmp) */ int thread=0; /* This code can be optionally compiled with the openmp option for parallel computation. Inside parallel regions, the use of the command "return" is forbidden. For error management, instead of "return _FAILURE_", we will set the variable below to "abort = _TRUE_". This will lead to a "return _FAILURE_" just after leaving the parallel region. */ int abort; #ifdef _OPENMP /* instrumentation times */ double tstart, tstop, tspent; #endif #ifdef _OPENMP #pragma omp parallel { number_of_threads = omp_get_num_threads(); } #endif abort = _FALSE_; #pragma omp parallel shared(ppt,ppm,ppr,abort,y_ini) private(index_k,thread,tspent,tstart,tstop) num_threads(number_of_threads) { #ifdef _OPENMP thread = omp_get_thread_num(); tspent=0.; #endif #pragma omp for schedule (dynamic) /* loop over Fourier wavenumbers */ for (index_k=0; index_k < ppm->lnk_size; index_k++) { #ifdef _OPENMP tstart = omp_get_wtime(); #endif class_call_parallel(primordial_inflation_one_wavenumber(ppt,ppm,ppr,y_ini,index_k), ppm->error_message, ppm->error_message); #ifdef _OPENMP tstop = omp_get_wtime(); tspent += tstop-tstart; #endif } #ifdef _OPENMP if (ppm->primordial_verbose>1) printf("In %s: time spent in parallel region (loop over k's) = %e s for thread %d\n", __func__,tspent,thread); #endif } /* end of parallel zone */ if (abort == _TRUE_) return _FAILURE_; ppm->is_non_zero[ppt->index_md_scalars][ppt->index_ic_ad] = _TRUE_; ppm->is_non_zero[ppt->index_md_tensors][ppt->index_ic_ten] = _TRUE_; return _SUCCESS_; } /** * Routine coordinating the computation of the primordial * spectrum for one wavenumber. It calls primordial_inflation_one_k() to * integrate the perturbation equations, and then it stores the result * for the scalar/tensor spectra. * * @param ppt Input: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param y_ini Input: initial conditions for the vector of background/perturbations, already allocated and filled * @param index_k Input: index of wavenumber to be considered * @return the error status */ int primordial_inflation_one_wavenumber( struct perturbs * ppt, struct primordial * ppm, struct precision * ppr, double * y_ini, int index_k ) { double k; double curvature,tensors; double * y; double * dy; k = exp(ppm->lnk[index_k]); /** Summary */ /** - allocate vectors for background/perturbed quantities */ class_alloc(y,ppm->in_size*sizeof(double),ppm->error_message); class_alloc(dy,ppm->in_size*sizeof(double),ppm->error_message); /** - initialize the background part of the running vector */ y[ppm->index_in_a] = y_ini[ppm->index_in_a]; y[ppm->index_in_phi] = y_ini[ppm->index_in_phi]; if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) y[ppm->index_in_dphi] = y_ini[ppm->index_in_dphi]; /** - evolve the background until the relevant initial time for integrating perturbations */ class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, k/ppr->primordial_inflation_ratio_min, _FALSE_, forward, conformal), ppm->error_message, ppm->error_message); /** - evolve the background/perturbation equations from this time and until some time after Horizon crossing */ class_call(primordial_inflation_one_k(ppm, ppr, k, y, dy, &curvature, &tensors), ppm->error_message, ppm->error_message); free(y); free(dy); class_test(curvature<=0., ppm->error_message, "negative curvature spectrum"); class_test(tensors<=0., ppm->error_message, "negative tensor spectrum"); /** - store the obtained result for curvature and tensor perturbations */ ppm->lnpk[ppt->index_md_scalars][index_k] = log(curvature); ppm->lnpk[ppt->index_md_tensors][index_k] = log(tensors); /* uncomment if you want to print here the spectra for testing */ /* fprintf(stderr,"%e %e %e\n", */ /* ppm->lnk[index_k], */ /* ppm->lnpk[ppt->index_md_scalars][index_k], */ /* ppm->lnpk[ppt->index_md_tensors][index_k]); */ return _SUCCESS_; } /** * Routine integrating the background plus perturbation equations for * each wavenumber, and returning the scalar and tensor spectrum. * * @param ppm Input: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param k Input: Fourier wavenumber * @param y Input: running vector of background/perturbations, already allocated and initialized * @param dy Input: running vector of background/perturbation derivatives, already allocated * @param curvature Output: curvature perturbation * @param tensor Output: tensor perturbation * @return the error status */ int primordial_inflation_one_k( struct primordial * ppm, struct precision * ppr, double k, double * y, double * dy, double * curvature, double * tensor ) { /** Summary: */ /** - define local variables */ double tau_start,tau_end,dtau; double z,ksi2,ah2; double aH; double curvature_old; double curvature_new; double dlnPdN; struct primordial_inflation_parameters_and_workspace pipaw; struct generic_integrator_workspace gi; /** - initialize the generic integrator (same integrator already used in background, thermodynamics and perturbation modules) */ pipaw.ppm = ppm; pipaw.N = ppm->in_size; pipaw.integrate = forward; pipaw.time = conformal; pipaw.k = k; class_call(initialize_generic_integrator(pipaw.N,&gi), gi.error_message, ppm->error_message); /* initial conditions for the perturbations, Bunch-Davies vacuum */ y[ppm->index_in_ksi_re]=1./sqrt(2.*k); y[ppm->index_in_ksi_im]=0.; y[ppm->index_in_dksi_re]=0.; y[ppm->index_in_dksi_im]=-k*y[ppm->index_in_ksi_re]; y[ppm->index_in_ah_re]=1./sqrt(2.*k); y[ppm->index_in_ah_im]=0.; y[ppm->index_in_dah_re]=0.; y[ppm->index_in_dah_im]=-k*y[ppm->index_in_ah_re]; /** - initialize variable used for deciding when to stop the calculation (= when the curvature remains stable) */ curvature_new = _HUGE_; /** - initialize conformal time to arbitrary value (here, only variations of tau matter: the equations that we integrate do not depend explicitly on time) */ tau_end = 0; /** - compute derivative of initial vector and infer first value of adaptive time-step */ class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); dtau = ppr->primordial_inflation_pt_stepsize*2.*_PI_ /MAX(sqrt(fabs(dy[ppm->index_in_dksi_re]/y[ppm->index_in_ksi_re])),k); /** - loop over time */ do { /* new time interval [tau_start, tau_end] over which equations will be integrated */ tau_start = tau_end; tau_end = tau_start + dtau; class_test(dtau/tau_start < ppr->smallest_allowed_variation, ppm->error_message, "integration step: relative change in time =%e < machine precision : leads either to numerical error or infinite loop",dtau/tau_start); /* evolve the system */ class_call(generic_integrator(primordial_inflation_derivs, tau_start, tau_end, y, &pipaw, ppr->primordial_inflation_tol_integration, ppr->smallest_allowed_variation, &gi), gi.error_message, ppm->error_message); /* compute derivatives at tau_end, useful to infer new time step and spectra */ class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); /* new time step */ dtau = ppr->primordial_inflation_pt_stepsize*2.*_PI_ /MAX(sqrt(fabs(dy[ppm->index_in_dksi_re]/y[ppm->index_in_ksi_re])),k); /* new aH */ aH = dy[ppm->index_in_a]/y[ppm->index_in_a]; /* store previous value of curvature (at tau_start) */ curvature_old = curvature_new; /* new curvature */ z = y[ppm->index_in_a]*dy[ppm->index_in_phi]/aH; ksi2 = y[ppm->index_in_ksi_re]*y[ppm->index_in_ksi_re]+y[ppm->index_in_ksi_im]*y[ppm->index_in_ksi_im]; curvature_new = k*k*k/2./_PI_/_PI_*ksi2/z/z; /* variation of curvature with time (dimensionless) */ dlnPdN = (curvature_new-curvature_old)/dtau*y[ppm->index_in_a]/dy[ppm->index_in_a]/curvature_new; /* stop when (k >> aH) AND curvature is stable */ } while ((k/aH >= ppr->primordial_inflation_ratio_max) || (fabs(dlnPdN) > ppr->primordial_inflation_tol_curvature)); /** - clean the generic integrator */ class_call(cleanup_generic_integrator(&gi), gi.error_message, ppm->error_message); /** - store final value of curvature for this wavenumber */ *curvature = curvature_new; /** - store final value of tensor perturbation for this wavenumber */ ah2 = y[ppm->index_in_ah_re]*y[ppm->index_in_ah_re]+y[ppm->index_in_ah_im]*y[ppm->index_in_ah_im]; *tensor = 32.*k*k*k/_PI_*ah2/y[ppm->index_in_a]/y[ppm->index_in_a]; //fprintf(stdout,"%g %g %g %g %g\n",k,*curvature,*tensor,*tensor/(*curvature),dlnPdN); return _SUCCESS_; } /** * Routine searching for the inflationary attractor solution at a * given phi_0, by iterations, with a given tolerance. If no solution * found within tolerance, returns error message. The principle is the * following. The code starts integrating the background equations * from various values of phi, corresponding to earlier and earlier * value before phi_0, and separated by a small arbitrary step size, * corresponding roughly to 1 e-fold of inflation. Each time, the * integration starts with the initial condition \f$ \phi=-V'/3H\f$ (slow-roll * prediction). If the found value of \f$\phi'\f$ in phi_0 is stable (up to * the parameter "precision"), the code considers that there is an * attractor, and stops iterating. If this process does not converge, * it returns an error message. * * @param ppm Input: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param phi_0 Input: field value at which we wish to find the solution * @param precision Input: tolerance on output values (if too large, an attractor will always considered to be found) * @param y Input: running vector of background variables, already allocated and initialized * @param dy Input: running vector of background derivatives, already allocated * @param H_0 Output: Hubble value at phi_0 for attractor solution * @param dphidt_0 Output: field derivative value at phi_0 for attractor solution * @return the error status */ int primordial_inflation_find_attractor( struct primordial * ppm, struct precision * ppr, double phi_0, double precision, double * y, double * dy, double * H_0, double * dphidt_0 ) { double V_0,dV_0,ddV_0; double V=0.,dV=0.,ddV=0.; double a; double dphidt,dphidt_0new,dphidt_0old,phi; int counter; /* we want a series of value of phi' in phi_0, obtained by integrating the system from earlier and earlier time. The first value iof the series is the slow-roll prediction phi' = -V'/3H. The following lines compute this value and initialize relevant quantities. */ class_call(primordial_inflation_check_potential(ppm,phi_0,&V_0,&dV_0,&ddV_0), ppm->error_message, ppm->error_message); dphidt_0new = -dV_0/3./sqrt((8.*_PI_/3.)*V_0); phi = phi_0; counter = 0; dphidt_0old = dphidt_0new/(precision+2.); // this silly value just // ensures that the loop // below will be executed // at least once. /* loop over different values of phi, from which the background equations are integrated until phi_0 */ while (fabs(dphidt_0new/dphidt_0old-1.) >= precision) { counter ++; class_test(counter >= ppr->primordial_inflation_attractor_maxit, ppm->error_message, "could not converge after %d iterations: there exists no attractor solution near phi=%g. Potential probably too steep in this region, or precision parameter primordial_inflation_attractor_precision=%g too small", counter, phi_0, precision); dphidt_0old = dphidt_0new; /* take one step in phi, corresponding roughly to adding one more e-fold of inflation */ phi=phi+dV_0/V_0/16./_PI_; /* fix the initial phi' to the slow-roll prediction in that point, and initialize other relevant quantities */ class_call(primordial_inflation_check_potential(ppm,phi,&V,&dV,&ddV), ppm->error_message, ppm->error_message); a = 1.; dphidt = -dV/3./sqrt((8.*_PI_/3.)*V); y[ppm->index_in_a]=a; y[ppm->index_in_phi]=phi; y[ppm->index_in_dphi]=a*dphidt; /* evolve the background equations until phi_0 is reached */ class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _phi_, phi_0, _TRUE_, forward, conformal), ppm->error_message, ppm->error_message); /* compute phi' in phi_0, this is the new point in the series which convergence we want to check */ dphidt_0new = y[ppm->index_in_dphi]/y[ppm->index_in_a]; } /* if we have converged and found the attractor, we take the last value of phi' in phi_0 to be the correct one for the attractor solution */ *dphidt_0 = dphidt_0new; *H_0 = sqrt((8.*_PI_/3.)*(0.5*dphidt_0new*dphidt_0new+V_0)); if (ppm->primordial_verbose > 1) { printf(" (attractor found in phi=%g with phi'=%g, H=%g)\n",phi_0,*dphidt_0,*H_0); } return _SUCCESS_; } /** * Routine integrating background equations only, from initial values * stored in y, to a final value (if target = _aH_, until aH = * aH_stop; if target = _phi_, till phi = phi_stop; if target = * _end_inflation_, until \f$ d^2a/dt^2 = 0\f$ (here t = proper time)). In * output, y contains the final background values. In addition, if * check_epsilon is true, the routine controls at each step that the * expansion is accelerated and that inflation holds (wepsilon>1), * otherwise it returns an error. Thanks to the last argument, it is * also possible to specify whether the integration should be carried * forward or backward in time. For the inflation_H case, only a 1st * order differential equation is involved, so the forward and * backward case can be done exactly without problems. For the * inflation_V case, the equation of motion is 2nd order. What the * module will do in the backward case is to search for an approximate * solution, corresponding to the (first-order) attractor inflationary * solution. This approximate backward solution is used in order to * estimate some initial times, but the approximation made here will * never impact the final result: the module is written in such a way * that after using this approximation, the code always computes (and * relies on) the exact forward solution. * * @param ppm Input: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param y Input/output: running vector of background variables, already allocated and initialized * @param dy Input: running vector of background derivatives, already allocated * @param target Input: whether the goal is to reach a given aH or \f$ \phi \f$ * @param stop Input: the target value of either aH or \f$ \phi \f$ * @param check_epsilon Input: whether we should impose inflation (epsilon>1) at each step * @param direction Input: whether we should integrate forward or backward in time * @param time Input: definition of time (proper or conformal) * @return the error status */ int primordial_inflation_evolve_background( struct primordial * ppm, struct precision * ppr, double * y, double * dy, enum target_quantity target, double stop, short check_epsilon, enum integration_direction direction, enum time_definition time ) { struct primordial_inflation_parameters_and_workspace pipaw; struct generic_integrator_workspace gi; double tau_start,tau_end,dtau=0.; double H,dH,ddH,dddH; double epsilon,epsilon_old; double quantity=0.; double V,dV,ddV; double sign_dtau=0.; pipaw.ppm = ppm; pipaw.N = ppm->in_bg_size; if ((direction == backward) && ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end))) { // -1 to remove the differential equation for phi', since we stick to the attractor pipaw.N -= 1; } pipaw.integrate = direction; pipaw.time = time; switch (direction) { case forward: sign_dtau = 1.; break; case backward: sign_dtau = -1.; break; } class_call(initialize_generic_integrator(pipaw.N,&gi), gi.error_message, ppm->error_message); /* at starting point, compute eventually epsilon */ if (check_epsilon == _TRUE_) { class_call(primordial_inflation_get_epsilon(ppm, y[ppm->index_in_phi], &epsilon), ppm->error_message, ppm->error_message); } /* at starting point, compute the stepsize dtau */ tau_end = 0; class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); // compute timestep (if time = conformal, dtau is the conformal time step, // if time = proper, dtau is in fact dt, the proper time step) if ((direction == forward) && ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end))) { dtau = ppr->primordial_inflation_bg_stepsize *MIN(y[ppm->index_in_a]/dy[ppm->index_in_a],fabs(y[ppm->index_in_dphi]/dy[ppm->index_in_dphi])); } else { // minus sign for backward in time dtau = sign_dtau * ppr->primordial_inflation_bg_stepsize*y[ppm->index_in_a]/dy[ppm->index_in_a]; } /* expected value of target quantity after the next step */ switch (target) { case _aH_: // next (approximate) value of aH after next step // (a+[da/dx]*dx) H = aH (1 + [da/dx] / a dx) // where dtau can be conformal or proper time quantity = dy[ppm->index_in_a] * (1.+ dy[ppm->index_in_a]/y[ppm->index_in_a] * dtau); if (time == conformal) quantity /= y[ppm->index_in_a]; break; case _phi_: // next (approximate) value of phi after next step quantity = y[ppm->index_in_phi]+dy[ppm->index_in_phi]*dtau; break; case _end_inflation_: // in this case, the goal is to reach d2a/dt2 = 0 (end of accelerated expansion) stop = 0.; // current value of quantity = - d2a/dt2 /a = [- (a'/a)^2 + 3/2 8pi/3 phi'^2]/a^2 quantity = -pow(dy[ppm->index_in_a]/y[ppm->index_in_a],2) + 4*_PI_ * y[ppm->index_in_dphi] * y[ppm->index_in_dphi]; if (time == conformal) quantity /= pow(y[ppm->index_in_a],2); // check that we are in the right case class_test(ppm->primordial_spec_type != inflation_V_end, ppm->error_message, "the target _end_inflation_ is only coded to work with inflation_V_end (but could be generalized if needed)"); break; case _a_: // next (approximate) value of a after next step quantity = y[ppm->index_in_a]+dy[ppm->index_in_a]*dtau; break; } /* loop over time steps, checking that there will be no overshooting */ while (sign_dtau*(quantity - stop) < 0.) { /* check that V(phi) or H(phi) do not take forbidden values (negative or positive derivative) */ if ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end)) { class_call(primordial_inflation_check_potential(ppm, y[ppm->index_in_phi], &V, &dV, &ddV), ppm->error_message, ppm->error_message); } else { class_call(primordial_inflation_check_hubble(ppm, y[ppm->index_in_phi], &H, &dH, &ddH, &dddH), ppm->error_message, ppm->error_message); } /* take one time step */ tau_start = tau_end; tau_end = tau_start + dtau; // mind the fabs(...) below (works for both forward and backward integration) class_test(fabs(dtau/tau_start) < ppr->smallest_allowed_variation, ppm->error_message, "integration step: relative change in time =%e < machine precision : leads either to numerical error or infinite loop",dtau/tau_start); class_call(generic_integrator(primordial_inflation_derivs, tau_start, tau_end, y, &pipaw, ppr->primordial_inflation_tol_integration, ppr->smallest_allowed_variation, &gi), gi.error_message, ppm->error_message); /* eventually, check that epsilon is not becoming greater than one */ if (check_epsilon == _TRUE_) { epsilon_old = epsilon; class_call_except(primordial_inflation_get_epsilon(ppm, y[ppm->index_in_phi], &epsilon), ppm->error_message, ppm->error_message, cleanup_generic_integrator(&gi)); class_test_except((epsilon > 1) && (epsilon_old <= 1), ppm->error_message, cleanup_generic_integrator(&gi), "Inflaton evolution crosses the border from epsilon<1 to epsilon>1 at phi=%g. Inflation disrupted during the observable e-folds", y[ppm->index_in_phi]); } /* recompute new value of next conformal time step */ class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); // compute timestep (if time = conformal, dtau is the conformal time step, // if time = proper, dtau is in fact dt, the proper time step) if ((direction == forward) && ((ppm->primordial_spec_type == inflation_V) || (ppm->primordial_spec_type == inflation_V_end))) { dtau = ppr->primordial_inflation_bg_stepsize *MIN(y[ppm->index_in_a]/dy[ppm->index_in_a],fabs(y[ppm->index_in_dphi]/dy[ppm->index_in_dphi])); } else { // minus sign for backward in time dtau = sign_dtau * ppr->primordial_inflation_bg_stepsize*y[ppm->index_in_a]/dy[ppm->index_in_a]; } /* expected value of target quantity after the next step */ switch (target) { case _aH_: // next (approximate) value of aH after next step // (a+[da/dx]*dx) H = aH (1 + [da/dx] / a dx) // where dtau can be conformal or proper time quantity = dy[ppm->index_in_a] * (1.+ dy[ppm->index_in_a]/y[ppm->index_in_a] * dtau); if (time == conformal) quantity /= y[ppm->index_in_a]; break; case _phi_: // next (approximate) value of phi after next step quantity = y[ppm->index_in_phi]+dy[ppm->index_in_phi]*dtau; break; case _end_inflation_: // current value of quantity = - d2a/dt2 /a = [- (a'/a)^2 + 3/2 8pi/3 phi'^2]/a^2 quantity = -pow(dy[ppm->index_in_a]/y[ppm->index_in_a],2) + 4*_PI_ * y[ppm->index_in_dphi] * y[ppm->index_in_dphi]; if (time == conformal) quantity /= pow(y[ppm->index_in_a],2); break; case _a_: // next (approximate) value of a after next step quantity = y[ppm->index_in_a]+dy[ppm->index_in_a]*dtau; break; } } /* won't use the integrator anymore */ class_call(cleanup_generic_integrator(&gi), gi.error_message, ppm->error_message); /* Perform one last step with a simple trapezoidal integral. This will bring exactly phi or a forward to phi_stop or a_stop, or approximately aH forward to aH_stop, or approximately [-d2a/dt2 /a] backward to zero. */ switch (target) { case _aH_: switch (time){ case proper: dtau = (stop/dy[ppm->index_in_a]-1.)/dy[ppm->index_in_a]; break; case conformal: dtau = (stop/(dy[ppm->index_in_a]/y[ppm->index_in_a])-1.)/(dy[ppm->index_in_a]/y[ppm->index_in_a]); break; } break; case _phi_: dtau = (stop-y[ppm->index_in_phi])/dy[ppm->index_in_phi]; break; case _end_inflation_: class_call(primordial_inflation_check_potential(ppm,y[ppm->index_in_phi],&V,&dV,&ddV), ppm->error_message, ppm->error_message); // We can easily pull back quantity=-d2a/dt2 /a by noticing that // d(quantity)/dtau = 8piG phi' phi'' / a^2 (exact relation!) // or // d(quantity)/dtau = 8piG phi^dot (a phi^dot)^dot = 8piG phi^dot (a^dot phi^dot+ a phi^dotdot) // By taking the step dtau = - quantity / [d(quantity)/dtau] we nearly reach quantity=0 (end of inflation), up to very good approximation switch (time){ case proper: dtau = -quantity/(8.*_PI_*dy[ppm->index_in_phi]*(dy[ppm->index_in_a]*dy[ppm->index_in_phi]+y[ppm->index_in_a]*dy[ppm->index_in_dphi])); break; case conformal: dtau = -quantity/(8.*_PI_/y[ppm->index_in_a]/y[ppm->index_in_a]*dy[ppm->index_in_phi]*dy[ppm->index_in_dphi]); break; } break; case _a_: dtau = (stop-y[ppm->index_in_a])/dy[ppm->index_in_a]; break; } y[ppm->index_in_a] += dy[ppm->index_in_a]*dtau; y[ppm->index_in_phi] += dy[ppm->index_in_phi]*dtau; if ((direction == forward) && ((ppm->primordial_spec_type == inflation_V)||(ppm->primordial_spec_type == inflation_V_end))) y[ppm->index_in_dphi] += dy[ppm->index_in_dphi]*dtau; // this last step updates also the dy[] class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); // uncomment if you want to test that the routine really reached the point at which d2a/dt2=0 /* if (target == _end_inflation_) { class_call(primordial_inflation_derivs(tau_end, y, dy, &pipaw, ppm->error_message), ppm->error_message, ppm->error_message); aH = dy[ppm->index_in_a]/y[ppm->index_in_a]; quantity = (-aH*aH + 4*_PI_ * y[ppm->index_in_dphi] * y[ppm->index_in_dphi])/y[ppm->index_in_a]/y[ppm->index_in_a]; if (ppm->primordial_verbose>1) printf(" (-d2a/dt2 /a = %e)\n",quantity); } */ return _SUCCESS_; } /** * Routine checking positivity and negative slope of potential. The * negative slope is an arbitrary choice. Currently the code can only * deal with monotonic variations of the inflaton during inflation. So * the slope had to be always negative or always positive... we took * the first option. * * @param ppm Input: pointer to primordial structure * @param phi Input: field value where to perform the check * @param V Output: inflaton potential in units of \f$ Mp^4\f$ * @param dV Output: first derivative of inflaton potential wrt the field * @param ddV Output: second derivative of inflaton potential wrt the field * @return the error status */ int primordial_inflation_check_potential( struct primordial * ppm, double phi, double * V, double * dV, double * ddV ) { class_call(primordial_inflation_potential(ppm,phi,V,dV,ddV), ppm->error_message, ppm->error_message); class_test(*V <= 0., ppm->error_message, "This potential becomes negative at phi=%g, before the end of observable inflation. It cannot be treated by this code", phi); class_test(*dV >= 0., ppm->error_message, "All the code is written for the case dV/dphi<0. Here, in phi=%g, we have dV/dphi=%g. This potential cannot be treated by this code", phi,*dV); return _SUCCESS_; } /** * Routine checking positivity and negative slope of \f$ H(\phi)\f$. The * negative slope is an arbitrary choice. Currently the code can only * deal with monotonic variations of the inflaton during * inflation. And H can only decrease with time. So the slope \f$ dH/d\phi\f$ * has to be always negative or always positive... we took the first * option: phi increases, H decreases. * * @param ppm Input: pointer to primordial structure * @param phi Input: field value where to perform the check * @param H Output: Hubble parameters in units of Mp * @param dH Output: \f$ dH / d\phi \f$ * @param ddH Output: \f$ d^2H / d\phi^2 \f$ * @param dddH Output: \f$ d^3H / d\phi^3 \f$ * @return the error status */ int primordial_inflation_check_hubble( struct primordial * ppm, double phi, double * H, double * dH, double * ddH, double * dddH ) { class_call(primordial_inflation_hubble(ppm, phi, H,dH,ddH,dddH), ppm->error_message, ppm->error_message); class_test(*H < 0., ppm->error_message, "this H(phi) is not physical. H = %e", *H); class_test(*dH > 0., ppm->error_message, "this H(phi) is not decreasing with growing phi. dH/dphi = %e", *dH); return _SUCCESS_; } /** * Routine computing the first slow-roll parameter epsilon * * @param ppm Input: pointer to primordial structure * @param phi Input: field value where to compute epsilon * @param epsilon Output: result * @return the error status */ int primordial_inflation_get_epsilon( struct primordial * ppm, double phi, double * epsilon ) { double V,dV,ddV; double H,dH,ddH,dddH; switch (ppm->primordial_spec_type) { case inflation_V: case inflation_V_end: class_call(primordial_inflation_potential(ppm, phi, &V,&dV,&ddV), ppm->error_message, ppm->error_message); *epsilon = 1./16./_PI_*pow(dV/V,2); //*eta = 1./8./pi*(ddV/V) break; case inflation_H: class_call(primordial_inflation_hubble(ppm, phi, &H,&dH,&ddH,&dddH), ppm->error_message, ppm->error_message); *epsilon = 1./4./_PI_*pow(dH/H,2); break; default: class_stop(ppm->error_message,"ppm->primordial_spec_type=%d different from possible relevant cases",ppm->primordial_spec_type); break; } return _SUCCESS_; } /** * Routine searching phi_pivot when a given amount of inflation is requested. * * @param ppm Input/output: pointer to primordial structure * @param ppr Input: pointer to precision structure * @param y Input: running vector of background variables, already allocated and initialized * @param dy Input: running vector of background derivatives, already allocated * @return the error status */ int primordial_inflation_find_phi_pivot( struct primordial * ppm, struct precision * ppr, double * y, double * dy ) { /** Summary: */ /** - define local variables */ double epsilon,dphi; double phi_try,H_try,dphidt_try,ratio_try=0.; double phi_left,phi_right,phi_mid; double phi_small_epsilon,phi_stop; double dphidt_small_epsilon; double H_small_epsilon; double aH_ratio_after_small_epsilon=0.; double a_ratio_after_small_epsilon=0.; double target=0.; double a_pivot,aH_pivot; double rho_end; double h; double H0; double rho_c0; double sigma_B; double Omega_g0; double Omega_r0; /** - check whether in vicinity of phi_end, inflation is still ongoing */ class_call(primordial_inflation_get_epsilon(ppm,ppm->phi_end-ppr->primordial_inflation_end_dphi,&epsilon), ppm->error_message, ppm->error_message); /** - case in which epsilon>1: hence we must find the value phi_stop < phi_end where inflation ends up naturally */ if (epsilon > 1.) { // assume that inflation ends up naturally /** - --> find latest value of the field such that epsilon = primordial_inflation_small_epsilon (default: 0.1) */ /** - --> bracketing right-hand value is phi_end (but the potential will not be evaluated exactly there, only closeby */ phi_right = ppm->phi_end; /** - --> bracketing left-hand value is found by iterating with logarithmic step until epsilon < primordial_inflation_small_epsilon */ dphi = ppr->primordial_inflation_end_dphi; do { dphi *= ppr->primordial_inflation_end_logstep; class_call(primordial_inflation_get_epsilon(ppm,ppm->phi_end-dphi,&epsilon), ppm->error_message, ppm->error_message); } while (epsilon > ppr->primordial_inflation_small_epsilon); phi_left = ppm->phi_end-dphi; /** - --> find value such that epsilon = primordial_inflation_small_epsilon by bisection */ do { phi_mid = 0.5*(phi_left+phi_right); class_call(primordial_inflation_get_epsilon(ppm,phi_mid,&epsilon), ppm->error_message, ppm->error_message); if (epsilon < ppr->primordial_inflation_small_epsilon) phi_left=phi_mid; else phi_right=phi_mid; } while (fabs(epsilon-ppr->primordial_inflation_small_epsilon) > ppr->primordial_inflation_small_epsilon_tol); /** - --> value found and stored as phi_small_epsilon */ phi_small_epsilon = phi_mid; /** - --> find inflationary attractor in phi_small_epsilon (should exist since epsilon<<1 there) */ class_call(primordial_inflation_find_attractor(ppm, ppr, phi_small_epsilon, ppr->primordial_inflation_attractor_precision_initial, y, dy, &H_small_epsilon, &dphidt_small_epsilon), ppm->error_message, ppm->error_message); /** - --> compute amount of inflation between this phi_small_epsilon and the end of inflation */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_small_epsilon; y[ppm->index_in_dphi]=y[ppm->index_in_a]*dphidt_small_epsilon; class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _end_inflation_, 0., _FALSE_, forward, conformal), ppm->error_message, ppm->error_message); // we have used here conformal time, so aH = dy[a]/y[a] aH_ratio_after_small_epsilon = dy[ppm->index_in_a]/y[ppm->index_in_a]/H_small_epsilon; a_ratio_after_small_epsilon = y[ppm->index_in_a]; switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: /* get the target value of ln_aH_ratio */ rho_end = 2./8./_PI_*pow(dy[ppm->index_in_a]/y[ppm->index_in_a],2); rho_end = 8*_PI_/3.*rho_end/(_G_*_h_P_/pow(_c_,3))*pow(_Mpc_over_m_,2); h = 0.7; H0 = h * 1.e5 / _c_; rho_c0 = pow(H0,2); sigma_B = 2. * pow(_PI_,5) * pow(_k_B_,4) / 15. / pow(_h_P_,3) / pow(_c_,2); Omega_g0 = (4.*sigma_B/_c_*pow(2.726,4.)) / (3.*_c_*_c_*1.e10*h*h/_Mpc_over_m_/_Mpc_over_m_/8./_PI_/_G_); Omega_r0 = 3.046*7./8.*pow(4./11.,4./3.)*Omega_g0; target = log(H0/0.05*pow(Omega_r0,0.5)*pow(2./100.,1./12.)*pow(rho_end/rho_c0,0.25)); //fprintf(stderr,"auto: log(aH_end/aH_*)=%e\n",target); break; case ln_aH_ratio: target = ppm->phi_pivot_target; //fprintf(stderr,"fixed: log(aH_end/aH_*)=%e\n",target); break; case N_star: target = ppm->phi_pivot_target; //fprintf(stderr,"fixed: log(a_end/a_*)=%e\n",target); break; } /** - --> by starting from phi_small_epsilon and integrating an approximate solution backward in time, try to estimate roughly a value close to phi_pivot but a bit smaller. This is done by trying to reach an amount of inflation equal to the requested one, minus the amount after phi_small_epsilon, and plus primordial_inflation_extra_efolds efolds (default: two). Note that it is not aggressive to require two extra e-folds of inflation before the pivot, since the calculation of the spectrum in the observable range will require even more. */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_small_epsilon; switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, H_small_epsilon/exp(target+ppr->primordial_inflation_extra_efolds)*aH_ratio_after_small_epsilon, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message); break; case N_star: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _a_, 1./exp(target+ppr->primordial_inflation_extra_efolds)*a_ratio_after_small_epsilon, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message); break; } /* we now have a value phi_try believed to be close to and slightly smaller than phi_pivot */ phi_try = y[ppm->index_in_phi]; /** - --> find attractor in phi_try */ class_call(primordial_inflation_find_attractor(ppm, ppr, phi_try, ppr->primordial_inflation_attractor_precision_initial, y, dy, &H_try, &dphidt_try), ppm->error_message, ppm->error_message); /** - --> check the total amount of inflation between phi_try and the end of inflation */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_try; y[ppm->index_in_dphi]= dphidt_try; class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _end_inflation_, 0., _FALSE_, forward, proper), ppm->error_message, ppm->error_message); switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: // aH_ratio (we have used here proper time, so aH = dy[a]) ratio_try = dy[ppm->index_in_a]/H_try; break; case N_star: // a_ratio ratio_try = y[ppm->index_in_a]; break; } class_test(log(ratio_try) < target, ppm->error_message, "phi_try not small enough, log(aH_stop/aH_try) or log(a_stop/a_try) (depending on what you asked) is equal to %e instead of requested %e; must write here a loop to deal automatically with this situation (by decreasing phi_try iteratively), or must increase precision parameter primordial_inflation_extra_efolds", log(ratio_try), target); phi_stop = y[1]; if (ppm->primordial_verbose > 1) printf(" (inflation stops in phi_stop = %e)\n",phi_stop); /** - --> go back to phi_try, and now find phi_pivot such that the amount of inflation between phi_pivot and the end of inflation is exactly the one requested. */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_try; y[ppm->index_in_dphi]= dphidt_try; switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, H_try*ratio_try/exp(target), _FALSE_, forward, proper), ppm->error_message, ppm->error_message); break; case N_star: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _a_, ratio_try/exp(target), _FALSE_, forward, proper), ppm->error_message, ppm->error_message); break; } ppm->phi_pivot = y[1]; if (ppm->primordial_verbose > 1) { printf(" (reached phi_pivot=%e)\n",ppm->phi_pivot); /* - --> In verbose mode, check that phi_pivot is correct. Done by restarting from phi_pivot and going again till the end of inflation. */ aH_pivot = dy[0]; a_pivot = y[0]; class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _end_inflation_, 0., _FALSE_, forward, proper), ppm->error_message, ppm->error_message); printf(" (from phi_pivot till the end, ln(aH_2/aH_1) = %e, ln(a_2/a_1) = %e)\n",log(dy[0]/aH_pivot),log(y[0]/a_pivot)); } } /** - case in which epsilon<1: */ else { /** - --> find inflationary attractor in phi_small_epsilon (should exist since epsilon<1 there) */ class_call(primordial_inflation_find_attractor(ppm, ppr, ppm->phi_end, ppr->primordial_inflation_attractor_precision_initial, y, dy, &H_small_epsilon, &dphidt_small_epsilon), ppm->error_message, ppm->error_message); /** - --> by starting from phi_end and integrating an approximate solution backward in time, try to estimate roughly a value close to phi_pivot but a bit smaller. This is done by trying to reach an amount of inflation equal to the requested one, minus the amount after phi_small_epsilon, and plus primordial_inflation_extra_efolds efolds (default: two). Note that it is not aggressive to require two extra e-folds of inflation before the pivot, since the calculation of the spectrum in the observable range will require even more. */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= ppm->phi_end; switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, H_small_epsilon/exp(target+ppr->primordial_inflation_extra_efolds)*aH_ratio_after_small_epsilon, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message); break; case N_star: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _a_, 1./exp(target+ppr->primordial_inflation_extra_efolds)*a_ratio_after_small_epsilon, _TRUE_, backward, conformal), ppm->error_message, ppm->error_message); break; } /** - --> we now have a value phi_try believed to be close to and slightly smaller than phi_pivot */ phi_try = y[ppm->index_in_phi]; /** - --> find attractor in phi_try */ class_call(primordial_inflation_find_attractor(ppm, ppr, phi_try, ppr->primordial_inflation_attractor_precision_initial, y, dy, &H_try, &dphidt_try), ppm->error_message, ppm->error_message); /** - --> check the total amount of inflation between phi_try and the end of inflation */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_try; y[ppm->index_in_dphi]= dphidt_try; class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _phi_, ppm->phi_end, _FALSE_, forward, proper), ppm->error_message, ppm->error_message); switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: // aH_ratio (we have used here proper time, so aH = dy[a]) ratio_try = dy[ppm->index_in_a]/H_try; break; case N_star: // a_ratio ratio_try = y[ppm->index_in_a]; break; } class_test(log(ratio_try) < target, ppm->error_message, "phi_try not small enough, log(aH_stop/aH_try) or log(a_stop/a_try) (depending on what you asked) is equal to %e instead of requested %e; must write here a loop to deal automatically with this situation (by decreasing phi_try iteratively), or must increase precision parameter primordial_inflation_extra_efolds", log(ratio_try), target); phi_stop = y[1]; if (ppm->primordial_verbose > 1) printf(" (inflation stops in phi_stop = %e)\n",phi_stop); /** - --> go back to phi_try, and now find phi_pivot such that the amount of inflation between phi_pivot and the end of inflation is exactly the one requested. */ y[ppm->index_in_a]=1.; y[ppm->index_in_phi]= phi_try; y[ppm->index_in_dphi]= dphidt_try; switch (ppm->phi_pivot_method) { case ln_aH_ratio_auto: case ln_aH_ratio: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _aH_, H_try*ratio_try/exp(target), _FALSE_, forward, proper), ppm->error_message, ppm->error_message); break; case N_star: class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _a_, ratio_try/exp(target), _FALSE_, forward, proper), ppm->error_message, ppm->error_message); break; } ppm->phi_pivot = y[1]; if (ppm->primordial_verbose > 1) { printf(" (reached phi_pivot=%e)\n",ppm->phi_pivot); /** - --> In verbose mode, check that phi_pivot is correct. Done by restarting from phi_pivot and going again till the end of inflation. */ aH_pivot = dy[0]; a_pivot = y[0]; class_call(primordial_inflation_evolve_background(ppm, ppr, y, dy, _phi_, ppm->phi_end, _FALSE_, forward, proper), ppm->error_message, ppm->error_message); printf(" (from phi_pivot till the end, ln(aH_2/aH_1) = %e, ln(a_2/a_1) = %e)\n",log(dy[0]/aH_pivot),log(y[0]/a_pivot)); } } return _SUCCESS_; } /** * Routine returning derivative of system of background/perturbation * variables. Like other routines used by the generic integrator * (background_derivs, thermodynamics_derivs, perturb_derivs), this * routine has a generic list of arguments, and a slightly different * error management, with the error message returned directly in an * ErrMsg field. * * @param tau Input: time (not used explicitly inside the routine, but requested by the generic integrator) * @param y Input/output: running vector of background variables, already allocated and initialized * @param dy Input: running vector of background derivatives, already allocated * @param parameters_and_workspace Input: all necessary input variables apart from y * @param error_message Output: error message * @return the error status */ int primordial_inflation_derivs( double tau, double * y, double * dy, void * parameters_and_workspace, ErrorMsg error_message ) { struct primordial_inflation_parameters_and_workspace * ppipaw; struct primordial * ppm; ppipaw = parameters_and_workspace; ppm = ppipaw->ppm; // a2 ppipaw->a2=y[ppm->index_in_a]*y[ppm->index_in_a]; // BACKGROUND switch (ppm->primordial_spec_type) { case inflation_V: case inflation_V_end: class_call(primordial_inflation_potential(ppm, y[ppm->index_in_phi], &(ppipaw->V), &(ppipaw->dV), &(ppipaw->ddV)), ppm->error_message, ppm->error_message); switch (ppipaw->integrate) { case forward: switch (ppipaw->time) { case conformal: // a H = a'/a ppipaw->aH = sqrt((8*_PI_/3.)*(0.5*y[ppm->index_in_dphi]*y[ppm->index_in_dphi]+ppipaw->a2*ppipaw->V)); // 1: a dy[ppm->index_in_a]=y[ppm->index_in_a]*ppipaw->aH; // 2: phi dy[ppm->index_in_phi]=y[ppm->index_in_dphi]; // 3: dphi/dtau dy[ppm->index_in_dphi]=-2.*ppipaw->aH*y[ppm->index_in_dphi]-ppipaw->a2*ppipaw->dV; break; case proper: // a H = adot ppipaw->aH = y[ppm->index_in_a]*sqrt((8*_PI_/3.)*(0.5*y[ppm->index_in_dphi]*y[ppm->index_in_dphi]+ppipaw->V)); // 1: a dy[ppm->index_in_a]=ppipaw->aH; // 2: phi dy[ppm->index_in_phi]=y[ppm->index_in_dphi]; // 3: dphi/dt dy[ppm->index_in_dphi]=-3.*ppipaw->aH/y[ppm->index_in_a]*y[ppm->index_in_dphi]-ppipaw->dV; break; } // z''/z (assumes that conformal time is requested) ppipaw->zpp_over_z= 2*ppipaw->aH*ppipaw->aH - ppipaw->a2*ppipaw->ddV - 4.*_PI_*(7.*y[ppm->index_in_dphi]*y[ppm->index_in_dphi] +4.*y[ppm->index_in_dphi]/ppipaw->aH*ppipaw->a2*ppipaw->dV) +32.*_PI_*_PI_*pow(y[ppm->index_in_dphi],4)/pow(ppipaw->aH,2); // a''/a (assumes that conformal time is requested) ppipaw->app_over_a=2.*ppipaw->aH*ppipaw->aH - 4.*_PI_*y[ppm->index_in_dphi]*y[ppm->index_in_dphi]; break; // For backward integration of approximate slow-roll solution: // Neglect kinetic energy of the field phi'^2/(2a^2) w.r.t. potential energy V // Neglect phi'' w.r.t 2aHphi', reducing 2nd order Klein-Gordon to approximate 1st-order case backward: switch (ppipaw->time) { case conformal: // a H = a'/a ppipaw->aH = sqrt((8*_PI_/3.)*ppipaw->a2*ppipaw->V); // 1: a dy[ppm->index_in_a]=y[ppm->index_in_a]*ppipaw->aH; // 2: phi dy[ppm->index_in_phi]= -ppipaw->a2*ppipaw->dV/3./ppipaw->aH; break; case proper: // a H = da/dt ppipaw->aH = y[ppm->index_in_a]*sqrt((8*_PI_/3.)*ppipaw->V); // 1: a dy[ppm->index_in_a]=ppipaw->aH; // 2: phi dy[ppm->index_in_phi]= -ppipaw->dV/3./ppipaw->aH*y[ppm->index_in_a]; break; } break; } break; case inflation_H: class_call(primordial_inflation_hubble(ppm, y[ppm->index_in_phi], &(ppipaw->H), &(ppipaw->dH), &(ppipaw->ddH), &(ppipaw->dddH)), ppm->error_message, ppm->error_message); switch (ppipaw->time) { case conformal: // 1: a dy[ppm->index_in_a]=ppipaw->a2*ppipaw->H; // 2: phi dy[ppm->index_in_phi]=-1./4./_PI_*y[ppm->index_in_a]*ppipaw->dH; break; case proper: // 1: a dy[ppm->index_in_a]=y[ppm->index_in_a]*ppipaw->H; // 2: phi dy[ppm->index_in_phi]=-1./4./_PI_*ppipaw->dH; break; } // z''/z (assumes that conformal time is requested) ppipaw->zpp_over_z = 2. *ppipaw->a2*ppipaw->H*ppipaw->H -3./4./_PI_ *ppipaw->a2*ppipaw->H*ppipaw->ddH +1./16./_PI_/_PI_*ppipaw->a2*ppipaw->ddH*ppipaw->ddH +1./16./_PI_/_PI_*ppipaw->a2*ppipaw->dH*ppipaw->dddH -1./4./_PI_/_PI_ *ppipaw->a2*ppipaw->dH*ppipaw->dH*ppipaw->ddH/ppipaw->H +1./2./_PI_ *ppipaw->a2*ppipaw->dH*ppipaw->dH +1./8./_PI_/_PI_ *ppipaw->a2*ppipaw->dH*ppipaw->dH*ppipaw->dH*ppipaw->dH/ppipaw->H/ppipaw->H; // a''/a (assumes that conformal time is requested) ppipaw->app_over_a = 2.*ppipaw->a2*ppipaw->H*ppipaw->H -4.*_PI_*dy[ppm->index_in_phi]*dy[ppm->index_in_phi]; break; default: class_stop(ppm->error_message,"ppm->primordial_spec_type=%d different from possible relevant cases",ppm->primordial_spec_type); break; } if (ppipaw->N <= ppm->in_bg_size) // mind the <= instead of ==, necessary because for backward integration 1 equation is removed return _SUCCESS_; // PERTURBATIONS class_test(ppipaw->time == proper, ppm->error_message, "For inflaton perturbations, only conformal time is coded."); // SCALARS // 4: ksi_re dy[ppm->index_in_ksi_re]=y[ppm->index_in_dksi_re]; // 5: ksi_im dy[ppm->index_in_ksi_im]=y[ppm->index_in_dksi_im]; // 6: d ksi_re / dtau dy[ppm->index_in_dksi_re]=-(ppipaw->k*ppipaw->k-ppipaw->zpp_over_z)*y[ppm->index_in_ksi_re]; // 7: d ksi_im / dtau dy[ppm->index_in_dksi_im]=-(ppipaw->k*ppipaw->k-ppipaw->zpp_over_z)*y[ppm->index_in_ksi_im]; // TENSORS // 8: ah_re dy[ppm->index_in_ah_re]=y[ppm->index_in_dah_re]; // 9: ah_im dy[ppm->index_in_ah_im]=y[ppm->index_in_dah_im]; // 10: d ah_re / dtau dy[ppm->index_in_dah_re]=-(ppipaw->k*ppipaw->k-ppipaw->app_over_a)*y[ppm->index_in_ah_re]; // 11: d ah_im / dtau dy[ppm->index_in_dah_im]=-(ppipaw->k*ppipaw->k-ppipaw->app_over_a)*y[ppm->index_in_ah_im]; return _SUCCESS_; } /** * This routine reads the primordial spectrum from an external command, * and stores the tabulated values. * The sampling of the k's given by the external command is preserved. * * Author: Jesus Torrado (torradocacho@lorentz.leidenuniv.nl) * Date: 2013-12-20 * * @param ppt Input/output: pointer to perturbation structure * @param ppm Input/output: pointer to primordial structure * @return the error status */ int primordial_external_spectrum_init( struct perturbs * ppt, struct primordial * ppm ) { /** Summary: */ char arguments[_ARGUMENT_LENGTH_MAX_]; char line[_LINE_LENGTH_MAX_]; char command_with_arguments[2*_ARGUMENT_LENGTH_MAX_]; FILE *process; int n_data_guess, n_data = 0; double *k = NULL, *pks = NULL, *pkt = NULL, *tmp = NULL; double this_k, this_pks, this_pkt; int status; int index_k; /** - Initialization */ /* Prepare the data (with some initial size) */ n_data_guess = 100; k = (double *)malloc(n_data_guess*sizeof(double)); pks = (double *)malloc(n_data_guess*sizeof(double)); if (ppt->has_tensors == _TRUE_) pkt = (double *)malloc(n_data_guess*sizeof(double)); /* Prepare the command */ /* If the command is just a "cat", no arguments need to be passed */ if(strncmp("cat ", ppm->command, 4) == 0) { sprintf(arguments, " "); } /* otherwise pass the list of arguments */ else { sprintf(arguments, " %g %g %g %g %g %g %g %g %g %g", ppm->custom1, ppm->custom2, ppm->custom3, ppm->custom4, ppm->custom5, ppm->custom6, ppm->custom7, ppm->custom8, ppm->custom9, ppm->custom10); } /* write the actual command in a string */ sprintf(command_with_arguments, "%s %s", ppm->command, arguments); if (ppm->primordial_verbose > 0) printf(" -> running: %s\n",command_with_arguments); /** - Launch the command and retrieve the output */ /* Launch the process */ process = popen(command_with_arguments, "r"); class_test(process == NULL, ppm->error_message, "The program failed to set the environment for the external command. Maybe you ran out of memory."); /* Read output and store it */ while (fgets(line, sizeof(line)-1, process) != NULL) { if (ppt->has_tensors == _TRUE_) { sscanf(line, "%lf %lf %lf", &this_k, &this_pks, &this_pkt); } else { sscanf(line, "%lf %lf", &this_k, &this_pks); } /* Standard technique in C: if too many data, double the size of the vectors */ /* (it is faster and safer that reallocating every new line) */ if((n_data+1) > n_data_guess) { n_data_guess *= 2; tmp = (double *)realloc(k, n_data_guess*sizeof(double)); class_test(tmp == NULL, ppm->error_message, "Error allocating memory to read the external spectrum.\n"); k = tmp; tmp = (double *)realloc(pks, n_data_guess*sizeof(double)); class_test(tmp == NULL, ppm->error_message, "Error allocating memory to read the external spectrum.\n"); pks = tmp; if (ppt->has_tensors == _TRUE_) { tmp = (double *)realloc(pkt, n_data_guess*sizeof(double)); class_test(tmp == NULL, ppm->error_message, "Error allocating memory to read the external spectrum.\n"); pkt = tmp; }; }; /* Store */ k [n_data] = this_k; pks[n_data] = this_pks; if (ppt->has_tensors == _TRUE_) { pkt[n_data] = this_pkt; } n_data++; /* Check ascending order of the k's */ if(n_data>1) { class_test(k[n_data-1] <= k[n_data-2], ppm->error_message, "The k's are not strictly sorted in ascending order, " "as it is required for the calculation of the splines.\n"); } } /* Close the process */ status = pclose(process); class_test(status != 0., ppm->error_message, "The attempt to launch the external command was unsuccessful. " "Try doing it by hand to check for errors."); /* Test limits of the k's */ class_test(k[1] > ppt->k_min, ppm->error_message, "Your table for the primordial spectrum does not have " "at least 2 points before the minimum value of k: %e . " "The splines interpolation would not be safe.",ppt->k_min); class_test(k[n_data-2] < ppt->k_max, ppm->error_message, "Your table for the primordial spectrum does not have " "at least 2 points after the maximum value of k: %e . " "The splines interpolation would not be safe.",ppt->k_max); /** - Store the read results into CLASS structures */ ppm->lnk_size = n_data; /** - Make room */ class_realloc(ppm->lnk, ppm->lnk, ppm->lnk_size*sizeof(double), ppm->error_message); class_realloc(ppm->lnpk[ppt->index_md_scalars], ppm->lnpk[ppt->index_md_scalars], ppm->lnk_size*sizeof(double), ppm->error_message); class_realloc(ppm->ddlnpk[ppt->index_md_scalars], ppm->ddlnpk[ppt->index_md_scalars], ppm->lnk_size*sizeof(double), ppm->error_message); if (ppt->has_tensors == _TRUE_) { class_realloc(ppm->lnpk[ppt->index_md_tensors], ppm->lnpk[ppt->index_md_tensors], ppm->lnk_size*sizeof(double), ppm->error_message); class_realloc(ppm->ddlnpk[ppt->index_md_tensors], ppm->ddlnpk[ppt->index_md_tensors], ppm->lnk_size*sizeof(double), ppm->error_message); }; /** - Store values */ for (index_k=0; index_k<ppm->lnk_size; index_k++) { ppm->lnk[index_k] = log(k[index_k]); ppm->lnpk[ppt->index_md_scalars][index_k] = log(pks[index_k]); if (ppt->has_tensors == _TRUE_) ppm->lnpk[ppt->index_md_tensors][index_k] = log(pkt[index_k]); /* DEBUG (with tensors) fprintf(stderr,"Storing[%d(+1) of %d]: \n k = %g == %g\n pks = %g == %g\n pkt = %g == %g\n", index_k, n_data, ppm->lnk[index_k], log(k[index_k]), ppm->lnpk[ppt->index_md_scalars][index_k], log(pks[index_k]), ppm->lnpk[ppt->index_md_tensors][index_k], log(pkt[index_k])); */ }; /** - Release the memory used locally */ free(k); free(pks); if (ppt->has_tensors == _TRUE_) free(pkt); /** - Tell CLASS that there are scalar (and tensor) modes */ ppm->is_non_zero[ppt->index_md_scalars][ppt->index_ic_ad] = _TRUE_; if (ppt->has_tensors == _TRUE_) ppm->is_non_zero[ppt->index_md_tensors][ppt->index_ic_ten] = _TRUE_; return _SUCCESS_; } int primordial_output_titles(struct perturbs * ppt, struct primordial * ppm, char titles[_MAXTITLESTRINGLENGTH_] ){ class_store_columntitle(titles,"k [1/Mpc]",_TRUE_); class_store_columntitle(titles,"P_scalar(k)",_TRUE_); class_store_columntitle(titles,"P_tensor(k)",ppt->has_tensors); return _SUCCESS_; } int primordial_output_data(struct perturbs * ppt, struct primordial * ppm, int number_of_titles, double *data){ int index_k, storeidx; double *dataptr; for (index_k=0; index_k<ppm->lnk_size; index_k++) { dataptr = data + index_k*number_of_titles; storeidx = 0; class_store_double(dataptr, exp(ppm->lnk[index_k]), _TRUE_,storeidx); class_store_double(dataptr, exp(ppm->lnpk[ppt->index_md_scalars][index_k]), _TRUE_,storeidx); class_store_double(dataptr, exp(ppm->lnpk[ppt->index_md_tensors][index_k]), ppt->has_tensors,storeidx); } return _SUCCESS_; }
matrixmultiply-ompacc.c
/* Naive matrix-matrix multiplication(mmm) By C. Liao */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif #define N 1024 #define M 1024 #define K 1024 #define REAL float int i,j,k; REAL a[N][M],b[M][K],c[N][K], c2[N][K]; int init(); int mmm(); int mmm2(); int verify(); int main(void) { init(); mmm(); mmm2(); return verify(); } int init() { for (i=0;i<N;i++) for(j=0;j<M;j++) a[i][j]=3.0*i*j/N/M; for (i=0;i<M;i++) for(j=0;j<K;j++) b[i][j]=5.0*j*i/N/M; for (i=0;i<N;i++) for(j=0;j<K;j++) { c[i][j]=0.0; c2[i][j]=0.0; } return 0; } /* TODO: try different i,j,k orders a b e f a*e+ b*g , a*f+ b*h c d x g h = c*e+ d*g, c*f+ d*h */ int mmm() { #pragma omp target map(inout:c[0:N][0:M]), map(in:a[0:N][0:M],b[0:M][0:K]) #pragma omp parallel for private(i,j,k) for (i = 0; i < N; i++) for (j = 0; j < M; j++) for (k = 0; k < K; k++) c[i][j]= c[i][j]+a[i][k]*b[k][j]; return 0; } int mmm2() { for (i = 0; i < N; i++) for (j = 0; j < M; j++) for (k = 0; k < K; k++) c2[i][j]= c2[i][j]+a[i][k]*b[k][j]; return 0; } int verify() { REAL sum=0.0, sum2=0.0; for (i=0;i<N;i++) for(j=0;j<K;j++) { sum+=c[i][j]; sum2+=c2[i][j]; } printf("sum of c[i][j] is %f\n",sum); printf("sum of c2[i][j] is %f\n",sum2); return 0; }
pvector.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef PVECTOR_H_ #define PVECTOR_H_ #include <algorithm> /* GAP Benchmark Suite Class: pvector Author: Scott Beamer Vector class with ability to not initialize or do initialize in parallel - std::vector (when resizing) will always initialize, and does it serially - When pvector is resized, new elements are uninitialized - Resizing is not thread-safe */ template <typename T_> class pvector { public: typedef T_* iterator; pvector() : start_(nullptr), end_size_(nullptr), end_capacity_(nullptr) {} explicit pvector(size_t num_elements) { start_ = new T_[num_elements]; end_size_ = start_ + num_elements; end_capacity_ = end_size_; } pvector(size_t num_elements, T_ init_val) : pvector(num_elements) { fill(init_val); } pvector(iterator copy_begin, iterator copy_end) : pvector(copy_end - copy_begin) { #pragma omp parallel for for (size_t i=0; i < capacity(); i++) start_[i] = copy_begin[i]; } // don't want this to be copied, too much data to move pvector(const pvector &other) = delete; // prefer move because too much data to copy pvector(pvector &&other) : start_(other.start_), end_size_(other.end_size_), end_capacity_(other.end_capacity_) { other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; } // want move assignment pvector& operator= (pvector &&other) { if (this != &other) { ReleaseResources(); start_ = other.start_; end_size_ = other.end_size_; end_capacity_ = other.end_capacity_; other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; } return *this; } void ReleaseResources(){ if (start_ != nullptr) { delete[] start_; } } ~pvector() { ReleaseResources(); } // not thread-safe void reserve(size_t num_elements) { if (num_elements > capacity()) { T_ *new_range = new T_[num_elements]; #pragma omp parallel for for (size_t i=0; i < size(); i++) new_range[i] = start_[i]; end_size_ = new_range + size(); delete[] start_; start_ = new_range; end_capacity_ = start_ + num_elements; } } // prevents internal storage from being freed when this pvector is desctructed // - used by Builder to reuse an EdgeList's space for in-place graph building void leak() { start_ = nullptr; } bool empty() { return end_size_ == start_; } void clear() { end_size_ = start_; } void resize(size_t num_elements) { reserve(num_elements); end_size_ = start_ + num_elements; } T_& operator[](size_t n) { return start_[n]; } const T_& operator[](size_t n) const { return start_[n]; } void push_back(T_ val) { if (size() == capacity()) { size_t new_size = capacity() == 0 ? 1 : capacity() * growth_factor; reserve(new_size); } *end_size_ = val; end_size_++; } void fill(T_ init_val) { #pragma omp parallel for for (T_* ptr=start_; ptr < end_size_; ptr++) *ptr = init_val; } size_t capacity() const { return end_capacity_ - start_; } size_t size() const { return end_size_ - start_; } iterator begin() const { return start_; } iterator end() const { return end_size_; } T_* data() const { return start_; } void swap(pvector &other) { std::swap(start_, other.start_); std::swap(end_size_, other.end_size_); std::swap(end_capacity_, other.end_capacity_); } private: T_* start_; T_* end_size_; T_* end_capacity_; static const size_t growth_factor = 2; }; #endif // PVECTOR_H_
constitute.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO N N SSSSS TTTTT IIIII TTTTT U U TTTTT EEEEE % % C O O NN N SS T I T U U T E % % C O O N N N ESSS T I T U U T EEE % % C O O N NN SS T I T U U T E % % CCCC OOO N N SSSSS T IIIII T UUU T EEEEE % % % % % % MagickCore Methods to Consitute an Image % % % % Software Design % % Cristy % % October 1998 % % % % % % 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/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/client.h" #include "MagickCore/coder-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/constitute-private.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/identify.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.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/policy.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/timer.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n s t i t u t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConstituteImage() returns an image from the pixel data you supply. % The pixel data must be in scanline order top-to-bottom. The data can be % char, short int, int, float, or double. Float and double require the % pixels to be normalized [0..1], otherwise [0..QuantumRange]. For example, to % create a 640x480 image from unsigned red-green-blue character data, use: % % image = ConstituteImage(640,480,"RGB",CharPixel,pixels,&exception); % % The format of the ConstituteImage method is: % % Image *ConstituteImage(const size_t columns,const size_t rows, % const char *map,const StorageType storage,const void *pixels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o columns: width in pixels of the image. % % o rows: height in pixels of the image. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, % Y = yellow, M = magenta, K = black, I = intensity (for grayscale), % P = pad. % % o storage: Define the data type of the pixels. Float and double types are % expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose % from these types: CharPixel, DoublePixel, FloatPixel, IntegerPixel, % LongPixel, QuantumPixel, or ShortPixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConstituteImage(const size_t columns,const size_t rows, const char *map,const StorageType storage,const void *pixels, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t i; size_t length; /* Allocate image structure. */ assert(map != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",map); assert(pixels != (void *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage((ImageInfo *) NULL,exception); if (image == (Image *) NULL) return((Image *) NULL); switch (storage) { case CharPixel: image->depth=8*sizeof(unsigned char); break; case DoublePixel: image->depth=8*sizeof(double); break; case FloatPixel: image->depth=8*sizeof(float); break; case LongPixel: image->depth=8*sizeof(unsigned long); break; case LongLongPixel: image->depth=8*sizeof(MagickSizeType); break; case ShortPixel: image->depth=8*sizeof(unsigned short); break; default: break; } length=strlen(map); for (i=0; i < (ssize_t) length; i++) { switch (map[i]) { case 'a': case 'A': case 'O': case 'o': { image->alpha_trait=BlendPixelTrait; break; } case 'C': case 'c': case 'm': case 'M': case 'Y': case 'y': case 'K': case 'k': { image->colorspace=CMYKColorspace; break; } case 'I': case 'i': { image->colorspace=GRAYColorspace; break; } default: { if (length == 1) image->colorspace=GRAYColorspace; break; } } } status=SetImageExtent(image,columns,rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ImportImagePixels(image,0,0,columns,rows,map,storage,pixels,exception); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i n g I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PingImage() returns all the properties of an image or image sequence % except for the pixels. It is much faster and consumes far less memory % than ReadImage(). On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the PingImage method is: % % Image *PingImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Ping the image defined by the file or filename members of % this structure. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static size_t PingStream(const Image *magick_unused(image), const void *magick_unused(pixels),const size_t columns) { magick_unreferenced(image); magick_unreferenced(pixels); return(columns); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport Image *PingImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; ImageInfo *ping_info; assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); ping_info=CloneImageInfo(image_info); ping_info->ping=MagickTrue; image=ReadStream(ping_info,&PingStream,exception); if (image != (Image *) NULL) { ResetTimer(&image->timer); if (ping_info->verbose != MagickFalse) (void) IdentifyImage(image,stdout,MagickFalse,exception); } ping_info=DestroyImageInfo(ping_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i n g I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PingImages() pings one or more images and returns them as an image list. % % The format of the PingImage method is: % % Image *PingImages(ImageInfo *image_info,const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PingImages(ImageInfo *image_info,const char *filename, ExceptionInfo *exception) { char ping_filename[MagickPathExtent]; Image *image, *images; ImageInfo *read_info; /* Ping image list from a file. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); (void) SetImageOption(image_info,"filename",filename); (void) CopyMagickString(image_info->filename,filename,MagickPathExtent); (void) InterpretImageFilename(image_info,(Image *) NULL,image_info->filename, (int) image_info->scene,ping_filename,exception); if (LocaleCompare(ping_filename,image_info->filename) != 0) { ExceptionInfo *sans; ssize_t extent, scene; /* Images of the form image-%d.png[1-5]. */ read_info=CloneImageInfo(image_info); sans=AcquireExceptionInfo(); (void) SetImageInfo(read_info,0,sans); sans=DestroyExceptionInfo(sans); if (read_info->number_scenes == 0) { read_info=DestroyImageInfo(read_info); return(PingImage(image_info,exception)); } (void) CopyMagickString(ping_filename,read_info->filename, MagickPathExtent); images=NewImageList(); extent=(ssize_t) (read_info->scene+read_info->number_scenes); for (scene=(ssize_t) read_info->scene; scene < (ssize_t) extent; scene++) { (void) InterpretImageFilename(image_info,(Image *) NULL,ping_filename, (int) scene,read_info->filename,exception); image=PingImage(read_info,exception); if (image == (Image *) NULL) continue; AppendImageToList(&images,image); } read_info=DestroyImageInfo(read_info); return(images); } return(PingImage(image_info,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadImage() reads an image or image sequence from a file or file handle. % The method returns a NULL if there is a memory shortage or if the image % cannot be read. On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the ReadImage method is: % % Image *ReadImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Read the image defined by the file or filename members of % this structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsCoderAuthorized(const char *coder, const PolicyRights rights,ExceptionInfo *exception) { if (IsRightsAuthorized(CoderPolicyDomain,rights,coder) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",coder); return(MagickFalse); } return(MagickTrue); } MagickExport Image *ReadImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], magick[MagickPathExtent], magick_filename[MagickPathExtent]; const char *value; const DelegateInfo *delegate_info; const MagickInfo *magick_info; DecodeImageHandler *decoder; ExceptionInfo *sans_exception; GeometryInfo geometry_info; Image *image, *next; ImageInfo *read_info; MagickBooleanType status; MagickStatusType flags; /* Determine image type from filename prefix or suffix (e.g. image.jpg). */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image_info->filename != (char *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); read_info=CloneImageInfo(image_info); (void) CopyMagickString(magick_filename,read_info->filename,MagickPathExtent); (void) SetImageInfo(read_info,0,exception); (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) CopyMagickString(magick,read_info->magick,MagickPathExtent); /* Call appropriate image reader based on image type. */ sans_exception=AcquireExceptionInfo(); magick_info=GetMagickInfo(read_info->magick,sans_exception); if (sans_exception->severity == PolicyError) magick_info=GetMagickInfo(read_info->magick,exception); sans_exception=DestroyExceptionInfo(sans_exception); if (magick_info != (const MagickInfo *) NULL) { if (GetMagickEndianSupport(magick_info) == MagickFalse) read_info->endian=UndefinedEndian; else if ((image_info->endian == UndefinedEndian) && (GetMagickRawSupport(magick_info) != MagickFalse)) { unsigned long lsb_first; lsb_first=1; read_info->endian=(*(char *) &lsb_first) == 1 ? LSBEndian : MSBEndian; } } if ((magick_info != (const MagickInfo *) NULL) && (GetMagickDecoderSeekableStream(magick_info) != MagickFalse)) { image=AcquireImage(read_info,exception); (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } if (IsBlobSeekable(image) == MagickFalse) { /* Coder requires a seekable stream. */ *read_info->filename='\0'; status=ImageToFile(image,read_info->filename,exception); if (status == MagickFalse) { (void) CloseBlob(image); read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } read_info->temporary=MagickTrue; } (void) CloseBlob(image); image=DestroyImage(image); } image=NewImageList(); decoder=GetImageDecoder(magick_info); if (decoder == (DecodeImageHandler *) NULL) { delegate_info=GetDelegateInfo(read_info->magick,(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) SetImageInfo(read_info,0,exception); (void) CopyMagickString(read_info->filename,filename, MagickPathExtent); magick_info=GetMagickInfo(read_info->magick,exception); decoder=GetImageDecoder(magick_info); } } if (decoder != (DecodeImageHandler *) NULL) { /* Call appropriate image reader based on image type. */ if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=IsCoderAuthorized(read_info->magick,ReadPolicyRights,exception); image=(Image *) NULL; if (status != MagickFalse) image=decoder(read_info,exception); if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } else { delegate_info=GetDelegateInfo(read_info->magick,(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->magick); if (read_info->temporary != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } /* Let our decoding delegate process the image. */ image=AcquireImage(read_info,exception); if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return((Image *) NULL); } (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); *read_info->filename='\0'; if (GetDelegateThreadSupport(delegate_info) == MagickFalse) LockSemaphoreInfo(delegate_info->semaphore); status=InvokeDelegate(read_info,image,read_info->magick,(char *) NULL, exception); if (GetDelegateThreadSupport(delegate_info) == MagickFalse) UnlockSemaphoreInfo(delegate_info->semaphore); image=DestroyImageList(image); read_info->temporary=MagickTrue; if (status != MagickFalse) (void) SetImageInfo(read_info,0,exception); magick_info=GetMagickInfo(read_info->magick,exception); decoder=GetImageDecoder(magick_info); if (decoder == (DecodeImageHandler *) NULL) { if (IsPathAccessible(read_info->filename) != MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->magick); else ThrowFileException(exception,FileOpenError,"UnableToOpenFile", read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } /* Call appropriate image reader based on image type. */ if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=IsCoderAuthorized(read_info->magick,ReadPolicyRights,exception); image=(Image *) NULL; if (status != MagickFalse) image=(decoder)(read_info,exception); if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } if (read_info->temporary != MagickFalse) { (void) RelinquishUniqueFileResource(read_info->filename); read_info->temporary=MagickFalse; if (image != (Image *) NULL) (void) CopyMagickString(image->filename,filename,MagickPathExtent); } if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return(image); } if (exception->severity >= ErrorException) (void) LogMagickEvent(ExceptionEvent,GetMagickModule(), "Coder (%s) generated an image despite an error (%d), " "notify the developers",image->magick,exception->severity); if (IsBlobTemporary(image) != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); if ((IsSceneGeometry(read_info->scenes,MagickFalse) != MagickFalse) && (GetImageListLength(image) != 1)) { Image *clones; clones=CloneImages(image,read_info->scenes,exception); if (clones != (Image *) NULL) { image=DestroyImageList(image); image=GetFirstImageInList(clones); } } for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { char magick_path[MagickPathExtent], *property, timestamp[MagickPathExtent]; const char *option; const StringInfo *profile; ssize_t option_type; static const char *source_date_epoch = (const char *) NULL; static MagickBooleanType epoch_initalized = MagickFalse; next->taint=MagickFalse; GetPathComponent(magick_filename,MagickPath,magick_path); if (*magick_path == '\0' && *next->magick == '\0') (void) CopyMagickString(next->magick,magick,MagickPathExtent); (void) CopyMagickString(next->magick_filename,magick_filename, MagickPathExtent); if (IsBlobTemporary(image) != MagickFalse) (void) CopyMagickString(next->filename,filename,MagickPathExtent); if (next->magick_columns == 0) next->magick_columns=next->columns; if (next->magick_rows == 0) next->magick_rows=next->rows; (void) GetImageProperty(next,"exif:*",exception); (void) GetImageProperty(next,"icc:*",exception); (void) GetImageProperty(next,"iptc:*",exception); (void) GetImageProperty(next,"xmp:*",exception); value=GetImageProperty(next,"exif:Orientation",exception); if (value == (char *) NULL) value=GetImageProperty(next,"tiff:Orientation",exception); if (value != (char *) NULL) { next->orientation=(OrientationType) StringToLong(value); (void) DeleteImageProperty(next,"tiff:Orientation"); (void) DeleteImageProperty(next,"exif:Orientation"); } value=GetImageProperty(next,"exif:XResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.x; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.x=geometry_info.rho/geometry_info.sigma; if (strchr(value,',') != (char *) NULL) next->resolution.x=geometry_info.rho+geometry_info.sigma/1000.0; (void) DeleteImageProperty(next,"exif:XResolution"); } value=GetImageProperty(next,"exif:YResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.y; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.y=geometry_info.rho/geometry_info.sigma; if (strchr(value,',') != (char *) NULL) next->resolution.y=geometry_info.rho+geometry_info.sigma/1000.0; (void) DeleteImageProperty(next,"exif:YResolution"); } value=GetImageProperty(next,"exif:ResolutionUnit",exception); if (value == (char *) NULL) value=GetImageProperty(next,"tiff:ResolutionUnit",exception); if (value != (char *) NULL) { option_type=ParseCommandOption(MagickResolutionOptions,MagickFalse, value); if (option_type >= 0) next->units=(ResolutionType) option_type; (void) DeleteImageProperty(next,"exif:ResolutionUnit"); (void) DeleteImageProperty(next,"tiff:ResolutionUnit"); } if (next->page.width == 0) next->page.width=next->columns; if (next->page.height == 0) next->page.height=next->rows; option=GetImageOption(read_info,"caption"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"caption",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"comment"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"comment",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"label"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"label",property,exception); property=DestroyString(property); } if (LocaleCompare(next->magick,"TEXT") == 0) (void) ParseAbsoluteGeometry("0x0+0+0",&next->page); if ((read_info->extract != (char *) NULL) && (read_info->stream == (StreamHandler) NULL)) { RectangleInfo geometry; SetGeometry(next,&geometry); flags=ParseAbsoluteGeometry(read_info->extract,&geometry); if ((next->columns != geometry.width) || (next->rows != geometry.height)) { if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { Image *crop_image; crop_image=CropImage(next,&geometry,exception); if (crop_image != (Image *) NULL) ReplaceImageInList(&next,crop_image); } else if (((flags & WidthValue) != 0) || ((flags & HeightValue) != 0)) { Image *size_image; flags=ParseRegionGeometry(next,read_info->extract,&geometry, exception); size_image=ResizeImage(next,geometry.width,geometry.height, next->filter,exception); if (size_image != (Image *) NULL) ReplaceImageInList(&next,size_image); } } } profile=GetImageProfile(next,"icc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"icm"); profile=GetImageProfile(next,"iptc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"8bim"); if (epoch_initalized == MagickFalse) { source_date_epoch=getenv("SOURCE_DATE_EPOCH"); epoch_initalized=MagickTrue; } if (source_date_epoch == (const char *) NULL) { (void) FormatMagickTime((time_t) GetBlobProperties(next)->st_mtime, MagickPathExtent,timestamp); (void) SetImageProperty(next,"date:modify",timestamp,exception); (void) FormatMagickTime((time_t) GetBlobProperties(next)->st_ctime, MagickPathExtent,timestamp); (void) SetImageProperty(next,"date:create",timestamp,exception); } option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (next->delay > (size_t) floor(geometry_info.rho+0.5)) next->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (next->delay < (size_t) floor(geometry_info.rho+0.5)) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else next->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) { option_type=ParseCommandOption(MagickDisposeOptions,MagickFalse, option); if (option_type >= 0) next->dispose=(DisposeType) option_type; } if (read_info->verbose != MagickFalse) (void) IdentifyImage(next,stderr,MagickFalse,exception); image=next; } read_info=DestroyImageInfo(read_info); if (GetBlobError(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadImages() reads one or more images and returns them as an image list. % % The format of the ReadImage method is: % % Image *ReadImages(ImageInfo *image_info,const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadImages(ImageInfo *image_info,const char *filename, ExceptionInfo *exception) { char read_filename[MagickPathExtent]; Image *image, *images; ImageInfo *read_info; /* Read image list from a file. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; (void) SetImageOption(read_info,"filename",filename); (void) CopyMagickString(read_info->filename,filename,MagickPathExtent); (void) InterpretImageFilename(read_info,(Image *) NULL,filename, (int) read_info->scene,read_filename,exception); if (LocaleCompare(read_filename,read_info->filename) != 0) { ExceptionInfo *sans; ssize_t extent, scene; /* Images of the form image-%d.png[1-5]. */ sans=AcquireExceptionInfo(); (void) SetImageInfo(read_info,0,sans); sans=DestroyExceptionInfo(sans); if (read_info->number_scenes != 0) { (void) CopyMagickString(read_filename,read_info->filename, MagickPathExtent); images=NewImageList(); extent=(ssize_t) (read_info->scene+read_info->number_scenes); scene=(ssize_t) read_info->scene; for ( ; scene < (ssize_t) extent; scene++) { (void) InterpretImageFilename(image_info,(Image *) NULL, read_filename,(int) scene,read_info->filename,exception); image=ReadImage(read_info,exception); if (image == (Image *) NULL) continue; AppendImageToList(&images,image); } read_info=DestroyImageInfo(read_info); return(images); } } (void) CopyMagickString(read_info->filename,filename,MagickPathExtent); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d I n l i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadInlineImage() reads a Base64-encoded inline image or image sequence. % The method returns a NULL if there is a memory shortage or if the image % cannot be read. On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the ReadInlineImage method is: % % Image *ReadInlineImage(const ImageInfo *image_info,const char *content, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o content: the image encoded in Base64. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadInlineImage(const ImageInfo *image_info, const char *content,ExceptionInfo *exception) { Image *image; ImageInfo *read_info; unsigned char *blob; size_t length; register const char *p; /* Skip over header (e.g. data:image/gif;base64,). */ image=NewImageList(); for (p=content; (*p != ',') && (*p != '\0'); p++) ; if (*p == '\0') ThrowReaderException(CorruptImageError,"CorruptImage"); p++; length=0; blob=Base64Decode(p,&length); if (length == 0) { blob=(unsigned char *) RelinquishMagickMemory(blob); ThrowReaderException(CorruptImageError,"CorruptImage"); } read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); *read_info->filename='\0'; *read_info->magick='\0'; image=BlobToImage(read_info,blob,length,exception); blob=(unsigned char *) RelinquishMagickMemory(blob); read_info=DestroyImageInfo(read_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteImage() writes an image or an image sequence to a file or file handle. % If writing to a file is on disk, the name is defined by the filename member % of the image structure. WriteImage() returns MagickFalse is there is a % memory shortage or if the image cannot be written. Check the exception % member of image to determine the cause for any failure. % % The format of the WriteImage method is: % % MagickBooleanType WriteImage(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. % */ MagickExport MagickBooleanType WriteImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; const MagickInfo *magick_info; EncodeImageHandler *encoder; ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType status, temporary; /* Determine image type from filename prefix or suffix (e.g. image.jpg). */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); sans_exception=AcquireExceptionInfo(); write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,image->filename, MagickPathExtent); (void) SetImageInfo(write_info,1,sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); (void) CopyMagickString(image->filename,write_info->filename, MagickPathExtent); /* Call appropriate image writer based on image type. */ magick_info=GetMagickInfo(write_info->magick,sans_exception); if (sans_exception->severity == PolicyError) magick_info=GetMagickInfo(write_info->magick,exception); sans_exception=DestroyExceptionInfo(sans_exception); if (magick_info != (const MagickInfo *) NULL) { if (GetMagickEndianSupport(magick_info) == MagickFalse) image->endian=UndefinedEndian; else if ((image_info->endian == UndefinedEndian) && (GetMagickRawSupport(magick_info) != MagickFalse)) { unsigned long lsb_first; lsb_first=1; image->endian=(*(char *) &lsb_first) == 1 ? LSBEndian : MSBEndian; } } (void) SyncImageProfiles(image); DisassociateImageStream(image); option=GetImageOption(image_info,"delegate:bimodal"); if ((IsStringTrue(option) != MagickFalse) && (write_info->page == (char *) NULL) && (GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) == (Image *) NULL) && (IsTaintImage(image) == MagickFalse) ) { delegate_info=GetDelegateInfo(image->magick,write_info->magick,exception); if ((delegate_info != (const DelegateInfo *) NULL) && (GetDelegateMode(delegate_info) == 0) && (IsPathAccessible(image->magick_filename) != MagickFalse)) { /* Process image with bi-modal delegate. */ (void) CopyMagickString(image->filename,image->magick_filename, MagickPathExtent); status=InvokeDelegate(write_info,image,image->magick, write_info->magick,exception); write_info=DestroyImageInfo(write_info); (void) CopyMagickString(image->filename,filename,MagickPathExtent); return(status); } } status=MagickFalse; temporary=MagickFalse; if ((magick_info != (const MagickInfo *) NULL) && (GetMagickEncoderSeekableStream(magick_info) != MagickFalse)) { char image_filename[MagickPathExtent]; (void) CopyMagickString(image_filename,image->filename,MagickPathExtent); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); (void) CopyMagickString(image->filename, image_filename,MagickPathExtent); if (status != MagickFalse) { if (IsBlobSeekable(image) == MagickFalse) { /* A seekable stream is required by the encoder. */ write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->filename,image->filename, MagickPathExtent); (void) AcquireUniqueFilename(image->filename); temporary=MagickTrue; } (void) CloseBlob(image); } } encoder=GetImageEncoder(magick_info); if (encoder != (EncodeImageHandler *) NULL) { /* Call appropriate image writer based on image type. */ if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=IsCoderAuthorized(write_info->magick,WritePolicyRights,exception); if (status != MagickFalse) status=encoder(write_info,image,exception); if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } else { delegate_info=GetDelegateInfo((char *) NULL,write_info->magick,exception); if (delegate_info != (DelegateInfo *) NULL) { /* Process the image with delegate. */ *write_info->filename='\0'; if (GetDelegateThreadSupport(delegate_info) == MagickFalse) LockSemaphoreInfo(delegate_info->semaphore); status=InvokeDelegate(write_info,image,(char *) NULL, write_info->magick,exception); if (GetDelegateThreadSupport(delegate_info) == MagickFalse) UnlockSemaphoreInfo(delegate_info->semaphore); (void) CopyMagickString(image->filename,filename,MagickPathExtent); } else { sans_exception=AcquireExceptionInfo(); magick_info=GetMagickInfo(write_info->magick,sans_exception); if (sans_exception->severity == PolicyError) magick_info=GetMagickInfo(write_info->magick,exception); sans_exception=DestroyExceptionInfo(sans_exception); if ((write_info->affirm == MagickFalse) && (magick_info == (const MagickInfo *) NULL)) { (void) CopyMagickString(write_info->magick,image->magick, MagickPathExtent); magick_info=GetMagickInfo(write_info->magick,exception); } encoder=GetImageEncoder(magick_info); if (encoder == (EncodeImageHandler *) NULL) { char extension[MagickPathExtent]; GetPathComponent(image->filename,ExtensionPath,extension); if (*extension != '\0') magick_info=GetMagickInfo(extension,exception); else magick_info=GetMagickInfo(image->magick,exception); (void) CopyMagickString(image->filename,filename, MagickPathExtent); encoder=GetImageEncoder(magick_info); } if (encoder == (EncodeImageHandler *) NULL) { magick_info=GetMagickInfo(image->magick,exception); encoder=GetImageEncoder(magick_info); if (encoder == (EncodeImageHandler *) NULL) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoEncodeDelegateForThisImageFormat", "`%s'",write_info->magick); } if (encoder != (EncodeImageHandler *) NULL) { /* Call appropriate image writer based on image type. */ if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=IsCoderAuthorized(write_info->magick,WritePolicyRights, exception); if (status != MagickFalse) status=encoder(write_info,image,exception); if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } } } if (temporary != MagickFalse) { /* Copy temporary image file to permanent. */ status=OpenBlob(write_info,image,ReadBinaryBlobMode,exception); if (status != MagickFalse) { (void) RelinquishUniqueFileResource(write_info->filename); status=ImageToFile(image,write_info->filename,exception); } (void) CloseBlob(image); (void) RelinquishUniqueFileResource(image->filename); (void) CopyMagickString(image->filename,write_info->filename, MagickPathExtent); } if ((LocaleCompare(write_info->magick,"info") != 0) && (write_info->verbose != MagickFalse)) (void) IdentifyImage(image,stdout,MagickFalse,exception); write_info=DestroyImageInfo(write_info); if (GetBlobError(image) != MagickFalse) ThrowWriterException(FileOpenError,"UnableToWriteFile"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteImages() writes an image sequence into one or more files. While % WriteImage() can write an image sequence, it is limited to writing % the sequence into a single file using a format which supports multiple % frames. WriteImages(), however, does not have this limitation, instead it % generates multiple output files if necessary (or when requested). When % ImageInfo's adjoin flag is set to MagickFalse, the file name is expected % to include a printf-style formatting string for the frame number (e.g. % "image%02d.png"). % % The format of the WriteImages method is: % % MagickBooleanType WriteImages(const ImageInfo *image_info,Image *images, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o images: the image list. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename, MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) { register Image *next; next=GetNextImageInList(p); if (next == (Image *) NULL) break; if (p->scene >= next->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(p,WriteImageTag,progress,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); }
MatrixProductOpenMP.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <omp.h> #include <time.h> const int MAX = 10; void run(int m, int size, char *name) { // Define my value int B[m][m], C[m * m]; int **A = (int**) malloc(sizeof(int*) * m); int *A_data = (int*) malloc(sizeof(int) * m * m); // Ensure matrix is contiguous memset(A_data, 0, m * m * sizeof(*A_data)); for (int i = 0; i < m; i++) { A[i] = &(A_data[m * i]); } srand((unsigned int)time(NULL)); // Generate A and B for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { A[i][j] = rand() % MAX + 1; B[i][j] = rand() % MAX + 1; } } /* printf("A = \n"); for(int i = 0; i<m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", B[i][j]); } printf("\n"); } printf("B = \n"); for(int i = 0; i<m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", B[i][j]); } printf("\n"); } */ // Zero out C for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { C[i * m + j] = 0; } } #pragma omp barrier double start = omp_get_wtime(); #pragma omp parallel num_threads(size) shared(A, B, C, m) #pragma omp for schedule(static) for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < m; k++) { C[i * m + j] = C[i * m + j] + (A[i][k] * B[k][j]); } } } #pragma omp barrier double end = omp_get_wtime(); printf("%s, %d, %d, %lf\n", name, size, m, end - start); /* printf("C = AB\n"); for(int i = 0; i< m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", C[i * m + j]); } printf("\n"); } */ } int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: %s MATRIX_SIZE NUM_PROCESSES NAME\n", argv[0]); exit(1); } int m = atoi(argv[1]); int size = atoi(argv[2]); char* name = argv[3]; int rank; if (size > m) { printf("No. of processes %d is greater than matrix size %d.\n",size, m); } else if (m % size) { printf("Matrix size %d is not a multiple of process count %d.\n", m, size); } else { run(m, size, name); } return 0; }
round_ref.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: qtang@openailab.com */ #include "sys_port.h" #include "module.h" #include "tengine_errno.h" #include "tengine_log.h" #include "tengine_ir.h" #include "../../cpu_node_ops.h" #include "tengine_op.h" #include <math.h> int ref_round_fp32(struct ir_tensor* input_tensor, struct ir_tensor* output_tensor, int num_thread) { // dims size = 2 or 3 if (input_tensor->dim_num < 4) { float* input_data = input_tensor->data; float* out_data = output_tensor->data; int total_size = input_tensor->elem_num; for (int i = 0; i < total_size; i++) { input_data[i] = round(out_data[i]); } return 0; } // dims size 3 else if (input_tensor->dim_num == 4) { int w = input_tensor->dims[3]; int h = output_tensor->dims[2]; int channels = input_tensor->dims[1]; int size = h * w; int c_step = h * w; float* input_data = input_tensor->data; float* out_data = output_tensor->data; #pragma omp parallel for num_threads(num_thread) for (int q = 0; q < channels; q++) { float* src = input_data + c_step * q; float* dst = out_data + c_step * q; for (int i = 0; i < size; i++) { dst[i] = round(src[i]); } } return 0; } return -1; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { // exec_node->inplace_map[0] = 0; // exec_node->inplace_map[1] = 0; // exec_node->inplace_map_num = 1; return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { // exec_node->inplace_map_num = 0; return 0; } static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor; struct ir_tensor* output_tensor; int layout = ir_graph->graph_layout; input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); // inplace inference // if(input_tensor->data != output_tensor->data) // { // TLOG_ERR("input and output are not the same mem\n"); // set_tengine_errno(EFAULT); // return -1; // } int ret = ref_round_fp32(input_tensor, output_tensor, exec_graph->num_thread); if (ret != 0) return -1; return 0; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct ir_node* exec_node) { return OPS_SCORE_CANDO; } static struct node_ops hcl_node_ops = {.prerun = prerun, .run = run, .reshape = NULL, .postrun = NULL, .init_node = init_node, .release_node = release_node, .score = score}; static int reg_round_hcl_ops(void* arg) { return register_builtin_node_ops(OP_ROUND, &hcl_node_ops); } static int unreg_round_hcl_ops(void* arg) { return unregister_builtin_node_ops(OP_ROUND, &hcl_node_ops); } AUTO_REGISTER_OPS(reg_round_hcl_ops); AUTO_UNREGISTER_OPS(unreg_round_hcl_ops);
omp_parallel_reduction.c
<ompts:test> <ompts:testdescription>Test which checks the omp parallel reduction directive with all its options.</ompts:testdescription> <ompts:ompversion>3.0</ompts:ompversion> <ompts:directive>omp parallel reduction</ompts:directive> <ompts:testcode> #include <stdio.h> #include <math.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_parallel_reduction</ompts:testcode:functionname>(FILE * logFile){ <ompts:orphan:vars> int sum; int known_sum; double dsum; double dknown_sum; double dt=0.5; /* base of geometric row for + and - test*/ double rounding_error= 1.E-9; #define DOUBLE_DIGITS 20 /* dt^DOUBLE_DIGITS */ int diff; double ddiff; int product; int known_product; #define MAX_FACTOR 10 #define KNOWN_PRODUCT 3628800 /* 10! */ int logic_and; int logic_or; int bit_and; int bit_or; int exclusiv_bit_or; int logics[LOOPCOUNT]; int i; double dpt; int result; </ompts:orphan:vars> sum =0; dsum=0; product=1; logic_and=1; logic_or=0; bit_and=1; bit_or=0; exclusiv_bit_or=0; result=0; dt = 1./3.; known_sum = (LOOPCOUNT*(LOOPCOUNT+1))/2; <ompts:orphan> #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(+:sum)</ompts:check><ompts:crosscheck></ompts:crosscheck> for (i=1;i<=LOOPCOUNT;i++) { sum=sum+i; } if(known_sum!=sum) { result++; fprintf(logFile,"Error in sum with integers: Result was %d instead of %d\n",sum,known_sum); } diff = (LOOPCOUNT*(LOOPCOUNT+1))/2; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(-:diff)</ompts:check><ompts:crosscheck></ompts:crosscheck> for (i=1;i<=LOOPCOUNT;++i) { diff=diff-i; } if(diff != 0) { result++; fprintf(logFile,"Error in difference with integers: Result was %d instead of 0.\n",diff); } /* Tests for doubles */ dsum=0; dpt=1; for (i=0;i<DOUBLE_DIGITS;++i) { dpt*=dt; } dknown_sum = (1-dpt)/(1-dt); #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(+:dsum)</ompts:check><ompts:crosscheck></ompts:crosscheck> for (i=0;i<DOUBLE_DIGITS;++i) { dsum += pow(dt,i); } if( fabs(dsum-dknown_sum) > rounding_error ) { result++; fprintf(logFile,"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",dsum,dknown_sum, dsum-dknown_sum); } dpt=1; for (i=0;i<DOUBLE_DIGITS;++i) { dpt*=dt; } fprintf(logFile,"\n"); ddiff = (1-dpt)/(1-dt); #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(-:ddiff)</ompts:check><ompts:crosscheck></ompts:crosscheck> for (i=0;i<DOUBLE_DIGITS;++i) { ddiff -= pow(dt,i); } if( fabs(ddiff) > rounding_error) { result++; fprintf(logFile,"Error in Difference with doubles: Result was %E instead of 0.0\n",ddiff); } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(*:product)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=1;i<=MAX_FACTOR;i++) { product *= i; } known_product = KNOWN_PRODUCT; if(known_product != product) { result++; fprintf(logFile,"Error in Product with integers: Result was %d instead of %d\n\n",product,known_product); } for(i=0;i<LOOPCOUNT;i++) { logics[i]=1; } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(&&:logic_and)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { logic_and = (logic_and && logics[i]); } if(!logic_and) { result++; fprintf(logFile,"Error in logic AND part 1.\n"); } logic_and = 1; logics[LOOPCOUNT/2]=0; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(&&:logic_and)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { logic_and = logic_and && logics[i]; } if(logic_and) { result++; fprintf(logFile,"Error in logic AND part 2.\n"); } for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(||:logic_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { logic_or = logic_or || logics[i]; } if(logic_or) { result++; fprintf(logFile,"Error in logic OR part 1.\n"); } logic_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(||:logic_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { logic_or = logic_or || logics[i]; } if(!logic_or) { result++; fprintf(logFile,"Error in logic OR part 2.\n"); } for(i=0;i<LOOPCOUNT;++i) { logics[i]=1; } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(&:bit_and)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { bit_and = (bit_and & logics[i]); } if(!bit_and) { result++; fprintf(logFile,"Error in BIT AND part 1.\n"); } bit_and = 1; logics[LOOPCOUNT/2]=0; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(&:bit_and)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { bit_and = bit_and & logics[i]; } if(bit_and) { result++; fprintf(logFile,"Error in BIT AND part 2.\n"); } for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(|:bit_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { bit_or = bit_or | logics[i]; } if(bit_or) { result++; fprintf(logFile,"Error in BIT OR part 1\n"); } bit_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(|:bit_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { bit_or = bit_or | logics[i]; } if(!bit_or) { result++; fprintf(logFile,"Error in BIT OR part 2\n"); } for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(^:exclusiv_bit_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } if(exclusiv_bit_or) { result++; fprintf(logFile,"Error in EXCLUSIV BIT OR part 1\n"); } exclusiv_bit_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) <ompts:check>reduction(^:exclusiv_bit_or)</ompts:check><ompts:crosscheck></ompts:crosscheck> for(i=0;i<LOOPCOUNT;++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } if(!exclusiv_bit_or) { result++; fprintf(logFile,"Error in EXCLUSIV BIT OR part 2\n"); } </ompts:orphan> /*printf("\nResult:%d\n",result);*/ return (result==0); } </ompts:testcode> </ompts:test>
pregpu.h
#ifndef pregpu_h #define pregpu_h #include <omp.h> static size_t keysDevcSize = 0; // Size of offsets for rangeHost static size_t rangeDevcSize = 0; // Size of offsets for sourceHost static size_t sourceDevcSize = 0; // Size of sources static size_t targetDevcSize = 0; // Size of targets static int *keysDevc; // Keys on device static int *rangeDevc; // Ranges on device static gpureal *sourceDevc; // Sources on device static gpureal *targetDevc; // Targets on device #pragma omp threadprivate(keysDevcSize,rangeDevcSize,sourceDevcSize,targetDevcSize) #pragma omp threadprivate(keysDevc,rangeDevc,sourceDevc,targetDevc) __device__ __constant__ gpureal constDevc[1]; // Constants on device namespace { // Limit scope of the following functions to nvcc __device__ void cart2sph(gpureal& r, gpureal& theta, gpureal& phi,// Get r,theta,phi from x,y,z on GPU gpureal dx, gpureal dy, gpureal dz) { r = sqrtf(dx * dx + dy * dy + dz * dz)+EPS; // r = sqrt(x^2 + y^2 + z^2) + eps theta = acosf(dz / r); // theta = acos(z / r) if( fabs(dx) + fabs(dy) < EPS ) { // If |x| < eps & |y| < eps phi = 0; // phi can be anything so we set it to 0 } else if( fabs(dx) < EPS ) { // If |x| < eps phi = dy / fabs(dy) * M_PI * 0.5; // phi = sign(y) * pi / 2 } else if( dx > 0 ) { // If x > 0 phi = atanf(dy / dx); // phi = atan(y / x) } else { // If x < 0 phi = atanf(dy / dx) + M_PI; // phi = atan(y / x) + pi } // End if for x,y cases } __device__ void sph2cart(gpureal r, gpureal theta, gpureal phi, // Spherical to cartesian coordinates on GPU gpureal *spherical, gpureal *cartesian) { cartesian[0] = sinf(theta) * cosf(phi) * spherical[0] // x component (not x itself) + cosf(theta) * cosf(phi) / r * spherical[1] - sinf(phi) / r / sinf(theta) * spherical[2]; cartesian[1] = sinf(theta) * sinf(phi) * spherical[0] // y component (not y itself) + cosf(theta) * sinf(phi) / r * spherical[1] + cosf(phi) / r / sinf(theta) * spherical[2]; cartesian[2] = cosf(theta) * spherical[0] // z component (not z itself) - sinf(theta) / r * spherical[1]; } __device__ void evalMultipole(gpureal *YnmShrd, gpureal rho, // Evaluate solid harmonics r^n * Ynm on GPU gpureal alpha, gpureal *factShrd) { gpureal x = cosf(alpha); // x = cos(alpha) gpureal y = sinf(alpha); // y = sin(alpha) gpureal fact = 1; // Initialize 2 * m + 1 gpureal pn = 1; // Initialize Legendre polynomial Pn gpureal rhom = 1; // Initialize rho^m for( int m=0; m<P; ++m ){ // Loop over m in Ynm gpureal p = pn; // Associate Legendre polynomial Pnm int npn = m * m + 2 * m; // Index of Ynm for m > 0 int nmn = m * m; // Index of Ynm for m < 0 YnmShrd[npn] = rhom * p / factShrd[2*m]; // rho^m * Ynm for m > 0 YnmShrd[nmn] = YnmShrd[npn]; // Use conjugate relation for m < 0 gpureal p1 = p; // Pnm-1 p = x * (2 * m + 1) * p; // Pnm using recurrence relation rhom *= -rho; // rho^m gpureal rhon = rhom; // rho^n for( int n=m+1; n<P; ++n ){ // Loop over n in Yn int npm = n * n + n + m; // Index of Ynm for m > 0 int nmm = n * n + n - m; // Index of Ynm for m < 0 YnmShrd[npm] = rhon * p / factShrd[n+m]; // rho^n * Ynm YnmShrd[nmm] = YnmShrd[npm]; // Use conjugate relation for m < 0 gpureal p2 = p1; // Pnm-2 p1 = p; // Pnm-1 p = (x * (2 * n + 1) * p1 - (n + m) * p2) / (n - m + 1); // Pnm using recurrence relation rhon *= -rho; // Update rho^n } // End loop over n in Ynm pn = -pn * fact * y; // Pn fact += 2; // 2 * m + 1 } // End loop over m in Ynm } __device__ void evalLocal(gpureal *YnmShrd, gpureal rho, // Evaluate singular harmonics r^(-n-1) * Ynm gpureal alpha, gpureal *factShrd) { gpureal x = cosf(alpha); // x = cos(alpha) gpureal y = sinf(alpha); // y = sin(alpha) gpureal rho_1 = 1 / rho; // 1 / rho for( int l=threadIdx.x; l<(2*P+1)*P; l+=THREADS ) { // Loop over coefficients in Ynm gpureal fact = 1; // Initialize 2 * m + 1 gpureal pn = 1; // Initialize Legendre polynomial Pn gpureal rhom = rho_1; // Initialize rho^(-m-1) int nn = floor(sqrtf(2*l+0.25)-0.5); // Calculate index n of Ynm int mm = 0; // Initialize index m of Ynm gpureal Ynm; // Define temporary Ynm for( int i=0; i<=nn; ++i ) mm += i; // Offset of m mm = l - mm; // Calculate index m of Ynm int n; // Define temporary n for( int m=0; m<mm; ++m ){ // Loop up to m rhom *= rho_1; // rho^(-m-1) pn = -pn * fact * y; // Pn fact += 2; // 2 * m + 1 } // End loop up to m int m = mm; // Define temporary m gpureal p = pn; // Associated Legendre polynomial Pnm if( mm == nn ) Ynm = rhom * p; // Ynm for n == m gpureal p1 = p; // Pnm-1 p = x * (2 * m + 1) * p; // Pnm rhom *= rho_1; // rho^(-m-1) gpureal rhon = rhom; // rho^(-n-1) for( n=m+1; n<nn; ++n ){ // Loop up to n gpureal p2 = p1; // Pnm-2 p1 = p; // Pnm-1 p = (x * (2 * n + 1) * p1 - (n + m) * p2) / (n - m + 1); // Pnm rhon *= rho_1; // rho^(-n-1) } // End loop up to n if( n <= nn ) Ynm = rhon * p * factShrd[n-m]; // rho^(-n-1) * Ynm YnmShrd[l] = Ynm; // Put Ynm in shared memory } // End loop over coefficients in Ynm __syncthreads(); // Syncronize threads } } // End anonymous namespace #endif
mttkrp_omp.c
/* This file is part of ParTI!. ParTI! is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ParTI! is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <ParTI.h> #include "sptensor.h" int sptOmpMTTKRP_3D(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk); int sptOmpMTTKRP_3D_Reduce(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptMatrix * copy_mats[], // temporary matrices for reduction sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk); int sptOmpMTTKRP_3D_Lock(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk, sptMutexPool * lock_pool); /** * OpenMP parallelized Matriced sparse tensor times a sequence of dense matrix Khatri-Rao products (MTTKRP) on a specified mode * @param[out] mats[nmodes] the result of MTTKRP, a dense matrix, with size * ndims[mode] * R * @param[in] X the sparse tensor input X * @param[in] mats (N+1) dense matrices, with mats[nmodes] as temporary * @param[in] mats_order the order of the Khatri-Rao products * @param[in] mode the mode on which the MTTKRP is performed * @param[in] scratch an temporary array to store intermediate results, space assigned before this function * * This function uses support arbitrary-order sparse tensors with Khatri-Rao * products of dense factor matrices, the output is the updated dense matrix for the "mode". * In this version, a large scratch is used to maximize parallelism. (To be optimized) */ int sptOmpMTTKRP_Init(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode) { sptIndex const nmodes = X->nmodes; sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const vals = X->values.data; sptIndex const stride = mats[0]->stride; sptValueVector scratch; // Temporary array sptNewValueVector(&scratch, nnz * stride, nnz * stride); sptConstantValueVector(&scratch, 0); /* Check the mats. */ for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const mode_ind = X->inds[mode].data; sptMatrix * const M = mats[nmodes]; sptValue * const mvals = M->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); #pragma omp parallel for for(sptNnzIndex x=0; x<nnz; ++x) { sptIndex times_mat_index = mats_order[1]; sptMatrix * times_mat = mats[times_mat_index]; sptIndex * times_inds = X->inds[times_mat_index].data; sptIndex tmp_i = times_inds[x]; sptValue const entry = vals[x]; for(sptIndex r=0; r<R; ++r) { scratch.data[x * stride + r] = entry * times_mat->values[tmp_i * stride + r]; } for(sptIndex i=2; i<nmodes; ++i) { times_mat_index = mats_order[i]; times_mat = mats[times_mat_index]; times_inds = X->inds[times_mat_index].data; tmp_i = times_inds[x]; for(sptIndex r=0; r<R; ++r) { scratch.data[x * stride + r] *= times_mat->values[tmp_i * stride + r]; } } } for(sptNnzIndex x=0; x<nnz; ++x) { sptIndex const mode_i = mode_ind[x]; for(sptIndex r=0; r<R; ++r) { mvals[mode_i * stride + r] += scratch.data[x * stride + r]; } } sptFreeValueVector(&scratch); return 0; } int sptOmpMTTKRP(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk) { sptIndex const nmodes = X->nmodes; if(nmodes == 3) { sptAssert(sptOmpMTTKRP_3D(X, mats, mats_order, mode, tk) == 0); return 0; } sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const mode_ind = X->inds[mode].data; sptValue * const restrict mvals = mats[nmodes]->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { sptValueVector scratch; // Temporary array sptNewValueVector(&scratch, R, R); sptConstantValueVector(&scratch, 0); sptIndex times_mat_index = mats_order[1]; sptMatrix * times_mat = mats[times_mat_index]; sptIndex * times_inds = X->inds[times_mat_index].data; sptIndex tmp_i = times_inds[x]; sptValue const entry = vals[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { scratch.data[r] = entry * times_mat->values[tmp_i * stride + r]; } for(sptIndex i=2; i<nmodes; ++i) { times_mat_index = mats_order[i]; times_mat = mats[times_mat_index]; times_inds = X->inds[times_mat_index].data; tmp_i = times_inds[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { scratch.data[r] *= times_mat->values[tmp_i * stride + r]; } } sptIndex const mode_i = mode_ind[x]; sptValue * const restrict mvals_row = mvals + mode_i * stride; for(sptIndex r=0; r<R; ++r) { #pragma omp atomic update mvals_row[r] += scratch.data[r]; } sptFreeValueVector(&scratch); } // End loop nnzs return 0; } int sptOmpMTTKRP_3D(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk) { sptIndex const nmodes = X->nmodes; sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const restrict vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ sptAssert(nmodes ==3); for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const restrict mode_ind = X->inds[mode].data; sptValue * const restrict mvals = mats[nmodes]->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); sptIndex times_mat_index_1 = mats_order[1]; sptMatrix * restrict times_mat_1 = mats[times_mat_index_1]; sptIndex * restrict times_inds_1 = X->inds[times_mat_index_1].data; sptIndex times_mat_index_2 = mats_order[2]; sptMatrix * restrict times_mat_2 = mats[times_mat_index_2]; sptIndex * restrict times_inds_2 = X->inds[times_mat_index_2].data; #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { sptIndex mode_i = mode_ind[x]; sptValue * const restrict mvals_row = mvals + mode_i * stride; sptIndex tmp_i_1 = times_inds_1[x]; sptIndex tmp_i_2 = times_inds_2[x]; sptValue entry = vals[x]; for(sptIndex r=0; r<R; ++r) { #pragma omp atomic update mvals_row[r] += entry * times_mat_1->values[tmp_i_1 * stride + r] * times_mat_2->values[tmp_i_2 * stride + r]; } } return 0; } int sptOmpMTTKRP_Lock(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk, sptMutexPool * lock_pool) { sptIndex const nmodes = X->nmodes; if(nmodes == 3) { sptAssert(sptOmpMTTKRP_3D_Lock(X, mats, mats_order, mode, tk, lock_pool) == 0); return 0; } sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const mode_ind = X->inds[mode].data; sptValue * const mvals = mats[nmodes]->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { sptValueVector scratch; // Temporary array sptNewValueVector(&scratch, R, R); sptConstantValueVector(&scratch, 0); sptIndex times_mat_index = mats_order[1]; sptMatrix * times_mat = mats[times_mat_index]; sptIndex * times_inds = X->inds[times_mat_index].data; sptIndex tmp_i = times_inds[x]; sptValue const entry = vals[x]; for(sptIndex r=0; r<R; ++r) { scratch.data[r] = entry * times_mat->values[tmp_i * stride + r]; } for(sptIndex i=2; i<nmodes; ++i) { times_mat_index = mats_order[i]; times_mat = mats[times_mat_index]; times_inds = X->inds[times_mat_index].data; tmp_i = times_inds[x]; for(sptIndex r=0; r<R; ++r) { scratch.data[r] *= times_mat->values[tmp_i * stride + r]; } } sptIndex const mode_i = mode_ind[x]; sptValue * const restrict mvals_row = mvals + mode_i * stride; sptMutexSetLock(lock_pool, mode_i); for(sptIndex r=0; r<R; ++r) { mvals_row[r] += scratch.data[r]; } sptMutexUnsetLock(lock_pool, mode_i); sptFreeValueVector(&scratch); } // End loop nnzs return 0; } int sptOmpMTTKRP_3D_Lock(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk, sptMutexPool * lock_pool) { sptIndex const nmodes = X->nmodes; sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const restrict vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ sptAssert(nmodes ==3); for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const restrict mode_ind = X->inds[mode].data; sptValue * const restrict mvals = mats[nmodes]->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); sptIndex times_mat_index_1 = mats_order[1]; sptMatrix * restrict times_mat_1 = mats[times_mat_index_1]; sptIndex * restrict times_inds_1 = X->inds[times_mat_index_1].data; sptIndex times_mat_index_2 = mats_order[2]; sptMatrix * restrict times_mat_2 = mats[times_mat_index_2]; sptIndex * restrict times_inds_2 = X->inds[times_mat_index_2].data; #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { sptValueVector scratch; // Temporary array sptNewValueVector(&scratch, R, R); sptConstantValueVector(&scratch, 0); sptIndex mode_i = mode_ind[x]; sptValue * const restrict mvals_row = mvals + mode_i * stride; sptIndex tmp_i_1 = times_inds_1[x]; sptIndex tmp_i_2 = times_inds_2[x]; sptValue entry = vals[x]; for(sptIndex r=0; r<R; ++r) { scratch.data[r] = entry * times_mat_1->values[tmp_i_1 * stride + r] * times_mat_2->values[tmp_i_2 * stride + r]; } sptMutexSetLock(lock_pool, mode_i); for(sptIndex r=0; r<R; ++r) { mvals_row[r] += scratch.data[r]; } sptMutexUnsetLock(lock_pool, mode_i); sptFreeValueVector(&scratch); } return 0; } int sptOmpMTTKRP_Reduce(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptMatrix * copy_mats[], // temporary matrices for reduction sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk) { sptIndex const nmodes = X->nmodes; if(nmodes == 3) { sptAssert(sptOmpMTTKRP_3D_Reduce(X, mats, copy_mats, mats_order, mode, tk) == 0); return 0; } sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const mode_ind = X->inds[mode].data; sptMatrix * const M = mats[nmodes]; sptValue * const mvals = M->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); for(int t=0; t<tk; ++t) { memset(copy_mats[t]->values, 0, ndims[mode]*stride*sizeof(*(copy_mats[t]->values))); } #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { int tid = omp_get_thread_num(); sptValueVector scratch; // Temporary array sptNewValueVector(&scratch, R, R); sptConstantValueVector(&scratch, 0); sptIndex times_mat_index = mats_order[1]; sptMatrix * times_mat = mats[times_mat_index]; sptIndex * times_inds = X->inds[times_mat_index].data; sptIndex tmp_i = times_inds[x]; sptValue const entry = vals[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { scratch.data[r] = entry * times_mat->values[tmp_i * stride + r]; } for(sptIndex i=2; i<nmodes; ++i) { times_mat_index = mats_order[i]; times_mat = mats[times_mat_index]; times_inds = X->inds[times_mat_index].data; tmp_i = times_inds[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { scratch.data[r] *= times_mat->values[tmp_i * stride + r]; } } sptIndex const mode_i = mode_ind[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { copy_mats[tid]->values[mode_i * stride + r] += scratch.data[r]; } sptFreeValueVector(&scratch); } // End loop nnzs /* Reduction */ #pragma omp parallel for schedule(static) num_threads(tk) for(sptIndex i=0; i<ndims[mode]; ++i) { for(int t=0; t<tk; ++t) { #pragma omp simd for(sptIndex r=0; r<R; ++r) { mvals[i * stride + r] += copy_mats[t]->values[i * stride + r]; } } } return 0; } int sptOmpMTTKRP_3D_Reduce(sptSparseTensor const * const X, sptMatrix * mats[], // mats[nmodes] as temporary space. sptMatrix * copy_mats[], // temporary matrices for reduction sptIndex const mats_order[], // Correspond to the mode order of X. sptIndex const mode, const int tk) { sptIndex const nmodes = X->nmodes; sptNnzIndex const nnz = X->nnz; sptIndex const * const ndims = X->ndims; sptValue const * const restrict vals = X->values.data; sptIndex const stride = mats[0]->stride; /* Check the mats. */ sptAssert(nmodes ==3); for(sptIndex i=0; i<nmodes; ++i) { if(mats[i]->ncols != mats[nmodes]->ncols) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols"); } if(mats[i]->nrows != ndims[i]) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "CPU SpTns MTTKRP", "mats[i]->nrows != ndims[i]"); } } sptIndex const tmpI = mats[mode]->nrows; sptIndex const R = mats[mode]->ncols; sptIndex const * const restrict mode_ind = X->inds[mode].data; sptMatrix * const restrict M = mats[nmodes]; sptValue * const restrict mvals = M->values; memset(mvals, 0, tmpI*stride*sizeof(sptValue)); for(int t=0; t<tk; ++t) { memset(copy_mats[t]->values, 0, ndims[mode]*stride*sizeof(*(copy_mats[t]->values))); } sptIndex times_mat_index_1 = mats_order[1]; sptMatrix * restrict times_mat_1 = mats[times_mat_index_1]; sptIndex * restrict times_inds_1 = X->inds[times_mat_index_1].data; sptIndex times_mat_index_2 = mats_order[2]; sptMatrix * restrict times_mat_2 = mats[times_mat_index_2]; sptIndex * restrict times_inds_2 = X->inds[times_mat_index_2].data; #pragma omp parallel for schedule(static) num_threads(tk) for(sptNnzIndex x=0; x<nnz; ++x) { int tid = omp_get_thread_num(); sptIndex mode_i = mode_ind[x]; sptIndex tmp_i_1 = times_inds_1[x]; sptIndex tmp_i_2 = times_inds_2[x]; sptValue entry = vals[x]; #pragma omp simd for(sptIndex r=0; r<R; ++r) { copy_mats[tid]->values[mode_i * stride + r] += entry * times_mat_1->values[tmp_i_1 * stride + r] * times_mat_2->values[tmp_i_2 * stride + r]; } } /* Reduction */ #pragma omp parallel for schedule(static) num_threads(tk) for(sptIndex i=0; i<ndims[mode]; ++i) { for(int t=0; t<tk; ++t) { #pragma omp simd for(sptIndex r=0; r<R; ++r) { mvals[i * stride + r] += copy_mats[t]->values[i * stride + r]; } } } return 0; }
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #else const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); float32x4_t _sum2 = vmulq_laneq_f32(_r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); float32x4_t _sum4 = vmulq_laneq_f32(_r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmul.f32 q6, q11, %e14[1] \n" "vmul.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmul.f32 q14, q11, %e14[1] \n" "vmul.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q8, q8, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); float32x4_t _sum2 = vmulq_laneq_f32(_r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmul.f32 q13, q10, %e10[1] \n" "vmul.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q7, q7, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(8*8, inch, outch); const float ktm[8][3] = { { 1.0f, 0.0f, 0.0f}, {-2.0f/9, -2.0f/9, -2.0f/9}, {-2.0f/9, 2.0f/9, -2.0f/9}, {1.0f/90, 1.0f/45, 2.0f/45}, {1.0f/90, -1.0f/45, 2.0f/45}, {1.0f/45, 1.0f/90, 1.0f/180}, {1.0f/45, -1.0f/90, 1.0f/180}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = kernel.data + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i=0; i<8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j=0; j<8; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<8; i++) { kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd64_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8*8, w_tm/8 * h_tm/8, inch); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm = img0_tm.row(i * w_tm/8 + j); // TODO neon optimize for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; r0_tm += 8; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8*8, w_tm/8 * h_tm/8, outch); int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); Mat out2_tm = top_blob_tm.channel(p+2); Mat out3_tm = top_blob_tm.channel(p+3); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); const Mat kernel2_tm = kernel_tm.channel(p+2); const Mat kernel3_tm = kernel_tm.channel(p+3); out0_tm.fill(0.f); out1_tm.fill(0.f); out2_tm.fill(0.f); out3_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k00 = kernel0_tm.row(q); const float* k10 = kernel1_tm.row(q); const float* k20 = kernel2_tm.row(q); const float* k30 = kernel3_tm.row(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output2_tm = vld1q_f32(output2_tm); float32x4_t _output3_tm = vld1q_f32(output3_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k00 = vld1q_f32(k00); k00 += 64; float32x4_t _k01 = vld1q_f32(k00); k00 += 64; float32x4_t _k02 = vld1q_f32(k00); k00 += 64; float32x4_t _k03 = vld1q_f32(k00); k00 += 64; k00 -= 64*4; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k02); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k03); float32x4_t _k10 = vld1q_f32(k10); k10 += 64; float32x4_t _k11 = vld1q_f32(k10); k10 += 64; float32x4_t _k12 = vld1q_f32(k10); k10 += 64; float32x4_t _k13 = vld1q_f32(k10); k10 += 64; k10 -= 64*4; _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tm = vmlaq_f32(_output1_tm, _r2, _k12); _output1_tm = vmlaq_f32(_output1_tm, _r3, _k13); float32x4_t _k20 = vld1q_f32(k20); k20 += 64; float32x4_t _k21 = vld1q_f32(k20); k20 += 64; float32x4_t _k22 = vld1q_f32(k20); k20 += 64; float32x4_t _k23 = vld1q_f32(k20); k20 += 64; k20 -= 64*4; _output2_tm = vmlaq_f32(_output2_tm, _r0, _k20); _output2_tm = vmlaq_f32(_output2_tm, _r1, _k21); _output2_tm = vmlaq_f32(_output2_tm, _r2, _k22); _output2_tm = vmlaq_f32(_output2_tm, _r3, _k23); float32x4_t _k30 = vld1q_f32(k30); k30 += 64; float32x4_t _k31 = vld1q_f32(k30); k30 += 64; float32x4_t _k32 = vld1q_f32(k30); k30 += 64; float32x4_t _k33 = vld1q_f32(k30); k30 += 64; k30 -= 64*4; _output3_tm = vmlaq_f32(_output3_tm, _r0, _k30); _output3_tm = vmlaq_f32(_output3_tm, _r1, _k31); _output3_tm = vmlaq_f32(_output3_tm, _r2, _k32); _output3_tm = vmlaq_f32(_output3_tm, _r3, _k33); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output2_tm, _output2_tm); vst1q_f32(output3_tm, _output3_tm); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k00 += 4; k10 += 4; k20 += 4; k30 += 4; float32x4_t _output0_tmn = vld1q_f32(output0_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm); float32x4_t _output2_tmn = vld1q_f32(output2_tm); float32x4_t _output3_tmn = vld1q_f32(output3_tm); float32x4_t _r0n = vld1q_f32(r0); float32x4_t _r1n = vld1q_f32(r1); float32x4_t _r2n = vld1q_f32(r2); float32x4_t _r3n = vld1q_f32(r3); float32x4_t _k00n = vld1q_f32(k00); k00 += 64; float32x4_t _k01n = vld1q_f32(k00); k00 += 64; float32x4_t _k02n = vld1q_f32(k00); k00 += 64; float32x4_t _k03n = vld1q_f32(k00); k00 += 64; k00 -= 64*4; _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output0_tmn = vmlaq_f32(_output0_tmn, _r2n, _k02n); _output0_tmn = vmlaq_f32(_output0_tmn, _r3n, _k03n); float32x4_t _k10n = vld1q_f32(k10); k10 += 64; float32x4_t _k11n = vld1q_f32(k10); k10 += 64; float32x4_t _k12n = vld1q_f32(k10); k10 += 64; float32x4_t _k13n = vld1q_f32(k10); k10 += 64; k10 -= 64*4; _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); _output1_tmn = vmlaq_f32(_output1_tmn, _r2n, _k12n); _output1_tmn = vmlaq_f32(_output1_tmn, _r3n, _k13n); float32x4_t _k20n = vld1q_f32(k20); k20 += 64; float32x4_t _k21n = vld1q_f32(k20); k20 += 64; float32x4_t _k22n = vld1q_f32(k20); k20 += 64; float32x4_t _k23n = vld1q_f32(k20); k20 += 64; k20 -= 64*4; _output2_tmn = vmlaq_f32(_output2_tmn, _r0n, _k20n); _output2_tmn = vmlaq_f32(_output2_tmn, _r1n, _k21n); _output2_tmn = vmlaq_f32(_output2_tmn, _r2n, _k22n); _output2_tmn = vmlaq_f32(_output2_tmn, _r3n, _k23n); float32x4_t _k30n = vld1q_f32(k30); k30 += 64; float32x4_t _k31n = vld1q_f32(k30); k30 += 64; float32x4_t _k32n = vld1q_f32(k30); k30 += 64; float32x4_t _k33n = vld1q_f32(k30); k30 += 64; k30 -= 64*4; _output3_tmn = vmlaq_f32(_output3_tmn, _r0n, _k30n); _output3_tmn = vmlaq_f32(_output3_tmn, _r1n, _k31n); _output3_tmn = vmlaq_f32(_output3_tmn, _r2n, _k32n); _output3_tmn = vmlaq_f32(_output3_tmn, _r3n, _k33n); vst1q_f32(output0_tm, _output0_tmn); vst1q_f32(output1_tm, _output1_tmn); vst1q_f32(output2_tm, _output2_tmn); vst1q_f32(output3_tm, _output3_tmn); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k00 += 4; k10 += 4; k20 += 4; k30 += 4; } #else // __aarch64__ asm volatile( "mov r4, #8 \n" "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]\n"//q8 q9 = _output0_tm "0: \n" "pld [%4, #256] \n" "vld1.f32 {d0-d3}, [%4 :128]! \n"//q0 q1 = _r0 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k00 "add %8, %8, #256 \n" "vmla.f32 q8, q0, q10 \n" "vmla.f32 q9, q1, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]\n"//q12 q13 = _output1_tm "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k10 "add %9, %9, #256 \n" "vmla.f32 q12, q0, q14 \n" "vmla.f32 q13, q1, q15 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n"//q2 q3 = _r1 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k01 "add %8, %8, #256 \n" "vmla.f32 q8, q2, q10 \n" "vmla.f32 q9, q3, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k11 "add %9, %9, #256 \n" "vmla.f32 q12, q2, q14 \n" "vmla.f32 q13, q3, q15 \n" "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]!\n"//q4 q5 = _r2 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k02 "add %8, %8, #256 \n" "vmla.f32 q8, q4, q10 \n" "vmla.f32 q9, q5, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k12 "add %9, %9, #256 \n" "vmla.f32 q12, q4, q14 \n" "vmla.f32 q13, q5, q15 \n" "pld [%7, #256] \n" "vld1.f32 {d12-d15}, [%7 :128]!\n"//q6 q7 = _r3 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k03 "sub %8, %8, #736 \n" "vmla.f32 q8, q6, q10 \n" "vmla.f32 q9, q7, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k13 "sub %9, %9, #736 \n" "vmla.f32 q12, q6, q14 \n" "vmla.f32 q13, q7, q15 \n" "vst1.f32 {d16-d19}, [%0 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]\n"//q8 q9 = _output2_tm "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k20 "add %10, %10, #256 \n" "vmla.f32 q8, q0, q10 \n" "vmla.f32 q9, q1, q11 \n" "vst1.f32 {d24-d27}, [%1 :128]!\n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]\n"//q12 q13 = _output3_tm "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k30 "add %11, %11, #256 \n" "vmla.f32 q12, q0, q14 \n" "vmla.f32 q13, q1, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k21 "add %10, %10, #256 \n" "vmla.f32 q8, q2, q10 \n" "vmla.f32 q9, q3, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k31 "add %11, %11, #256 \n" "vmla.f32 q12, q2, q14 \n" "vmla.f32 q13, q3, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k22 "add %10, %10, #256 \n" "vmla.f32 q8, q4, q10 \n" "vmla.f32 q9, q5, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k32 "add %11, %11, #256 \n" "vmla.f32 q12, q4, q14 \n" "vmla.f32 q13, q5, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k23 "sub %10, %10, #736 \n" "vmla.f32 q8, q6, q10 \n" "vmla.f32 q9, q7, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k33 "sub %11, %11, #736 \n" "vmla.f32 q12, q6, q14 \n" "vmla.f32 q13, q7, q15 \n" "vst1.f32 {d16-d19}, [%2 :128]!\n" "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]\n"//q8 q9 = _output0_tm "subs r4, r4, #1 \n" "vst1.f32 {d24-d27}, [%3 :128]!\n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(r2), // %6 "=r"(r3), // %7 "=r"(k00), // %8 "=r"(k10), // %9 "=r"(k20), // %10 "=r"(k30) // %11 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "6"(r2), "7"(r3), "8"(k00), "9"(k10), "10"(k20), "11"(k30) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k00 -= 64; k10 -= 64; k20 -= 64; k30 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k00[m]; k00 += 64; output0_tm[m] += r1[m] * k00[m]; k00 += 64; output0_tm[m] += r2[m] * k00[m]; k00 += 64; output0_tm[m] += r3[m] * k00[m]; k00 += 64; k00 -= 64 * 4; output1_tm[m] += r0[m] * k10[m]; k10 += 64; output1_tm[m] += r1[m] * k10[m]; k10 += 64; output1_tm[m] += r2[m] * k10[m]; k10 += 64; output1_tm[m] += r3[m] * k10[m]; k10 += 64; k10 -= 64 * 4; output2_tm[m] += r0[m] * k20[m]; k20 += 64; output2_tm[m] += r1[m] * k20[m]; k20 += 64; output2_tm[m] += r2[m] * k20[m]; k20 += 64; output2_tm[m] += r3[m] * k20[m]; k20 += 64; k20 -= 64 * 4; output3_tm[m] += r0[m] * k30[m]; k30 += 64; output3_tm[m] += r1[m] * k30[m]; k30 += 64; output3_tm[m] += r2[m] * k30[m]; k30 += 64; output3_tm[m] += r3[m] * k30[m]; k30 += 64; k30 -= 64 * 4; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; output1_tm += 64; output2_tm += 64; output3_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output1_tm[m] += r0[m] * k1[m]; output2_tm[m] += r0[m] * k2[m]; output3_tm[m] += r0[m] * k3[m]; } r0 += 64; output0_tm += 64; output1_tm += 64; output2_tm += 64; output3_tm += 64; } } } #pragma omp parallel for for (int p=remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k2); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k3); vst1q_f32(output0_tm, _output0_tm); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; float32x4_t _output0_tmn = vld1q_f32(output0_tm); float32x4_t _r0n = vld1q_f32(r0); float32x4_t _r1n = vld1q_f32(r1); float32x4_t _r2n = vld1q_f32(r2); float32x4_t _r3n = vld1q_f32(r3); float32x4_t _k0n = vld1q_f32(k0); float32x4_t _k1n = vld1q_f32(k1); float32x4_t _k2n = vld1q_f32(k2); float32x4_t _k3n = vld1q_f32(k3); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); _output0_tmn = vmlaq_f32(_output0_tmn, _r2n, _k2n); _output0_tmn = vmlaq_f32(_output0_tmn, _r3n, _k3n); vst1q_f32(output0_tm, _output0_tmn); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; } #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "mov r4, %0 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "vmla.f32 q15, q9, q11 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(k0), // %5 "=r"(k1), // %6 "=r"(k2), // %7 "=r"(k3) // %8 : "0"(output0_tm), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(k0), "6"(k1), "7"(k2), "8"(k3) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k0 -= 64; k1 -= 64; k2 -= 64; k3 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; output0_tm[m] += r2[m] * k2[m]; output0_tm[m] += r3[m] * k3[m]; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 64; output0_tm += 64; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm = out0_tm.row(i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; // TODO neon optimize for (int m=0; m<8; m++) { float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm += 8; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s1_winograd64_neon2(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, inch); const int tiles = w_tm/8 * h_tm/8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm01 = img0_tm.row(i * w_tm/8 + j); float* r0_tm23 = img0_tm.row(tiles + i * w_tm/8 + j); float* r0_tm45 = img0_tm.row(tiles * 2 + i * w_tm/8 + j); float* r0_tm67 = img0_tm.row(tiles * 3 + i * w_tm/8 + j); for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tms[4] = { r0_tm01, r0_tm23, r0_tm45, r0_tm67 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm = r0_tms[m/2] + (m%2) * 8; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k1n = vld1q_f32(k1+4); float32x4_t _k1nn = vld1q_f32(k1+8); float32x4_t _k1nnn = vld1q_f32(k1+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; float32x4_t _k1; float32x4_t _k1n; float32x4_t _k1nn; float32x4_t _k1nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "pld [%1, #512] \n" "vld1.f32 {%e4-%f4}, [%1 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e5-%f5}, [%1 :128]! \n" "vld1.f32 {%e6-%f6}, [%0 :128]! \n" "vld1.f32 {%e8-%f8}, [%1 :128]! \n" "vld1.f32 {%e7-%f7}, [%0 :128]! \n" "vld1.f32 {%e9-%f9}, [%1 :128]! \n" : "=r"(k0), // %0 "=r"(k1), // %1 "=w"(_k0), // %2 "=w"(_k0n), // %3 "=w"(_k1), // %4 "=w"(_k1n), // %5 "=w"(_k0nn), // %6 "=w"(_k0nnn), // %7 "=w"(_k1nn), // %8 "=w"(_k1nnn) // %9 : "0"(k0), "1"(k1) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; } #else if (nn > 0) { asm volatile( "mov r4, %1 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "0: \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "subs %0, #1 \n" "vst1.f32 {d20-d23}, [r4 :128]! \n" "bne 0b \n" "sub %1, #32 \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(r1), "w"(_k0), // %8 "w"(_k0n), // %9 "w"(_k1), // %10 "w"(_k1n), // %11 "w"(_k0nn), // %12 "w"(_k0nnn), // %13 "w"(_k1nn), // %14 "w"(_k1nnn) // %15 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q9, q13, %q7 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "vmla.f32 q8, q14, %q8 \n" "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q9, q15, %q9 \n" "vmla.f32 q10, q12, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q10, q14, %q12 \n" "vmla.f32 q11, q15, %q13 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1) // %2 : "0"(output0_tm), "1"(r0), "2"(r1), "w"(_k0), // %6 "w"(_k0n), // %7 "w"(_k1), // %8 "w"(_k1n), // %9 "w"(_k0nn), // %10 "w"(_k0nnn), // %11 "w"(_k1nn), // %12 "w"(_k1nnn) // %13 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; } r0 += 16; r1 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; k1 += 16; #endif // __aarch64__ #else k0 += 16; k1 += 16; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e1-%f1}, [%0 :128]! \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e4-%f4}, [%0 :128]! \n" : "=r"(k0), // %0 "=w"(_k0), // %1 "=w"(_k0n), // %2 "=w"(_k0nn), // %3 "=w"(_k0nnn) // %4 : "0"(k0) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q4 \n" "vmla.f32 q9, q13, %q5 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q6 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "vmla.f32 q11, q13, %q7 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k0), // %4 "w"(_k0n), // %5 "w"(_k0nn), // %6 "w"(_k0nnn) // %7 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; #endif // __aarch64__ #else k0 += 16; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm/8 * h_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm01 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm23 = out0_tm.row(tiles + i * w_tm/8 + j); const float* output0_tm45 = out0_tm.row(tiles * 2 + i * w_tm/8 + j); const float* output0_tm67 = out0_tm.row(tiles * 3 + i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms[4] = { output0_tm01, output0_tm23, output0_tm45, output0_tm67 }; for (int m=0; m<8; m++) { const float* output0_tm = output0_tms[m/2] + (m%2) * 8; float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s1_winograd64_neon3(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8, 8 * w_tm/8 * h_tm/8, inch); const int tiles = w_tm/8 * h_tm/8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm0 = img0_tm.row(i * w_tm/8 + j); float* r0_tm1 = img0_tm.row(i * w_tm/8 + j + tiles); float* r0_tm2 = img0_tm.row(i * w_tm/8 + j + tiles * 2); float* r0_tm3 = img0_tm.row(i * w_tm/8 + j + tiles * 3); float* r0_tm4 = img0_tm.row(i * w_tm/8 + j + tiles * 4); float* r0_tm5 = img0_tm.row(i * w_tm/8 + j + tiles * 5); float* r0_tm6 = img0_tm.row(i * w_tm/8 + j + tiles * 6); float* r0_tm7 = img0_tm.row(i * w_tm/8 + j + tiles * 7); for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tms[8] = { r0_tm0, r0_tm1, r0_tm2, r0_tm3, r0_tm4, r0_tm5, r0_tm6, r0_tm7 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm = r0_tms[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8, 8 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 2; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); out0_tm.fill(0.f); out1_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q+1); const float* k10 = kernel1_tm.row(q); const float* k11 = kernel1_tm.row(q+1); float* output0_tm = out0_tm; float* output1_tm = out1_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); float32x4_t _k01 = vld1q_f32(k01); float32x4_t _k01n = vld1q_f32(k01+4); float32x4_t _k10 = vld1q_f32(k10); float32x4_t _k10n = vld1q_f32(k10+4); float32x4_t _k11 = vld1q_f32(k11); float32x4_t _k11n = vld1q_f32(k11+4); #else float32x4_t _k00; float32x4_t _k00n; float32x4_t _k01; float32x4_t _k01n; float32x4_t _k10; float32x4_t _k10n; float32x4_t _k11; float32x4_t _k11n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e4-%f4}, [%0 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {%e6-%f6}, [%1 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {%e8-%f8}, [%2 :128]! \n" "pld [%3, #256] \n" "vld1.f32 {%e10-%f10}, [%3 :128]! \n" "vld1.f32 {%e5-%f5}, [%0 :128]! \n" "vld1.f32 {%e7-%f7}, [%1 :128]! \n" "vld1.f32 {%e9-%f9}, [%2 :128]! \n" "vld1.f32 {%e11-%f11}, [%3 :128]! \n" : "=r"(k00), // %0 "=r"(k01), // %1 "=r"(k10), // %2 "=r"(k11), // %3 "=w"(_k00), // %4 "=w"(_k00n), // %5 "=w"(_k01), // %6 "=w"(_k01n), // %7 "=w"(_k10), // %8 "=w"(_k10n), // %9 "=w"(_k11), // %10 "=w"(_k11n) // %11 : "0"(k00), "1"(k01), "2"(k10), "3"(k11) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; } #else if (nn > 0) { asm volatile( "0: \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(r1) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(r1), "w"(_k00), // %10 "w"(_k00n), // %11 "w"(_k01), // %12 "w"(_k01n), // %13 "w"(_k10), // %14 "w"(_k10n), // %15 "w"(_k11), // %16 "w"(_k11n) // %17 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; #else asm volatile( "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" "vst1.f32 {d20-d23}, [%1 :128]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(output0_tm), "1"(output1_tm), "2"(r0), "3"(r1), "w"(_k00), // %8 "w"(_k00n), // %9 "w"(_k01), // %10 "w"(_k01n), // %11 "w"(_k10), // %12 "w"(_k10n), // %13 "w"(_k11), // %14 "w"(_k11n) // %15 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; output0_tm[m] += r1[m] * k01[m]; output1_tm[m] += r0[m] * k10[m]; output1_tm[m] += r1[m] * k11[m]; } r0 += 8; r1 += 8; output0_tm += 8; output1_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; k01 += 8; k10 += 8; k11 += 8; #endif // __aarch64__ #else k00 += 8; k01 += 8; k10 += 8; k11 += 8; #endif // __ARM_NEON } } } #pragma omp parallel for for (int p = remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q+1); float* output0_tm = out0_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); float32x4_t _k01 = vld1q_f32(k01); float32x4_t _k01n = vld1q_f32(k01+4); #else float32x4_t _k00; float32x4_t _k00n; float32x4_t _k01; float32x4_t _k01n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {%e4-%f4}, [%1 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e5-%f5}, [%1 :128]! \n" : "=r"(k00), // %0 "=r"(k01), // %1 "=w"(_k00), // %2 "=w"(_k00n), // %3 "=w"(_k01), // %4 "=w"(_k01n) // %5 : "0"(k00), "1"(k01) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; } #else if (nn > 0) { asm volatile( "0: \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(r1), "w"(_k00), // %8 "w"(_k00n), // %9 "w"(_k01), // %10 "w"(_k01n) // %11 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q6 \n" "vmla.f32 q9, q13, %q7 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q8 \n" "vmla.f32 q9, q15, %q9 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1) // %2 : "0"(output0_tm), "1"(r0), "2"(r1), "w"(_k00), // %6 "w"(_k00n), // %7 "w"(_k01), // %8 "w"(_k01n) // %9 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; output0_tm[m] += r1[m] * k01[m]; } r0 += 8; r1 += 8; output0_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; k01 += 8; #endif // __aarch64__ #else k00 += 8; k01 += 8; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k00 = kernel0_tm.row(q); float* output0_tm = out0_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); #else float32x4_t _k00; float32x4_t _k00n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e1-%f1}, [%0 :128]! \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" : "=r"(k00), // %0 "=w"(_k00), // %1 "=w"(_k00n) // %2 : "0"(k00) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q4 \n" "vmla.f32 q9, q13, %q5 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00), // %4 "w"(_k00n) // %5 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; } r0 += 8; output0_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; #endif // __aarch64__ #else k00 += 8; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm/8 * h_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm0 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm1 = out0_tm.row(i * w_tm/8 + j + tiles); const float* output0_tm2 = out0_tm.row(i * w_tm/8 + j + tiles * 2); const float* output0_tm3 = out0_tm.row(i * w_tm/8 + j + tiles * 3); const float* output0_tm4 = out0_tm.row(i * w_tm/8 + j + tiles * 4); const float* output0_tm5 = out0_tm.row(i * w_tm/8 + j + tiles * 5); const float* output0_tm6 = out0_tm.row(i * w_tm/8 + j + tiles * 6); const float* output0_tm7 = out0_tm.row(i * w_tm/8 + j + tiles * 7); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms[8] = { output0_tm0, output0_tm1, output0_tm2, output0_tm3, output0_tm4, output0_tm5, output0_tm6, output0_tm7 }; for (int m=0; m<8; m++) { const float* output0_tm = output0_tms[m]; float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmul.f32 q10, q3, %e10[1] \n" "pld [%2, #128] \n" "vld2.f32 {d16-d17}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmul.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #128] \n" "vld2.f32 {d16-d17}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #128] \n" "vld2.f32 {d16-d17}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "vadd.f32 q0, q0, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } }
fast_statistics.h
#pragma once #ifndef FASTSTATISTIC_H #define FASTSTATISTIC_H #include <stdint.h> #include <random> #include <chrono> #define MERGE(x, y) ((x & 0xFFFFFFF0) | (y)) /* This code was adapted by Zur Shmaria in order to use parameterized seed (Needed for multithreading) */ namespace SplitMix64 { /* Modified by D. Lemire, August 2017 */ /*** Fast Splittable Pseudorandom Number Generators Steele Jr, Guy L., Doug Lea, and Christine H. Flood. "Fast splittable pseudorandom number generators." ACM SIGPLAN Notices 49.10 (2014): 453-472. ***/ /* Written in 2015 by Sebastiano Vigna (vigna@acm.org) To the extent possible under law, the author has dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. See <http://creativecommons.org/publicdomain/zero/1.0/>. */ // original documentation by Vigna: /* This is a fixed-increment version of Java 8's SplittableRandom generator See http://dx.doi.org/10.1145/2714064.2660195 and http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html It is a very fast generator passing BigCrush, and it can be useful if for some reason you absolutely want 64 bits of state; otherwise, we rather suggest to use a xoroshiro128+ (for moderately parallel computations) or xorshift1024* (for massively parallel computations) generator. */ // state for splitmix64 uint64_t state; /* The state can be seeded with any value. */ #pragma omp threadprivate(state) // call this one before calling splitmix64 static inline void seed(uint64_t seed) { state = seed; } static inline uint64_t genSeed(int threadID) { state = MERGE(std::chrono::high_resolution_clock::now().time_since_epoch().count(), threadID + 1); return state; } // returns random number, modifies splitmix64_x // compared with D. Lemire against // http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/SplittableRandom.java#SplittableRandom.0gamma static inline uint64_t next_r(uint64_t *seed) { uint64_t z = (*seed += UINT64_C(0x9E3779B97F4A7C15)); z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9); z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB); return z ^ (z >> 31); } // same as splitmix64, but does not change the state, designed by D. Lemire static inline uint64_t next() { return next_r(&state); } static inline uint32_t next32() { return (uint32_t)next_r(&state); } } // namespace SplitMix64 namespace WyRand { // adapted to this project by D. Lemire, from https://github.com/wangyi-fudan/wyhash/blob/master/wyhash.h // This uses mum hashing. // state for wyrand uint64_t state; /* The state can be seeded with any value. */ #pragma omp threadprivate(state) // call wyrand_seed before calling wyrand static inline void seed(uint64_t seed) { state = seed; } static inline uint64_t genSeed(int threadID) { state = MERGE(std::chrono::high_resolution_clock::now().time_since_epoch().count(), threadID + 1); return state; } static inline uint64_t next_r(uint64_t *s) { *s += UINT64_C(0xa0761d6478bd642f); __uint128_t t = (__uint128_t)*s * (*s ^ UINT64_C(0xe7037ed1a0b428db)); return (t >> 64) ^ t; } // returns random number, modifies state static inline uint64_t next() { return next_r(&state); } static inline uint32_t next32() { return (uint32_t)next_r(&state); } } // namespace WyRand namespace WyHash { // adapted to this project by D. Lemire, from https://github.com/wangyi-fudan/wyhash/blob/master/wyhash.h // This uses mum hashing. // state for wyrand // state for wyhash64 uint64_t state; /* The state can be seeded with any value. */ #pragma omp threadprivate(state) // call wyhash64_seed before calling wyhash64 static inline void seed(uint64_t seed) { state = seed; } static inline uint64_t genSeed(int threadID) { state = MERGE(std::chrono::high_resolution_clock::now().time_since_epoch().count(), threadID + 1); return state; } static inline uint64_t next_r(uint64_t *seed) { *seed += UINT64_C(0x60bee2bee120fc15); __uint128_t tmp; tmp = (__uint128_t)*seed * UINT64_C(0xa3b195354a39b70d); uint64_t m1 = (tmp >> 64) ^ tmp; tmp = (__uint128_t)m1 * UINT64_C(0x1b03738712fad5c9); uint64_t m2 = (tmp >> 64) ^ tmp; return m2; } // returns random number, modifies state static inline uint64_t next() { return next_r(&state); } static inline uint32_t next32() { return (uint32_t)next_r(&state); } } // namespace WyHash namespace Xoroshiro128P { // original documentation by Vigna: /* This is the successor to xorshift128+. It is the fastest full-period generator passing BigCrush without systematic failures, but due to the relatively short period it is acceptable only for applications with a mild amount of parallelism; otherwise, use a xorshift1024* generator. Beside passing BigCrush, this generator passes the PractRand test suite up to (and included) 16TB, with the exception of binary rank tests, which fail due to the lowest bit being an LFSR; all other bits pass all tests. We suggest to use a sign test to extract a random Boolean value. Note that the generator uses a simulated rotate operation, which most C compilers will turn into a single instruction. In Java, you can use Long.rotateLeft(). In languages that do not make low-level rotation instructions accessible xorshift128+ could be faster. The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we suggest to seed a splitmix64 generator and use its output to fill s. */ // state for xoroshiro128plus uint64_t state[2]; #pragma omp threadprivate(state) static inline uint64_t rotl(const uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } // call this one before calling xoroshiro128plus static inline void seed(uint64_t seed) { state[0] = SplitMix64::next_r(&seed); state[1] = SplitMix64::next_r(&seed); } static inline uint64_t genSeed(int threadID) { seed(MERGE(std::chrono::high_resolution_clock::now().time_since_epoch().count(), threadID + 1)); return state[0]; } // returns random number, modifies xoroshiro128plus_s static inline uint64_t next_r(uint64_t seed[2]) { const uint64_t s0 = seed[0]; uint64_t s1 = seed[1]; const uint64_t result = s0 + s1; s1 ^= s0; seed[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b seed[1] = rotl(s1, 36); // c return result; } static inline uint64_t next() { return next_r(state); } static inline uint32_t next32() { return (uint32_t)next_r(state); } } // namespace Xoroshiro128P namespace Xoroshiro128PP { static inline uint32_t rotl(const uint32_t x, int k) { return (x << k) | (x >> (32 - k)); } uint32_t state[4]; #pragma omp threadprivate(state) static inline void seed(uint64_t seed) { state[0] = SplitMix64::next_r(&seed); state[1] = SplitMix64::next_r(&seed); state[2] = SplitMix64::next_r(&seed); state[3] = SplitMix64::next_r(&seed); } static inline uint64_t genSeed(int threadID) { seed(MERGE(std::chrono::high_resolution_clock::now().time_since_epoch().count(), threadID + 1)); return state[0]; } uint32_t next_r(uint32_t seed[4]) { const uint32_t result = rotl(seed[0] + seed[3], 7) + seed[0]; const uint32_t t = seed[1] << 9; seed[2] ^= seed[0]; seed[3] ^= seed[1]; seed[1] ^= seed[2]; seed[0] ^= seed[3]; seed[2] ^= t; seed[3] = rotl(seed[3], 11); return result; } uint32_t next() { return next_r(state); } } // namespace Xoroshiro128PP namespace GMS::FastStatistics { /** * Provides STL compatible RNG over WyRand. */ class WyRandRng { private: uint64_t state; public: using result_type = uint64_t; constexpr result_type min() { return 0; } constexpr result_type max() { return std::numeric_limits<result_type>::max(); } WyRandRng(int threadId) { state = WyRand::genSeed(threadId); } result_type operator()() { return WyRand::next_r(&state); } }; /** * Provides STL compatible RNG over Xoroshiro128PP. */ class Xoroshiro128PPRng { private: uint32_t state[4]; public: using result_type = uint32_t; constexpr result_type min() { return 0; } constexpr result_type max() { return std::numeric_limits<result_type>::max(); } Xoroshiro128PPRng(int threadId) { Xoroshiro128PP::genSeed(threadId); for (int i = 0; i < 4; ++i) { state[i] = Xoroshiro128PP::state[i]; } } result_type operator()() { return Xoroshiro128PP::next_r(state); } }; } #endif
slow_flow_calculator_cython.c
/* Generated by Cython 0.25.2 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [], "extra_compile_args": [ "-fopenmp" ], "extra_link_args": [ "-fopenmp" ] }, "module_name": "triplet_flow_loss.slow_flow_calculator_cython" } END: Cython Metadata */ #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 < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_25_2" #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && 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_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #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 #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_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 #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_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 #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 #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_FASTCALL #define METH_FASTCALL 0x80 typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #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))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_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 #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_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 #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !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 #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #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 typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #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) #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 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; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__triplet_flow_loss__slow_flow_calculator_cython #define __PYX_HAVE_API__triplet_flow_loss__slow_flow_calculator_cython #include <string.h> #include <stdio.h> #include <stdlib.h> #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include <math.h> #include "pythread.h" #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif 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))) ) #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) && defined (_M_X64) #define __Pyx_sst_abs(value) _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 char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_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)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static 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[] = { "triplet_flow_loss/slow_flow_calculator_cython.pyx", "__init__.pxd", "triplet_flow_loss/stringsource", "type.pxd", }; /* 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; /* 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; /* 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 /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 * # 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 * * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":727 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":728 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 * #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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 * * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":734 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":735 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":739 * #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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":740 * * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 * # 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":750 * # 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":754 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":757 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":761 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 * 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 ---*/ struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":765 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 * 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":103 * * @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":275 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":326 * * @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":951 * * @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":103 * * @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":326 * * @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":951 * * @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) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* 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 */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /* 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 CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* 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 /* 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); /* 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 #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 /* 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); /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFormatCheck.proto */ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); 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); // PROTO /* 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); /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #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); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(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 /* 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) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* 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); /* 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 */ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, 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 /* 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 *); /* 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)); /* 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); 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); /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* 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; /* None.proto */ static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* 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); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* MemviewDtypeToObject.proto */ static CYTHON_INLINE PyObject *__pyx_memview_get_float(const char *itemp); static CYTHON_INLINE int __pyx_memview_set_float(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 char __Pyx_PyInt_As_char(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* 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_dsdsds_float(PyObject *); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_int(PyObject *); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* 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 '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 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'libc.math' */ /* Module declarations from 'triplet_flow_loss.slow_flow_calculator_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 PyObject *__pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow_helper(PyArrayObject *, PyArrayObject *, PyArrayObject *, int, PyArrayObject *, PyArrayObject *, int); /*proto*/ static void __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_set_flow_at_point(int, int, float, float, __Pyx_memviewslice); /*proto*/ static CYTHON_INLINE float __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int, int, int); /*proto*/ static CYTHON_INLINE int __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_max_int(int, int); /*proto*/ static CYTHON_INLINE int __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_min_int(int, int); /*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 __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t = { "float32_t", NULL, sizeof(__pyx_t_5numpy_float32_t), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 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 }; #define __Pyx_MODULE_NAME "triplet_flow_loss.slow_flow_calculator_cython" int __pyx_module_is_main_triplet_flow_loss__slow_flow_calculator_cython = 0; /* Implementation of 'triplet_flow_loss.slow_flow_calculator_cython' */ static PyObject *__pyx_builtin_range; 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_Ellipsis; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static const char __pyx_k_O[] = "O"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_id[] = "id"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_obj[] = "obj"; static const char __pyx_k_base[] = "base"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mask[] = "mask"; static const char __pyx_k_math[] = "math"; 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_class[] = "__class__"; static const char __pyx_k_dtype[] = "dtype"; 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_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_astype[] = "astype"; 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_struct[] = "struct"; static const char __pyx_k_unpack[] = "unpack"; static const char __pyx_k_asarray[] = "asarray"; static const char __pyx_k_float32[] = "float32"; 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_itemsize[] = "itemsize"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_IndexError[] = "IndexError"; static const char __pyx_k_ValueError[] = "ValueError"; 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_array_equal[] = "array_equal"; static const char __pyx_k_interpolate[] = "interpolate"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_compute_flow[] = "compute_flow"; static const char __pyx_k_left_features[] = "left_features"; static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static const char __pyx_k_initialization[] = "initialization"; static const char __pyx_k_right_features[] = "right_features"; 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_feature_error_arr[] = "feature_error_arr"; static const char __pyx_k_interpolate_after[] = "interpolate_after"; 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_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_contiguous_and_indirect[] = "<contiguous and indirect>"; static const char __pyx_k_neighborhood_len_import[] = "neighborhood_len_import"; 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_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_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static const char __pyx_k_home_davidm_DA_RNN_DA_RNN_lib_t[] = "/home/davidm/DA-RNN/DA-RNN/lib/triplet_flow_loss/slow_flow_calculator_cython.pyx"; 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_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_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_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_triplet_flow_loss_slow_flow_calc[] = "triplet_flow_loss.slow_flow_calculator_cython"; 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_index_with_type_s; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_n_s_IndexError; static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; static PyObject *__pyx_kp_s_MemoryView_of_r_object; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_array_equal; static PyObject *__pyx_n_s_asarray; static PyObject *__pyx_n_s_astype; 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_compute_flow; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_feature_error_arr; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_float32; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; static PyObject *__pyx_kp_s_home_davidm_DA_RNN_DA_RNN_lib_t; static PyObject *__pyx_n_s_id; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_initialization; static PyObject *__pyx_n_s_int32; static PyObject *__pyx_n_s_interpolate; static PyObject *__pyx_n_s_interpolate_after; static PyObject *__pyx_n_s_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_left_features; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mask; static PyObject *__pyx_n_s_math; static PyObject *__pyx_n_s_memview; 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_neighborhood_len_import; 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_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_right_features; 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_n_s_struct; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_triplet_flow_loss_slow_flow_calc; 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_zeros; static PyObject *__pyx_pf_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_left_features, PyObject *__pyx_v_right_features, PyObject *__pyx_v_mask, PyObject *__pyx_v_initialization, PyObject *__pyx_v_neighborhood_len_import, PyObject *__pyx_v_interpolate_after); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_2; static PyObject *__pyx_int_6; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_slice_; static PyObject *__pyx_slice__2; static PyObject *__pyx_slice__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_slice__23; static PyObject *__pyx_slice__24; 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__25; static PyObject *__pyx_tuple__26; 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__27; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":14 * * * def compute_flow(left_features, right_features, mask, initialization, neighborhood_len_import=6, interpolate_after=False): # <<<<<<<<<<<<<< * """ * Calculate optical flow using a nearest neighbor search. */ /* Python wrapper */ static PyObject *__pyx_pw_17triplet_flow_loss_27slow_flow_calculator_cython_1compute_flow(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow[] = "\n Calculate optical flow using a nearest neighbor search.\n :param left_features: Feature array from the first image\n :param right_features: Feature array from the second image\n :param mask: An integer array of points to not compute flow from or to. Setting a pixel 0 marks it as valid.\n :param initialization: An approximate optical flow array to use as a guide.\n :param neighborhood_len_import: The distance away from each pixel to search. This is a diameter, not a radius\n :param interpolate_after: Do sub-pixel interpolation?\n :return: An optical flow array and an array containing the distance between each pixel and it's corresponding pixel.\n "; static PyMethodDef __pyx_mdef_17triplet_flow_loss_27slow_flow_calculator_cython_1compute_flow = {"compute_flow", (PyCFunction)__pyx_pw_17triplet_flow_loss_27slow_flow_calculator_cython_1compute_flow, METH_VARARGS|METH_KEYWORDS, __pyx_doc_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow}; static PyObject *__pyx_pw_17triplet_flow_loss_27slow_flow_calculator_cython_1compute_flow(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_left_features = 0; PyObject *__pyx_v_right_features = 0; PyObject *__pyx_v_mask = 0; PyObject *__pyx_v_initialization = 0; PyObject *__pyx_v_neighborhood_len_import = 0; PyObject *__pyx_v_interpolate_after = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("compute_flow (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_left_features,&__pyx_n_s_right_features,&__pyx_n_s_mask,&__pyx_n_s_initialization,&__pyx_n_s_neighborhood_len_import,&__pyx_n_s_interpolate_after,0}; PyObject* values[6] = {0,0,0,0,0,0}; values[4] = ((PyObject *)__pyx_int_6); values[5] = ((PyObject *)Py_False); 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); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_left_features)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_right_features)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_flow", 0, 4, 6, 1); __PYX_ERR(0, 14, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_flow", 0, 4, 6, 2); __PYX_ERR(0, 14, __pyx_L3_error) } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_initialization)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_flow", 0, 4, 6, 3); __PYX_ERR(0, 14, __pyx_L3_error) } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_neighborhood_len_import); if (value) { values[4] = value; kw_args--; } } case 5: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_interpolate_after); if (value) { values[5] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_flow") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); 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_left_features = values[0]; __pyx_v_right_features = values[1]; __pyx_v_mask = values[2]; __pyx_v_initialization = values[3]; __pyx_v_neighborhood_len_import = values[4]; __pyx_v_interpolate_after = values[5]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("compute_flow", 0, 4, 6, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("triplet_flow_loss.slow_flow_calculator_cython.compute_flow", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow(__pyx_self, __pyx_v_left_features, __pyx_v_right_features, __pyx_v_mask, __pyx_v_initialization, __pyx_v_neighborhood_len_import, __pyx_v_interpolate_after); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_left_features, PyObject *__pyx_v_right_features, PyObject *__pyx_v_mask, PyObject *__pyx_v_initialization, PyObject *__pyx_v_neighborhood_len_import, PyObject *__pyx_v_interpolate_after) { long __pyx_v_interpolate; PyObject *__pyx_v_feature_error_arr = NULL; 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; PyObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; __Pyx_RefNannySetupContext("compute_flow", 0); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":25 * :return: An optical flow array and an array containing the distance between each pixel and it's corresponding pixel. * """ * if interpolate_after: # <<<<<<<<<<<<<< * interpolate = 1 * else: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_interpolate_after); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 25, __pyx_L1_error) if (__pyx_t_1) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":26 * """ * if interpolate_after: * interpolate = 1 # <<<<<<<<<<<<<< * else: * interpolate = 0 */ __pyx_v_interpolate = 1; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":25 * :return: An optical flow array and an array containing the distance between each pixel and it's corresponding pixel. * """ * if interpolate_after: # <<<<<<<<<<<<<< * interpolate = 1 * else: */ goto __pyx_L3; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":28 * interpolate = 1 * else: * interpolate = 0 # <<<<<<<<<<<<<< * feature_error_arr = np.zeros([left_features.shape[0], left_features.shape[1]], dtype=np.float32) * assert np.array_equal(left_features.shape[:2], mask.shape) */ /*else*/ { __pyx_v_interpolate = 0; } __pyx_L3:; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":29 * else: * interpolate = 0 * feature_error_arr = np.zeros([left_features.shape[0], left_features.shape[1]], dtype=np.float32) # <<<<<<<<<<<<<< * assert np.array_equal(left_features.shape[:2], mask.shape) * assert np.array_equal(left_features.shape, right_features.shape) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __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, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyList_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_4); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float32); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_6) < 0) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_feature_error_arr = __pyx_t_6; __pyx_t_6 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":30 * interpolate = 0 * feature_error_arr = np.zeros([left_features.shape[0], left_features.shape[1]], dtype=np.float32) * assert np.array_equal(left_features.shape[:2], mask.shape) # <<<<<<<<<<<<<< * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array_equal); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, 2, NULL, NULL, &__pyx_slice_, 0, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_mask, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_5))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); __pyx_t_7 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_t_3, __pyx_t_2}; __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_t_3, __pyx_t_2}; __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_4) { __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); __pyx_t_4 = NULL; } __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_t_2); __pyx_t_3 = 0; __pyx_t_2 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_8, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 30, __pyx_L1_error) } } #endif /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":31 * feature_error_arr = np.zeros([left_features.shape[0], left_features.shape[1]], dtype=np.float32) * assert np.array_equal(left_features.shape[:2], mask.shape) * assert np.array_equal(left_features.shape, right_features.shape) # <<<<<<<<<<<<<< * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_array_equal); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_right_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_8))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_8, function); __pyx_t_7 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_8)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_5, __pyx_t_2}; __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_8)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_5, __pyx_t_2}; __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_4 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (__pyx_t_3) { __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; } __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_7, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_7, __pyx_t_2); __pyx_t_5 = 0; __pyx_t_2 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_4, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 31, __pyx_L1_error) } } #endif /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":32 * assert np.array_equal(left_features.shape[:2], mask.shape) * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) # <<<<<<<<<<<<<< * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), * neighborhood_len_import, initialization.astype(np.float32), feature_error_arr, interpolate) */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_array_equal); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_shape); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_8, 0, 2, NULL, NULL, &__pyx_slice__2, 0, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_initialization, __pyx_n_s_shape); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_t_5 = __Pyx_PyObject_GetSlice(__pyx_t_8, 0, 2, NULL, NULL, &__pyx_slice__3, 0, 1, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_8)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_8); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); __pyx_t_7 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_t_2, __pyx_t_5}; __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_t_2, __pyx_t_5}; __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif { __pyx_t_3 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__pyx_t_8) { __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); __pyx_t_8 = NULL; } __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_7, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_7, __pyx_t_5); __pyx_t_2 = 0; __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 32, __pyx_L1_error) } } #endif /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":33 * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), # <<<<<<<<<<<<<< * neighborhood_len_import, initialization.astype(np.float32), feature_error_arr, interpolate) * */ __Pyx_XDECREF(__pyx_r); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_left_features, __pyx_n_s_astype); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_float32); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } if (!__pyx_t_3) { __pyx_t_6 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_6); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_5}; __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_5}; __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif { __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_2, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 33, __pyx_L1_error) __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_right_features, __pyx_n_s_astype); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float32); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && likely(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); } } if (!__pyx_t_5) { __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_4); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif { __pyx_t_8 = PyTuple_New(1+1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_8, 0+1, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 33, __pyx_L1_error) __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_mask, __pyx_n_s_astype); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_8); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_8, function); } } if (!__pyx_t_3) { __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_2); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_8)) { PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_5}; __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_8, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_8)) { PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_5}; __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_8, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif { __pyx_t_9 = PyTuple_New(1+1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 33, __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 = NULL; __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_9, 0+1, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_9, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 33, __pyx_L1_error) /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":34 * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), * neighborhood_len_import, initialization.astype(np.float32), feature_error_arr, interpolate) # <<<<<<<<<<<<<< * * */ __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_v_neighborhood_len_import); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 34, __pyx_L1_error) __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_initialization, __pyx_n_s_astype); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float32); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_9))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_9); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_9, function); } } if (!__pyx_t_5) { __pyx_t_8 = __Pyx_PyObject_CallOneArg(__pyx_t_9, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_8); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_8 = __Pyx_PyFunction_FastCall(__pyx_t_9, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_8 = __Pyx_PyCFunction_FastCall(__pyx_t_9, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif { __pyx_t_10 = PyTuple_New(1+1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); __pyx_t_5 = NULL; __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_10, 0+1, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_10, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; } } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 34, __pyx_L1_error) if (!(likely(((__pyx_v_feature_error_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_feature_error_arr, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 34, __pyx_L1_error) /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":33 * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), # <<<<<<<<<<<<<< * neighborhood_len_import, initialization.astype(np.float32), feature_error_arr, interpolate) * */ __pyx_t_9 = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow_helper(((PyArrayObject *)__pyx_t_6), ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_t_2), __pyx_t_7, ((PyArrayObject *)__pyx_t_8), ((PyArrayObject *)__pyx_v_feature_error_arr), __pyx_v_interpolate); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_r = __pyx_t_9; __pyx_t_9 = 0; goto __pyx_L0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":14 * * * def compute_flow(left_features, right_features, mask, initialization, neighborhood_len_import=6, interpolate_after=False): # <<<<<<<<<<<<<< * """ * Calculate optical flow using a nearest neighbor search. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("triplet_flow_loss.slow_flow_calculator_cython.compute_flow", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_feature_error_arr); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":40 * @cython.wraparound(False) * @cython.cdivision(True) * cdef compute_flow_helper(np.ndarray[np.float32_t, ndim=3] left_features_obj, # <<<<<<<<<<<<<< * np.ndarray[np.float32_t, ndim=3] right_features_obj, np.ndarray[np.int32_t, ndim=2] mask_obj, * int neighborhood_len_import, np.ndarray[np.float32_t, ndim=3] flow_arr_obj, */ static PyObject *__pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_compute_flow_helper(PyArrayObject *__pyx_v_left_features_obj, PyArrayObject *__pyx_v_right_features_obj, PyArrayObject *__pyx_v_mask_obj, int __pyx_v_neighborhood_len_import, PyArrayObject *__pyx_v_flow_arr_obj, PyArrayObject *__pyx_v_feature_error_obj, int __pyx_v_interpolate_after) { int __pyx_v_start_a; int __pyx_v_stop_a; int __pyx_v_start_b; int __pyx_v_stop_b; int __pyx_v_left_len_0; int __pyx_v_left_len_1; int __pyx_v_right_len_0; int __pyx_v_right_len_1; int __pyx_v_feature_depth; int __pyx_v_neighborhood_len; __Pyx_memviewslice __pyx_v_left_features = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_right_features = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_flow_arr = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_mask = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_feature_errors = { 0, 0, { 0 }, { 0 }, { 0 } }; float __pyx_v_current_dist; float __pyx_v_best_dist; float __pyx_v_best_index_u; float __pyx_v_best_index_v; int __pyx_v_i; int __pyx_v_j; int __pyx_v_a; int __pyx_v_b; int __pyx_v_initial_i; int __pyx_v_initial_j; int __pyx_v_u1; int __pyx_v_u2; int __pyx_v_v1; int __pyx_v_v2; float __pyx_v_dist1; float __pyx_v_dist2; __Pyx_LocalBuf_ND __pyx_pybuffernd_feature_error_obj; __Pyx_Buffer __pyx_pybuffer_feature_error_obj; __Pyx_LocalBuf_ND __pyx_pybuffernd_flow_arr_obj; __Pyx_Buffer __pyx_pybuffer_flow_arr_obj; __Pyx_LocalBuf_ND __pyx_pybuffernd_left_features_obj; __Pyx_Buffer __pyx_pybuffer_left_features_obj; __Pyx_LocalBuf_ND __pyx_pybuffernd_mask_obj; __Pyx_Buffer __pyx_pybuffer_mask_obj; __Pyx_LocalBuf_ND __pyx_pybuffernd_right_features_obj; __Pyx_Buffer __pyx_pybuffer_right_features_obj; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_2 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_3 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_4; long __pyx_t_5; long __pyx_t_6; int __pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; Py_ssize_t __pyx_t_10; int __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_t_18; int __pyx_t_19; int __pyx_t_20; int __pyx_t_21; int __pyx_t_22; Py_ssize_t __pyx_t_23; Py_ssize_t __pyx_t_24; PyObject *__pyx_t_25 = NULL; PyObject *__pyx_t_26 = NULL; PyObject *__pyx_t_27 = NULL; PyObject *__pyx_t_28 = NULL; PyObject *__pyx_t_29 = NULL; PyObject *__pyx_t_30 = NULL; __Pyx_RefNannySetupContext("compute_flow_helper", 0); __pyx_pybuffer_left_features_obj.pybuffer.buf = NULL; __pyx_pybuffer_left_features_obj.refcount = 0; __pyx_pybuffernd_left_features_obj.data = NULL; __pyx_pybuffernd_left_features_obj.rcbuffer = &__pyx_pybuffer_left_features_obj; __pyx_pybuffer_right_features_obj.pybuffer.buf = NULL; __pyx_pybuffer_right_features_obj.refcount = 0; __pyx_pybuffernd_right_features_obj.data = NULL; __pyx_pybuffernd_right_features_obj.rcbuffer = &__pyx_pybuffer_right_features_obj; __pyx_pybuffer_mask_obj.pybuffer.buf = NULL; __pyx_pybuffer_mask_obj.refcount = 0; __pyx_pybuffernd_mask_obj.data = NULL; __pyx_pybuffernd_mask_obj.rcbuffer = &__pyx_pybuffer_mask_obj; __pyx_pybuffer_flow_arr_obj.pybuffer.buf = NULL; __pyx_pybuffer_flow_arr_obj.refcount = 0; __pyx_pybuffernd_flow_arr_obj.data = NULL; __pyx_pybuffernd_flow_arr_obj.rcbuffer = &__pyx_pybuffer_flow_arr_obj; __pyx_pybuffer_feature_error_obj.pybuffer.buf = NULL; __pyx_pybuffer_feature_error_obj.refcount = 0; __pyx_pybuffernd_feature_error_obj.data = NULL; __pyx_pybuffernd_feature_error_obj.rcbuffer = &__pyx_pybuffer_feature_error_obj; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer, (PyObject*)__pyx_v_left_features_obj, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) __PYX_ERR(0, 40, __pyx_L1_error) } __pyx_pybuffernd_left_features_obj.diminfo[0].strides = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_left_features_obj.diminfo[0].shape = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_left_features_obj.diminfo[1].strides = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_left_features_obj.diminfo[1].shape = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_left_features_obj.diminfo[2].strides = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_left_features_obj.diminfo[2].shape = __pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer.shape[2]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer, (PyObject*)__pyx_v_right_features_obj, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) __PYX_ERR(0, 40, __pyx_L1_error) } __pyx_pybuffernd_right_features_obj.diminfo[0].strides = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_right_features_obj.diminfo[0].shape = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_right_features_obj.diminfo[1].strides = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_right_features_obj.diminfo[1].shape = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_right_features_obj.diminfo[2].strides = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_right_features_obj.diminfo[2].shape = __pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer.shape[2]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mask_obj.rcbuffer->pybuffer, (PyObject*)__pyx_v_mask_obj, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 40, __pyx_L1_error) } __pyx_pybuffernd_mask_obj.diminfo[0].strides = __pyx_pybuffernd_mask_obj.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mask_obj.diminfo[0].shape = __pyx_pybuffernd_mask_obj.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_mask_obj.diminfo[1].strides = __pyx_pybuffernd_mask_obj.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_mask_obj.diminfo[1].shape = __pyx_pybuffernd_mask_obj.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer, (PyObject*)__pyx_v_flow_arr_obj, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) __PYX_ERR(0, 40, __pyx_L1_error) } __pyx_pybuffernd_flow_arr_obj.diminfo[0].strides = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_flow_arr_obj.diminfo[0].shape = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_flow_arr_obj.diminfo[1].strides = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_flow_arr_obj.diminfo[1].shape = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_flow_arr_obj.diminfo[2].strides = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_flow_arr_obj.diminfo[2].shape = __pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer.shape[2]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer, (PyObject*)__pyx_v_feature_error_obj, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 40, __pyx_L1_error) } __pyx_pybuffernd_feature_error_obj.diminfo[0].strides = __pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_feature_error_obj.diminfo[0].shape = __pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_feature_error_obj.diminfo[1].strides = __pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_feature_error_obj.diminfo[1].shape = __pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer.shape[1]; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":51 * cdef int start_a, stop_a, start_b, stop_b * cdef int left_len_0, left_len_1, right_len_0, right_len_1, feature_depth, neighborhood_len * left_len_0 = <int> left_features_obj.shape[0] # <<<<<<<<<<<<<< * left_len_1 = <int> left_features_obj.shape[1] * right_len_0 = <int> right_features_obj.shape[0] */ __pyx_v_left_len_0 = ((int)(__pyx_v_left_features_obj->dimensions[0])); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":52 * cdef int left_len_0, left_len_1, right_len_0, right_len_1, feature_depth, neighborhood_len * left_len_0 = <int> left_features_obj.shape[0] * left_len_1 = <int> left_features_obj.shape[1] # <<<<<<<<<<<<<< * right_len_0 = <int> right_features_obj.shape[0] * right_len_1 = <int> right_features_obj.shape[1] */ __pyx_v_left_len_1 = ((int)(__pyx_v_left_features_obj->dimensions[1])); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":53 * left_len_0 = <int> left_features_obj.shape[0] * left_len_1 = <int> left_features_obj.shape[1] * right_len_0 = <int> right_features_obj.shape[0] # <<<<<<<<<<<<<< * right_len_1 = <int> right_features_obj.shape[1] * feature_depth = <int> left_features_obj.shape[2] */ __pyx_v_right_len_0 = ((int)(__pyx_v_right_features_obj->dimensions[0])); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":54 * left_len_1 = <int> left_features_obj.shape[1] * right_len_0 = <int> right_features_obj.shape[0] * right_len_1 = <int> right_features_obj.shape[1] # <<<<<<<<<<<<<< * feature_depth = <int> left_features_obj.shape[2] * neighborhood_len = <int> neighborhood_len_import */ __pyx_v_right_len_1 = ((int)(__pyx_v_right_features_obj->dimensions[1])); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":55 * right_len_0 = <int> right_features_obj.shape[0] * right_len_1 = <int> right_features_obj.shape[1] * feature_depth = <int> left_features_obj.shape[2] # <<<<<<<<<<<<<< * neighborhood_len = <int> neighborhood_len_import * */ __pyx_v_feature_depth = ((int)(__pyx_v_left_features_obj->dimensions[2])); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":56 * right_len_1 = <int> right_features_obj.shape[1] * feature_depth = <int> left_features_obj.shape[2] * neighborhood_len = <int> neighborhood_len_import # <<<<<<<<<<<<<< * * cdef float[:,:,:] left_features = left_features_obj */ __pyx_v_neighborhood_len = ((int)__pyx_v_neighborhood_len_import); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":58 * neighborhood_len = <int> neighborhood_len_import * * cdef float[:,:,:] left_features = left_features_obj # <<<<<<<<<<<<<< * cdef float[:,:,:] right_features = right_features_obj * cdef float[:,:,:] flow_arr = flow_arr_obj */ __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dsdsds_float(((PyObject *)__pyx_v_left_features_obj)); if (unlikely(!__pyx_t_1.memview)) __PYX_ERR(0, 58, __pyx_L1_error) __pyx_v_left_features = __pyx_t_1; __pyx_t_1.memview = NULL; __pyx_t_1.data = NULL; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":59 * * cdef float[:,:,:] left_features = left_features_obj * cdef float[:,:,:] right_features = right_features_obj # <<<<<<<<<<<<<< * cdef float[:,:,:] flow_arr = flow_arr_obj * cdef int[:,:] mask = mask_obj */ __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dsdsds_float(((PyObject *)__pyx_v_right_features_obj)); if (unlikely(!__pyx_t_1.memview)) __PYX_ERR(0, 59, __pyx_L1_error) __pyx_v_right_features = __pyx_t_1; __pyx_t_1.memview = NULL; __pyx_t_1.data = NULL; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":60 * cdef float[:,:,:] left_features = left_features_obj * cdef float[:,:,:] right_features = right_features_obj * cdef float[:,:,:] flow_arr = flow_arr_obj # <<<<<<<<<<<<<< * cdef int[:,:] mask = mask_obj * cdef float[:,:] feature_errors = feature_error_obj */ __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dsdsds_float(((PyObject *)__pyx_v_flow_arr_obj)); if (unlikely(!__pyx_t_1.memview)) __PYX_ERR(0, 60, __pyx_L1_error) __pyx_v_flow_arr = __pyx_t_1; __pyx_t_1.memview = NULL; __pyx_t_1.data = NULL; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":61 * cdef float[:,:,:] right_features = right_features_obj * cdef float[:,:,:] flow_arr = flow_arr_obj * cdef int[:,:] mask = mask_obj # <<<<<<<<<<<<<< * cdef float[:,:] feature_errors = feature_error_obj * */ __pyx_t_2 = __Pyx_PyObject_to_MemoryviewSlice_dsds_int(((PyObject *)__pyx_v_mask_obj)); if (unlikely(!__pyx_t_2.memview)) __PYX_ERR(0, 61, __pyx_L1_error) __pyx_v_mask = __pyx_t_2; __pyx_t_2.memview = NULL; __pyx_t_2.data = NULL; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":62 * cdef float[:,:,:] flow_arr = flow_arr_obj * cdef int[:,:] mask = mask_obj * cdef float[:,:] feature_errors = feature_error_obj # <<<<<<<<<<<<<< * * cdef float current_dist, best_dist, temp, temp2, best_index_u, best_index_v, best_a, best_b, x_average */ __pyx_t_3 = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(((PyObject *)__pyx_v_feature_error_obj)); if (unlikely(!__pyx_t_3.memview)) __PYX_ERR(0, 62, __pyx_L1_error) __pyx_v_feature_errors = __pyx_t_3; __pyx_t_3.memview = NULL; __pyx_t_3.data = NULL; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":72 * cdef int best_x, best_y * * for i in prange(0, left_len_0, nogil=True, schedule='dynamic', num_threads=20): # <<<<<<<<<<<<<< * # for i in range(left_len_0): * for j in range(0, left_len_1): */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { __pyx_t_4 = __pyx_v_left_len_0; 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_6 = (__pyx_t_4 - 0 + 1 - 1/abs(1)) / 1; if (__pyx_t_6 > 0) { #ifdef _OPENMP #pragma omp parallel num_threads(20) 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_7, __pyx_t_8, __pyx_t_9) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_a) lastprivate(__pyx_v_b) lastprivate(__pyx_v_best_dist) lastprivate(__pyx_v_best_index_u) lastprivate(__pyx_v_best_index_v) lastprivate(__pyx_v_current_dist) lastprivate(__pyx_v_dist1) lastprivate(__pyx_v_dist2) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_initial_i) lastprivate(__pyx_v_initial_j) lastprivate(__pyx_v_j) lastprivate(__pyx_v_start_a) lastprivate(__pyx_v_start_b) lastprivate(__pyx_v_stop_a) lastprivate(__pyx_v_stop_b) lastprivate(__pyx_v_u1) lastprivate(__pyx_v_u2) lastprivate(__pyx_v_v1) lastprivate(__pyx_v_v2) schedule(dynamic) #endif /* _OPENMP */ for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_6; __pyx_t_5++){ { __pyx_v_i = (int)(0 + 1 * __pyx_t_5); /* Initialize private variables to invalid values */ __pyx_v_a = ((int)0xbad0bad0); __pyx_v_b = ((int)0xbad0bad0); __pyx_v_best_dist = ((float)__PYX_NAN()); __pyx_v_best_index_u = ((float)__PYX_NAN()); __pyx_v_best_index_v = ((float)__PYX_NAN()); __pyx_v_current_dist = ((float)__PYX_NAN()); __pyx_v_dist1 = ((float)__PYX_NAN()); __pyx_v_dist2 = ((float)__PYX_NAN()); __pyx_v_initial_i = ((int)0xbad0bad0); __pyx_v_initial_j = ((int)0xbad0bad0); __pyx_v_j = ((int)0xbad0bad0); __pyx_v_start_a = ((int)0xbad0bad0); __pyx_v_start_b = ((int)0xbad0bad0); __pyx_v_stop_a = ((int)0xbad0bad0); __pyx_v_stop_b = ((int)0xbad0bad0); __pyx_v_u1 = ((int)0xbad0bad0); __pyx_v_u2 = ((int)0xbad0bad0); __pyx_v_v1 = ((int)0xbad0bad0); __pyx_v_v2 = ((int)0xbad0bad0); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":74 * for i in prange(0, left_len_0, nogil=True, schedule='dynamic', num_threads=20): * # for i in range(left_len_0): * for j in range(0, left_len_1): # <<<<<<<<<<<<<< * if mask[i, j] != 0: * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) */ __pyx_t_7 = __pyx_v_left_len_1; for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { __pyx_v_j = __pyx_t_8; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":75 * # for i in range(left_len_0): * for j in range(0, left_len_1): * if mask[i, j] != 0: # <<<<<<<<<<<<<< * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) * else: */ __pyx_t_9 = __pyx_v_i; __pyx_t_10 = __pyx_v_j; __pyx_t_11 = (((*((int *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_mask.data + __pyx_t_9 * __pyx_v_mask.strides[0]) ) + __pyx_t_10 * __pyx_v_mask.strides[1]) ))) != 0) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":76 * for j in range(0, left_len_1): * if mask[i, j] != 0: * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) # <<<<<<<<<<<<<< * else: * best_index_u = i */ __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_set_flow_at_point(__pyx_v_i, __pyx_v_j, 0.0, 0.0, __pyx_v_flow_arr); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":75 * # for i in range(left_len_0): * for j in range(0, left_len_1): * if mask[i, j] != 0: # <<<<<<<<<<<<<< * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) * else: */ goto __pyx_L12; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":78 * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) * else: * best_index_u = i # <<<<<<<<<<<<<< * best_index_v = j * */ /*else*/ { __pyx_v_best_index_u = __pyx_v_i; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":79 * else: * best_index_u = i * best_index_v = j # <<<<<<<<<<<<<< * * # set the starting distance to no be no movement. Otherwise the default will be large */ __pyx_v_best_index_v = __pyx_v_j; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":82 * * # set the starting distance to no be no movement. Otherwise the default will be large * current_dist = 10**5 # just a really big number # <<<<<<<<<<<<<< * * initial_i = <int> flow_arr[i, j, 1] + i */ __pyx_v_current_dist = 100000.0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":84 * current_dist = 10**5 # just a really big number * * initial_i = <int> flow_arr[i, j, 1] + i # <<<<<<<<<<<<<< * initial_j = <int> flow_arr[i, j, 0] + j * current_dist = dist(left_features, right_features, i, j, initial_i, initial_j, feature_depth) */ __pyx_t_12 = __pyx_v_i; __pyx_t_13 = __pyx_v_j; __pyx_t_14 = 1; __pyx_v_initial_i = (((int)(*((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_flow_arr.data + __pyx_t_12 * __pyx_v_flow_arr.strides[0]) ) + __pyx_t_13 * __pyx_v_flow_arr.strides[1]) ) + __pyx_t_14 * __pyx_v_flow_arr.strides[2]) )))) + __pyx_v_i); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":85 * * initial_i = <int> flow_arr[i, j, 1] + i * initial_j = <int> flow_arr[i, j, 0] + j # <<<<<<<<<<<<<< * current_dist = dist(left_features, right_features, i, j, initial_i, initial_j, feature_depth) * best_dist = current_dist */ __pyx_t_15 = __pyx_v_i; __pyx_t_16 = __pyx_v_j; __pyx_t_17 = 0; __pyx_v_initial_j = (((int)(*((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_flow_arr.data + __pyx_t_15 * __pyx_v_flow_arr.strides[0]) ) + __pyx_t_16 * __pyx_v_flow_arr.strides[1]) ) + __pyx_t_17 * __pyx_v_flow_arr.strides[2]) )))) + __pyx_v_j); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":86 * initial_i = <int> flow_arr[i, j, 1] + i * initial_j = <int> flow_arr[i, j, 0] + j * current_dist = dist(left_features, right_features, i, j, initial_i, initial_j, feature_depth) # <<<<<<<<<<<<<< * best_dist = current_dist * */ __pyx_v_current_dist = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, __pyx_v_initial_i, __pyx_v_initial_j, __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":87 * initial_j = <int> flow_arr[i, j, 0] + j * current_dist = dist(left_features, right_features, i, j, initial_i, initial_j, feature_depth) * best_dist = current_dist # <<<<<<<<<<<<<< * * start_a = max_int(0, initial_i - neighborhood_len/2) */ __pyx_v_best_dist = __pyx_v_current_dist; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":89 * best_dist = current_dist * * start_a = max_int(0, initial_i - neighborhood_len/2) # <<<<<<<<<<<<<< * stop_a = min_int(left_len_0, initial_i + (neighborhood_len - neighborhood_len/2)) * start_b = max_int(0, initial_j - neighborhood_len / 2) */ __pyx_v_start_a = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_max_int(0, (__pyx_v_initial_i - (__pyx_v_neighborhood_len / 2))); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":90 * * start_a = max_int(0, initial_i - neighborhood_len/2) * stop_a = min_int(left_len_0, initial_i + (neighborhood_len - neighborhood_len/2)) # <<<<<<<<<<<<<< * start_b = max_int(0, initial_j - neighborhood_len / 2) * stop_b = min_int(left_len_1, initial_j + (<int> neighborhood_len - <int> neighborhood_len / 2)) */ __pyx_v_stop_a = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_min_int(__pyx_v_left_len_0, (__pyx_v_initial_i + (__pyx_v_neighborhood_len - (__pyx_v_neighborhood_len / 2)))); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":91 * start_a = max_int(0, initial_i - neighborhood_len/2) * stop_a = min_int(left_len_0, initial_i + (neighborhood_len - neighborhood_len/2)) * start_b = max_int(0, initial_j - neighborhood_len / 2) # <<<<<<<<<<<<<< * stop_b = min_int(left_len_1, initial_j + (<int> neighborhood_len - <int> neighborhood_len / 2)) * for a in range(start_a, stop_a): */ __pyx_v_start_b = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_max_int(0, (__pyx_v_initial_j - (__pyx_v_neighborhood_len / 2))); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":92 * stop_a = min_int(left_len_0, initial_i + (neighborhood_len - neighborhood_len/2)) * start_b = max_int(0, initial_j - neighborhood_len / 2) * stop_b = min_int(left_len_1, initial_j + (<int> neighborhood_len - <int> neighborhood_len / 2)) # <<<<<<<<<<<<<< * for a in range(start_a, stop_a): * for b in range(start_b, stop_b): */ __pyx_v_stop_b = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_min_int(__pyx_v_left_len_1, (__pyx_v_initial_j + (((int)__pyx_v_neighborhood_len) - (((int)__pyx_v_neighborhood_len) / 2)))); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":93 * start_b = max_int(0, initial_j - neighborhood_len / 2) * stop_b = min_int(left_len_1, initial_j + (<int> neighborhood_len - <int> neighborhood_len / 2)) * for a in range(start_a, stop_a): # <<<<<<<<<<<<<< * for b in range(start_b, stop_b): * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) */ __pyx_t_18 = __pyx_v_stop_a; for (__pyx_t_19 = __pyx_v_start_a; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { __pyx_v_a = __pyx_t_19; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":94 * stop_b = min_int(left_len_1, initial_j + (<int> neighborhood_len - <int> neighborhood_len / 2)) * for a in range(start_a, stop_a): * for b in range(start_b, stop_b): # <<<<<<<<<<<<<< * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) * if current_dist < best_dist: */ __pyx_t_20 = __pyx_v_stop_b; for (__pyx_t_21 = __pyx_v_start_b; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { __pyx_v_b = __pyx_t_21; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":95 * for a in range(start_a, stop_a): * for b in range(start_b, stop_b): * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) # <<<<<<<<<<<<<< * if current_dist < best_dist: * best_dist = current_dist */ __pyx_v_current_dist = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, __pyx_v_a, __pyx_v_b, __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":96 * for b in range(start_b, stop_b): * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) * if current_dist < best_dist: # <<<<<<<<<<<<<< * best_dist = current_dist * best_index_u = a */ __pyx_t_11 = ((__pyx_v_current_dist < __pyx_v_best_dist) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":97 * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) * if current_dist < best_dist: * best_dist = current_dist # <<<<<<<<<<<<<< * best_index_u = a * best_index_v = b */ __pyx_v_best_dist = __pyx_v_current_dist; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":98 * if current_dist < best_dist: * best_dist = current_dist * best_index_u = a # <<<<<<<<<<<<<< * best_index_v = b * */ __pyx_v_best_index_u = __pyx_v_a; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":99 * best_dist = current_dist * best_index_u = a * best_index_v = b # <<<<<<<<<<<<<< * * if interpolate_after == 1 and best_index_u != -1: */ __pyx_v_best_index_v = __pyx_v_b; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":96 * for b in range(start_b, stop_b): * current_dist = dist(left_features, right_features, i, j, a, b, feature_depth) * if current_dist < best_dist: # <<<<<<<<<<<<<< * best_dist = current_dist * best_index_u = a */ } } } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":101 * best_index_v = b * * if interpolate_after == 1 and best_index_u != -1: # <<<<<<<<<<<<<< * u1 = <int> best_index_u - 1 * if u1 < 0: */ __pyx_t_22 = ((__pyx_v_interpolate_after == 1) != 0); if (__pyx_t_22) { } else { __pyx_t_11 = __pyx_t_22; goto __pyx_L19_bool_binop_done; } __pyx_t_22 = ((__pyx_v_best_index_u != -1.0) != 0); __pyx_t_11 = __pyx_t_22; __pyx_L19_bool_binop_done:; if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":102 * * if interpolate_after == 1 and best_index_u != -1: * u1 = <int> best_index_u - 1 # <<<<<<<<<<<<<< * if u1 < 0: * u1 = 0 */ __pyx_v_u1 = (((int)__pyx_v_best_index_u) - 1); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":103 * if interpolate_after == 1 and best_index_u != -1: * u1 = <int> best_index_u - 1 * if u1 < 0: # <<<<<<<<<<<<<< * u1 = 0 * if u1 >= right_len_0 - 3: */ __pyx_t_11 = ((__pyx_v_u1 < 0) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":104 * u1 = <int> best_index_u - 1 * if u1 < 0: * u1 = 0 # <<<<<<<<<<<<<< * if u1 >= right_len_0 - 3: * u1 = right_len_0 - 3 */ __pyx_v_u1 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":103 * if interpolate_after == 1 and best_index_u != -1: * u1 = <int> best_index_u - 1 * if u1 < 0: # <<<<<<<<<<<<<< * u1 = 0 * if u1 >= right_len_0 - 3: */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":105 * if u1 < 0: * u1 = 0 * if u1 >= right_len_0 - 3: # <<<<<<<<<<<<<< * u1 = right_len_0 - 3 * u2 = u1 + 2 */ __pyx_t_11 = ((__pyx_v_u1 >= (__pyx_v_right_len_0 - 3)) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":106 * u1 = 0 * if u1 >= right_len_0 - 3: * u1 = right_len_0 - 3 # <<<<<<<<<<<<<< * u2 = u1 + 2 * */ __pyx_v_u1 = (__pyx_v_right_len_0 - 3); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":105 * if u1 < 0: * u1 = 0 * if u1 >= right_len_0 - 3: # <<<<<<<<<<<<<< * u1 = right_len_0 - 3 * u2 = u1 + 2 */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":107 * if u1 >= right_len_0 - 3: * u1 = right_len_0 - 3 * u2 = u1 + 2 # <<<<<<<<<<<<<< * * dist1 = dist(left_features, right_features, i, j, u1, <int> best_index_v, feature_depth) */ __pyx_v_u2 = (__pyx_v_u1 + 2); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":109 * u2 = u1 + 2 * * dist1 = dist(left_features, right_features, i, j, u1, <int> best_index_v, feature_depth) # <<<<<<<<<<<<<< * dist2 = dist(left_features, right_features, i, j, u2, <int> best_index_v, feature_depth) * best_index_u = dist1 / (dist1 + dist2 + 0.00001) * u2 + dist2 / (dist1 + dist2 + 0.00001) * u1 */ __pyx_v_dist1 = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, __pyx_v_u1, ((int)__pyx_v_best_index_v), __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":110 * * dist1 = dist(left_features, right_features, i, j, u1, <int> best_index_v, feature_depth) * dist2 = dist(left_features, right_features, i, j, u2, <int> best_index_v, feature_depth) # <<<<<<<<<<<<<< * best_index_u = dist1 / (dist1 + dist2 + 0.00001) * u2 + dist2 / (dist1 + dist2 + 0.00001) * u1 * # if not (u1 <= best_index_u and u2 >= best_index_u): */ __pyx_v_dist2 = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, __pyx_v_u2, ((int)__pyx_v_best_index_v), __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":111 * dist1 = dist(left_features, right_features, i, j, u1, <int> best_index_v, feature_depth) * dist2 = dist(left_features, right_features, i, j, u2, <int> best_index_v, feature_depth) * best_index_u = dist1 / (dist1 + dist2 + 0.00001) * u2 + dist2 / (dist1 + dist2 + 0.00001) * u1 # <<<<<<<<<<<<<< * # if not (u1 <= best_index_u and u2 >= best_index_u): * # printf("i %3i, j, %3i, u1 %2i, u2 %2i, best_index_v %2.1f, dist1 %3.2f,\t dist2 %3.2f,\t best_index_u %3.1lf\n", i, j, u1, u2, best_index_v, dist1, dist2, best_index_u) */ __pyx_v_best_index_u = (((__pyx_v_dist1 / ((__pyx_v_dist1 + __pyx_v_dist2) + 0.00001)) * __pyx_v_u2) + ((__pyx_v_dist2 / ((__pyx_v_dist1 + __pyx_v_dist2) + 0.00001)) * __pyx_v_u1)); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":115 * # printf("i %3i, j, %3i, u1 %2i, u2 %2i, best_index_v %2.1f, dist1 %3.2f,\t dist2 %3.2f,\t best_index_u %3.1lf\n", i, j, u1, u2, best_index_v, dist1, dist2, best_index_u) * * v1 = <int> best_index_v - 1 # <<<<<<<<<<<<<< * if v1 < 0: * v1 = 0 */ __pyx_v_v1 = (((int)__pyx_v_best_index_v) - 1); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":116 * * v1 = <int> best_index_v - 1 * if v1 < 0: # <<<<<<<<<<<<<< * v1 = 0 * if v1 >= right_len_1 - 3: */ __pyx_t_11 = ((__pyx_v_v1 < 0) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":117 * v1 = <int> best_index_v - 1 * if v1 < 0: * v1 = 0 # <<<<<<<<<<<<<< * if v1 >= right_len_1 - 3: * v1 = right_len_1 - 3 */ __pyx_v_v1 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":116 * * v1 = <int> best_index_v - 1 * if v1 < 0: # <<<<<<<<<<<<<< * v1 = 0 * if v1 >= right_len_1 - 3: */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":118 * if v1 < 0: * v1 = 0 * if v1 >= right_len_1 - 3: # <<<<<<<<<<<<<< * v1 = right_len_1 - 3 * v2 = v1 + 2 */ __pyx_t_11 = ((__pyx_v_v1 >= (__pyx_v_right_len_1 - 3)) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":119 * v1 = 0 * if v1 >= right_len_1 - 3: * v1 = right_len_1 - 3 # <<<<<<<<<<<<<< * v2 = v1 + 2 * */ __pyx_v_v1 = (__pyx_v_right_len_1 - 3); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":118 * if v1 < 0: * v1 = 0 * if v1 >= right_len_1 - 3: # <<<<<<<<<<<<<< * v1 = right_len_1 - 3 * v2 = v1 + 2 */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":120 * if v1 >= right_len_1 - 3: * v1 = right_len_1 - 3 * v2 = v1 + 2 # <<<<<<<<<<<<<< * * dist1 = dist(left_features, right_features, i, j, <int> best_index_u, v1, feature_depth) */ __pyx_v_v2 = (__pyx_v_v1 + 2); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":122 * v2 = v1 + 2 * * dist1 = dist(left_features, right_features, i, j, <int> best_index_u, v1, feature_depth) # <<<<<<<<<<<<<< * dist2 = dist(left_features, right_features, i, j, <int> best_index_u, v2, feature_depth) * best_index_v = (dist1 + 0.00001) / (dist1 + dist2 + 0.00002) * v2 + (dist2 + 0.00001) / (dist1 + dist2 + 0.00002) * v1 */ __pyx_v_dist1 = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, ((int)__pyx_v_best_index_u), __pyx_v_v1, __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":123 * * dist1 = dist(left_features, right_features, i, j, <int> best_index_u, v1, feature_depth) * dist2 = dist(left_features, right_features, i, j, <int> best_index_u, v2, feature_depth) # <<<<<<<<<<<<<< * best_index_v = (dist1 + 0.00001) / (dist1 + dist2 + 0.00002) * v2 + (dist2 + 0.00001) / (dist1 + dist2 + 0.00002) * v1 * # if not (v1 <= best_index_v and v2 >= best_index_v): */ __pyx_v_dist2 = __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, ((int)__pyx_v_best_index_u), __pyx_v_v2, __pyx_v_feature_depth); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":124 * dist1 = dist(left_features, right_features, i, j, <int> best_index_u, v1, feature_depth) * dist2 = dist(left_features, right_features, i, j, <int> best_index_u, v2, feature_depth) * best_index_v = (dist1 + 0.00001) / (dist1 + dist2 + 0.00002) * v2 + (dist2 + 0.00001) / (dist1 + dist2 + 0.00002) * v1 # <<<<<<<<<<<<<< * # if not (v1 <= best_index_v and v2 >= best_index_v): * # printf("i %3i, j, %3i, v1 %2i, v2 %2i, best_index_u %2.1f, dist1 %3.2f,\t dist2 %3.2f,\t best_index_v %3.1lf\n", i, j, v1, v2, best_index_u, dist1, dist2, best_index_v) */ __pyx_v_best_index_v = ((((__pyx_v_dist1 + 0.00001) / ((__pyx_v_dist1 + __pyx_v_dist2) + 0.00002)) * __pyx_v_v2) + (((__pyx_v_dist2 + 0.00001) / ((__pyx_v_dist1 + __pyx_v_dist2) + 0.00002)) * __pyx_v_v1)); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":101 * best_index_v = b * * if interpolate_after == 1 and best_index_u != -1: # <<<<<<<<<<<<<< * u1 = <int> best_index_u - 1 * if u1 < 0: */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":128 * # printf("i %3i, j, %3i, v1 %2i, v2 %2i, best_index_u %2.1f, dist1 %3.2f,\t dist2 %3.2f,\t best_index_v %3.1lf\n", i, j, v1, v2, best_index_u, dist1, dist2, best_index_v) * * if best_index_u != -1: # <<<<<<<<<<<<<< * set_flow_at_point(i, j, best_index_v - j, best_index_u - i, flow_arr) * feature_errors[i, j] = <float> dist(left_features, right_features, i, j, <int> best_index_u, <int> best_index_v, feature_depth) */ __pyx_t_11 = ((__pyx_v_best_index_u != -1.0) != 0); if (__pyx_t_11) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":129 * * if best_index_u != -1: * set_flow_at_point(i, j, best_index_v - j, best_index_u - i, flow_arr) # <<<<<<<<<<<<<< * feature_errors[i, j] = <float> dist(left_features, right_features, i, j, <int> best_index_u, <int> best_index_v, feature_depth) * else: */ __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_set_flow_at_point(__pyx_v_i, __pyx_v_j, (__pyx_v_best_index_v - __pyx_v_j), (__pyx_v_best_index_u - __pyx_v_i), __pyx_v_flow_arr); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":130 * if best_index_u != -1: * set_flow_at_point(i, j, best_index_v - j, best_index_u - i, flow_arr) * feature_errors[i, j] = <float> dist(left_features, right_features, i, j, <int> best_index_u, <int> best_index_v, feature_depth) # <<<<<<<<<<<<<< * else: * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) */ __pyx_t_23 = __pyx_v_i; __pyx_t_24 = __pyx_v_j; *((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_feature_errors.data + __pyx_t_23 * __pyx_v_feature_errors.strides[0]) ) + __pyx_t_24 * __pyx_v_feature_errors.strides[1]) )) = ((float)__pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__pyx_v_left_features, __pyx_v_right_features, __pyx_v_i, __pyx_v_j, ((int)__pyx_v_best_index_u), ((int)__pyx_v_best_index_v), __pyx_v_feature_depth)); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":128 * # printf("i %3i, j, %3i, v1 %2i, v2 %2i, best_index_u %2.1f, dist1 %3.2f,\t dist2 %3.2f,\t best_index_v %3.1lf\n", i, j, v1, v2, best_index_u, dist1, dist2, best_index_v) * * if best_index_u != -1: # <<<<<<<<<<<<<< * set_flow_at_point(i, j, best_index_v - j, best_index_u - i, flow_arr) * feature_errors[i, j] = <float> dist(left_features, right_features, i, j, <int> best_index_u, <int> best_index_v, feature_depth) */ goto __pyx_L25; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":132 * feature_errors[i, j] = <float> dist(left_features, right_features, i, j, <int> best_index_u, <int> best_index_v, feature_depth) * else: * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) # <<<<<<<<<<<<<< * * return (np.asarray(flow_arr), np.asarray(feature_errors)) */ /*else*/ { __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_set_flow_at_point(__pyx_v_i, __pyx_v_j, 0.0, 0.0, __pyx_v_flow_arr); } __pyx_L25:; } __pyx_L12:; } } } } } } #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 } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":72 * cdef int best_x, best_y * * for i in prange(0, left_len_0, nogil=True, schedule='dynamic', num_threads=20): # <<<<<<<<<<<<<< * # for i in range(left_len_0): * for j in range(0, left_len_1): */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":134 * set_flow_at_point(i, j, 0.0, 0.0, flow_arr) * * return (np.asarray(flow_arr), np.asarray(feature_errors)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_26 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_26)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_26); __pyx_t_27 = __Pyx_PyObject_GetAttrStr(__pyx_t_26, __pyx_n_s_asarray); if (unlikely(!__pyx_t_27)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_27); __Pyx_DECREF(__pyx_t_26); __pyx_t_26 = 0; __pyx_t_26 = __pyx_memoryview_fromslice(__pyx_v_flow_arr, 3, (PyObject *(*)(char *)) __pyx_memview_get_float, (int (*)(char *, PyObject *)) __pyx_memview_set_float, 0);; if (unlikely(!__pyx_t_26)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_26); __pyx_t_28 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_27))) { __pyx_t_28 = PyMethod_GET_SELF(__pyx_t_27); if (likely(__pyx_t_28)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_27); __Pyx_INCREF(__pyx_t_28); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_27, function); } } if (!__pyx_t_28) { __pyx_t_25 = __Pyx_PyObject_CallOneArg(__pyx_t_27, __pyx_t_26); if (unlikely(!__pyx_t_25)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_DECREF(__pyx_t_26); __pyx_t_26 = 0; __Pyx_GOTREF(__pyx_t_25); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_27)) { PyObject *__pyx_temp[2] = {__pyx_t_28, __pyx_t_26}; __pyx_t_25 = __Pyx_PyFunction_FastCall(__pyx_t_27, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_25)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_28); __pyx_t_28 = 0; __Pyx_GOTREF(__pyx_t_25); __Pyx_DECREF(__pyx_t_26); __pyx_t_26 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_27)) { PyObject *__pyx_temp[2] = {__pyx_t_28, __pyx_t_26}; __pyx_t_25 = __Pyx_PyCFunction_FastCall(__pyx_t_27, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_25)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_28); __pyx_t_28 = 0; __Pyx_GOTREF(__pyx_t_25); __Pyx_DECREF(__pyx_t_26); __pyx_t_26 = 0; } else #endif { __pyx_t_29 = PyTuple_New(1+1); if (unlikely(!__pyx_t_29)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_29); __Pyx_GIVEREF(__pyx_t_28); PyTuple_SET_ITEM(__pyx_t_29, 0, __pyx_t_28); __pyx_t_28 = NULL; __Pyx_GIVEREF(__pyx_t_26); PyTuple_SET_ITEM(__pyx_t_29, 0+1, __pyx_t_26); __pyx_t_26 = 0; __pyx_t_25 = __Pyx_PyObject_Call(__pyx_t_27, __pyx_t_29, NULL); if (unlikely(!__pyx_t_25)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_25); __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; } } __Pyx_DECREF(__pyx_t_27); __pyx_t_27 = 0; __pyx_t_29 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_29)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_29); __pyx_t_26 = __Pyx_PyObject_GetAttrStr(__pyx_t_29, __pyx_n_s_asarray); if (unlikely(!__pyx_t_26)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_26); __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; __pyx_t_29 = __pyx_memoryview_fromslice(__pyx_v_feature_errors, 2, (PyObject *(*)(char *)) __pyx_memview_get_float, (int (*)(char *, PyObject *)) __pyx_memview_set_float, 0);; if (unlikely(!__pyx_t_29)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_29); __pyx_t_28 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_26))) { __pyx_t_28 = PyMethod_GET_SELF(__pyx_t_26); if (likely(__pyx_t_28)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_26); __Pyx_INCREF(__pyx_t_28); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_26, function); } } if (!__pyx_t_28) { __pyx_t_27 = __Pyx_PyObject_CallOneArg(__pyx_t_26, __pyx_t_29); if (unlikely(!__pyx_t_27)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; __Pyx_GOTREF(__pyx_t_27); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_26)) { PyObject *__pyx_temp[2] = {__pyx_t_28, __pyx_t_29}; __pyx_t_27 = __Pyx_PyFunction_FastCall(__pyx_t_26, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_27)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_28); __pyx_t_28 = 0; __Pyx_GOTREF(__pyx_t_27); __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_26)) { PyObject *__pyx_temp[2] = {__pyx_t_28, __pyx_t_29}; __pyx_t_27 = __Pyx_PyCFunction_FastCall(__pyx_t_26, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_27)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_28); __pyx_t_28 = 0; __Pyx_GOTREF(__pyx_t_27); __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; } else #endif { __pyx_t_30 = PyTuple_New(1+1); if (unlikely(!__pyx_t_30)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_30); __Pyx_GIVEREF(__pyx_t_28); PyTuple_SET_ITEM(__pyx_t_30, 0, __pyx_t_28); __pyx_t_28 = NULL; __Pyx_GIVEREF(__pyx_t_29); PyTuple_SET_ITEM(__pyx_t_30, 0+1, __pyx_t_29); __pyx_t_29 = 0; __pyx_t_27 = __Pyx_PyObject_Call(__pyx_t_26, __pyx_t_30, NULL); if (unlikely(!__pyx_t_27)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_27); __Pyx_DECREF(__pyx_t_30); __pyx_t_30 = 0; } } __Pyx_DECREF(__pyx_t_26); __pyx_t_26 = 0; __pyx_t_26 = PyTuple_New(2); if (unlikely(!__pyx_t_26)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_26); __Pyx_GIVEREF(__pyx_t_25); PyTuple_SET_ITEM(__pyx_t_26, 0, __pyx_t_25); __Pyx_GIVEREF(__pyx_t_27); PyTuple_SET_ITEM(__pyx_t_26, 1, __pyx_t_27); __pyx_t_25 = 0; __pyx_t_27 = 0; __pyx_r = __pyx_t_26; __pyx_t_26 = 0; goto __pyx_L0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":40 * @cython.wraparound(False) * @cython.cdivision(True) * cdef compute_flow_helper(np.ndarray[np.float32_t, ndim=3] left_features_obj, # <<<<<<<<<<<<<< * np.ndarray[np.float32_t, ndim=3] right_features_obj, np.ndarray[np.int32_t, ndim=2] mask_obj, * int neighborhood_len_import, np.ndarray[np.float32_t, ndim=3] flow_arr_obj, */ /* function exit code */ __pyx_L1_error:; __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_2, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_3, 1); __Pyx_XDECREF(__pyx_t_25); __Pyx_XDECREF(__pyx_t_26); __Pyx_XDECREF(__pyx_t_27); __Pyx_XDECREF(__pyx_t_28); __Pyx_XDECREF(__pyx_t_29); __Pyx_XDECREF(__pyx_t_30); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("triplet_flow_loss.slow_flow_calculator_cython.compute_flow_helper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_feature_error_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flow_arr_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_left_features_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask_obj.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_right_features_obj.rcbuffer->pybuffer); __pyx_L2:; __PYX_XDEC_MEMVIEW(&__pyx_v_left_features, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_right_features, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_flow_arr, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_mask, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_feature_errors, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":139 * @cython.boundscheck(False) # turn off bounds-checking for entire function * @cython.wraparound(False) * cdef void set_flow_at_point(int a, int b, float i, float j, float[:,:,:] flow_arr) nogil: # <<<<<<<<<<<<<< * flow_arr[a, b, 0] = i * flow_arr[a, b, 1] = j */ static void __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_set_flow_at_point(int __pyx_v_a, int __pyx_v_b, float __pyx_v_i, float __pyx_v_j, __Pyx_memviewslice __pyx_v_flow_arr) { Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":140 * @cython.wraparound(False) * cdef void set_flow_at_point(int a, int b, float i, float j, float[:,:,:] flow_arr) nogil: * flow_arr[a, b, 0] = i # <<<<<<<<<<<<<< * flow_arr[a, b, 1] = j * */ __pyx_t_1 = __pyx_v_a; __pyx_t_2 = __pyx_v_b; __pyx_t_3 = 0; *((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_flow_arr.data + __pyx_t_1 * __pyx_v_flow_arr.strides[0]) ) + __pyx_t_2 * __pyx_v_flow_arr.strides[1]) ) + __pyx_t_3 * __pyx_v_flow_arr.strides[2]) )) = __pyx_v_i; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":141 * cdef void set_flow_at_point(int a, int b, float i, float j, float[:,:,:] flow_arr) nogil: * flow_arr[a, b, 0] = i * flow_arr[a, b, 1] = j # <<<<<<<<<<<<<< * * */ __pyx_t_4 = __pyx_v_a; __pyx_t_5 = __pyx_v_b; __pyx_t_6 = 1; *((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_flow_arr.data + __pyx_t_4 * __pyx_v_flow_arr.strides[0]) ) + __pyx_t_5 * __pyx_v_flow_arr.strides[1]) ) + __pyx_t_6 * __pyx_v_flow_arr.strides[2]) )) = __pyx_v_j; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":139 * @cython.boundscheck(False) # turn off bounds-checking for entire function * @cython.wraparound(False) * cdef void set_flow_at_point(int a, int b, float i, float j, float[:,:,:] flow_arr) nogil: # <<<<<<<<<<<<<< * flow_arr[a, b, 0] = i * flow_arr[a, b, 1] = j */ /* function exit code */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":147 * @cython.wraparound(False) * @cython.cdivision(True) * cdef inline float dist(float[:,:,:] left_features, float[:,:,:] right_features, # <<<<<<<<<<<<<< * int i, int j, int a, int b, int feature_depth) nogil: * """ */ static CYTHON_INLINE float __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_dist(__Pyx_memviewslice __pyx_v_left_features, __Pyx_memviewslice __pyx_v_right_features, int __pyx_v_i, int __pyx_v_j, int __pyx_v_a, int __pyx_v_b, int __pyx_v_feature_depth) { float __pyx_v_current_dist; float __pyx_v_temp; int __pyx_v_k; float __pyx_r; 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; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; Py_ssize_t __pyx_t_8; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":153 * appears to work better than L1 or L2, future investigation into this could be interesting. * """ * cdef float current_dist = 0 # <<<<<<<<<<<<<< * cdef float temp = 0 * cdef int k */ __pyx_v_current_dist = 0.0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":154 * """ * cdef float current_dist = 0 * cdef float temp = 0 # <<<<<<<<<<<<<< * cdef int k * for k in range(feature_depth): */ __pyx_v_temp = 0.0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":156 * cdef float temp = 0 * cdef int k * for k in range(feature_depth): # <<<<<<<<<<<<<< * temp = <float> left_features[i, j, k] - <float> right_features[a, b, k] * current_dist += sqrt(fabs(temp)) */ __pyx_t_1 = __pyx_v_feature_depth; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_k = __pyx_t_2; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":157 * cdef int k * for k in range(feature_depth): * temp = <float> left_features[i, j, k] - <float> right_features[a, b, k] # <<<<<<<<<<<<<< * current_dist += sqrt(fabs(temp)) * return current_dist */ __pyx_t_3 = __pyx_v_i; __pyx_t_4 = __pyx_v_j; __pyx_t_5 = __pyx_v_k; __pyx_t_6 = __pyx_v_a; __pyx_t_7 = __pyx_v_b; __pyx_t_8 = __pyx_v_k; __pyx_v_temp = (((float)(*((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_left_features.data + __pyx_t_3 * __pyx_v_left_features.strides[0]) ) + __pyx_t_4 * __pyx_v_left_features.strides[1]) ) + __pyx_t_5 * __pyx_v_left_features.strides[2]) )))) - ((float)(*((float *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_right_features.data + __pyx_t_6 * __pyx_v_right_features.strides[0]) ) + __pyx_t_7 * __pyx_v_right_features.strides[1]) ) + __pyx_t_8 * __pyx_v_right_features.strides[2]) ))))); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":158 * for k in range(feature_depth): * temp = <float> left_features[i, j, k] - <float> right_features[a, b, k] * current_dist += sqrt(fabs(temp)) # <<<<<<<<<<<<<< * return current_dist * */ __pyx_v_current_dist = (__pyx_v_current_dist + sqrt(fabs(__pyx_v_temp))); } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":159 * temp = <float> left_features[i, j, k] - <float> right_features[a, b, k] * current_dist += sqrt(fabs(temp)) * return current_dist # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_current_dist; goto __pyx_L0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":147 * @cython.wraparound(False) * @cython.cdivision(True) * cdef inline float dist(float[:,:,:] left_features, float[:,:,:] right_features, # <<<<<<<<<<<<<< * int i, int j, int a, int b, int feature_depth) nogil: * """ */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":162 * * * cdef inline int max_int(int a, int b) nogil: # <<<<<<<<<<<<<< * if a < b: * return b */ static CYTHON_INLINE int __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_max_int(int __pyx_v_a, int __pyx_v_b) { int __pyx_r; int __pyx_t_1; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":163 * * cdef inline int max_int(int a, int b) nogil: * if a < b: # <<<<<<<<<<<<<< * return b * else: */ __pyx_t_1 = ((__pyx_v_a < __pyx_v_b) != 0); if (__pyx_t_1) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":164 * cdef inline int max_int(int a, int b) nogil: * if a < b: * return b # <<<<<<<<<<<<<< * else: * return a */ __pyx_r = __pyx_v_b; goto __pyx_L0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":163 * * cdef inline int max_int(int a, int b) nogil: * if a < b: # <<<<<<<<<<<<<< * return b * else: */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":166 * return b * else: * return a # <<<<<<<<<<<<<< * * */ /*else*/ { __pyx_r = __pyx_v_a; goto __pyx_L0; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":162 * * * cdef inline int max_int(int a, int b) nogil: # <<<<<<<<<<<<<< * if a < b: * return b */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":169 * * * cdef inline int min_int(int a, int b) nogil: # <<<<<<<<<<<<<< * if a > b: * return b */ static CYTHON_INLINE int __pyx_f_17triplet_flow_loss_27slow_flow_calculator_cython_min_int(int __pyx_v_a, int __pyx_v_b) { int __pyx_r; int __pyx_t_1; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":170 * * cdef inline int min_int(int a, int b) nogil: * if a > b: # <<<<<<<<<<<<<< * return b * else: */ __pyx_t_1 = ((__pyx_v_a > __pyx_v_b) != 0); if (__pyx_t_1) { /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":171 * cdef inline int min_int(int a, int b) nogil: * if a > b: * return b # <<<<<<<<<<<<<< * else: * return a */ __pyx_r = __pyx_v_b; goto __pyx_L0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":170 * * cdef inline int min_int(int a, int b) nogil: * if a > b: # <<<<<<<<<<<<<< * return b * else: */ } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":173 * return b * else: * return a # <<<<<<<<<<<<<< */ /*else*/ { __pyx_r = __pyx_v_a; goto __pyx_L0; } /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":169 * * * cdef inline int min_int(int a, int b) nogil: # <<<<<<<<<<<<<< * if a > b: * return b */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":207 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":212 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ goto __pyx_L4; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ /*else*/ { __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 218, __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, 218, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 222, __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, 222, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":224 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":225 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":231 * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L11; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":237 * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":238 * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":242 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef int offset */ __pyx_v_f = NULL; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":243 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":250 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ goto __pyx_L14; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ /*else*/ { __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 * 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__6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 259, __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, 259, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 * (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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = ((char *)"B"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = ((char *)"h"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = ((char *)"H"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = ((char *)"i"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = ((char *)"I"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = ((char *)"l"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = ((char *)"L"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = ((char *)"q"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = ((char *)"Q"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = ((char *)"f"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = ((char *)"d"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = ((char *)"g"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = ((char *)"Zf"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = ((char *)"Zd"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":275 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = ((char *)"Zg"); break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = ((char *)"O"); break; default: /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 * 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, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 278, __pyx_L1_error) break; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":279 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 * return * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)malloc(0xFF)); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":284 * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":285 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) __PYX_ERR(1, 285, __pyx_L1_error) __pyx_v_f = __pyx_t_7; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 * 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'; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":294 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":770 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 * * 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, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":770 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":773 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 * * 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, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":773 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":776 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 * * 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, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":776 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":779 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 * * 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, 780, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":779 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":782 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 783, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":782 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 * * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 * 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, 794, __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, 794, __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, 794, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 * * 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, 795, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 795, __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, 795, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - <int>(new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 796, __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, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 796, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 796, __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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 * 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, 798, __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, 798, __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, 798, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * * 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__7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 799, __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, 799, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 * 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") * */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * 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:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 * * 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:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * 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 (__pyx_t_6) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 * 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__8, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 803, __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, 803, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * 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") */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 * * # 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, 813, __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, 813, __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, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 * 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); } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 * 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) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 * * 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, 821, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * 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__9, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 823, __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, 823, __pyx_L1_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 * * # 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, 826, __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, 826, __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, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 * # 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, 827, __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, 827, __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, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 * 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, 828, __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, 828, __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, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 * 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, 829, __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, 829, __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, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 * 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, 830, __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, 830, __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, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 * 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, 831, __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, 831, __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, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 * 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, 832, __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, 832, __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, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 * 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, 833, __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, 833, __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, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 * 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, 834, __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, 834, __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, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 * 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, 835, __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, 835, __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, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 * 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, 836, __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, 836, __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, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 * 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, 837, __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, 837, __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, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 * 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, 838, __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, 838, __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, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 * 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, 839, __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, 839, __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, 839, __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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 * 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, 840, __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, 840, __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, 840, __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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 * 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, 841, __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, 841, __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, 841, __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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 * 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, 842, __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, 842, __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, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 * 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 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __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(1, 844, __pyx_L1_error) } __pyx_L15:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 * # 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 == NULL)) __PYX_ERR(1, 849, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 * 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; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ goto __pyx_L3; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = <PyObject*>base * Py_XDECREF(arr.base) */ /*else*/ { Py_INCREF(__pyx_v_base); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = <PyObject*>base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return <object>arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< * * */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":985 * # 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":986 * # 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:*/ { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":987 * 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 == -1)) __PYX_ERR(1, 987, __pyx_L3_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":986 * # 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_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":988 * 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, 988, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":989 * _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__10, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 989, __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, 989, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ __Pyx_PyThreadState_assign __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_L10_try_end:; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":985 * # 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":991 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":992 * * 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:*/ { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":993 * 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 == -1)) __PYX_ERR(1, 993, __pyx_L3_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":992 * * 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_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":994 * 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, 994, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":995 * _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__11, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 995, __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, 995, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __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_L10_try_end:; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":991 * 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; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":997 * 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); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":998 * * 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:*/ { /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":999 * 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 == -1)) __PYX_ERR(1, 999, __pyx_L3_error) /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":998 * * 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_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":1000 * 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, 1000, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1001, __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, 1001, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __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_L10_try_end:; } /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":997 * 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":120 * 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); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(2, 120, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(2, 120, __pyx_L3_error) } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 120, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_shape = ((PyObject*)values[0]); __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 120, __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, 121, __pyx_L3_error) } else { /* "View.MemoryView":121 * * 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, 120, __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, 120, __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, 120, __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":120 * 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; char *__pyx_t_6; int __pyx_t_7; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":127 * 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, 127, __pyx_L1_error) } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(2, 127, __pyx_L1_error) __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":128 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":130 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":131 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 131, __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, 131, __pyx_L1_error) /* "View.MemoryView":130 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ } /* "View.MemoryView":133 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":134 * * 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__14, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 134, __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, 134, __pyx_L1_error) /* "View.MemoryView":133 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ } /* "View.MemoryView":136 * 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":137 * * 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_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":136 * 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":138 * 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, 138, __pyx_L1_error) __pyx_t_5 = __pyx_v_format; __Pyx_INCREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __Pyx_GOTREF(__pyx_v_self->_format); __Pyx_DECREF(__pyx_v_self->_format); __pyx_v_self->_format = ((PyObject*)__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":139 * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ __pyx_t_6 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_6) && PyErr_Occurred())) __PYX_ERR(2, 139, __pyx_L1_error) __pyx_v_self->format = __pyx_t_6; /* "View.MemoryView":142 * * * 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":143 * * 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":145 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":146 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 146, __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, 146, __pyx_L1_error) /* "View.MemoryView":145 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ } /* "View.MemoryView":149 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_7 = 0; __pyx_t_5 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_5); __pyx_t_1 = 0; for (;;) { if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_5)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(2, 149, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_5, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 149, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 149, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_dim = __pyx_t_8; __pyx_v_idx = __pyx_t_7; __pyx_t_7 = (__pyx_t_7 + 1); /* "View.MemoryView":150 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":151 * 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_3 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); __pyx_t_3 = 0; __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __Pyx_Raise(__pyx_t_9, 0, 0, 0); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __PYX_ERR(2, 151, __pyx_L1_error) /* "View.MemoryView":150 * * 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":152 * 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":149 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":155 * * 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, 155, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":156 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":157 * 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":155 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ goto __pyx_L10; } /* "View.MemoryView":158 * 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, 158, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":159 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":160 * 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":158 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ goto __pyx_L10; } /* "View.MemoryView":162 * 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_5 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 162, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 162, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 162, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __PYX_ERR(2, 162, __pyx_L1_error) } __pyx_L10:; /* "View.MemoryView":164 * 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":167 * 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":168 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_5 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 168, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 168, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":169 * 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":172 * * * 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":173 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":174 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 174, __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, 174, __pyx_L1_error) /* "View.MemoryView":173 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ } /* "View.MemoryView":176 * 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":177 * * 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":178 * 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, 178, __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, 178, __pyx_L1_error) } __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { __pyx_v_i = __pyx_t_8; /* "View.MemoryView":179 * 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":180 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } /* "View.MemoryView":176 * 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":169 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":120 * 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_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_format); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":183 * * @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; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":184 * @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":185 * 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, 185, __pyx_L1_error) __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":186 * 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":185 * 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":187 * 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, 187, __pyx_L1_error) __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":188 * 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":187 * 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":189 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":190 * 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__18, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 190, __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, 190, __pyx_L1_error) /* "View.MemoryView":189 * 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":191 * 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":192 * 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":193 * 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":194 * 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":195 * 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":196 * 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":197 * 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":198 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":200 * 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":201 * * 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":200 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ goto __pyx_L5; } /* "View.MemoryView":203 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":205 * 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":183 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":209 * __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":210 * * 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":211 * 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":210 * * 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":212 * 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":213 * 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":214 * 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":213 * 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":216 * 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":212 * 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":217 * self._strides, self.ndim, False) * free(self.data) * PyObject_Free(self._shape) # <<<<<<<<<<<<<< * * @property */ PyObject_Free(__pyx_v_self->_shape); /* "View.MemoryView":209 * __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":220 * * @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":221 * @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, 221, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":220 * * @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":224 * * @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":225 * @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":226 * cdef get_memview(self): * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 226, __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, 226, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 226, __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, 226, __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":224 * * @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":229 * * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* Python wrapper */ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__getattr__", 0); /* "View.MemoryView":230 * * 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, 230, __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, 230, __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":229 * * * 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":232 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* Python wrapper */ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":233 * * 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, 233, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 233, __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":232 * 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":235 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* Python wrapper */ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setitem__", 0); /* "View.MemoryView":236 * * 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, 236, __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, 236, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":235 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":240 * * @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":244 * 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":245 * * 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, 245, __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, 245, __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, 245, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 245, __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, 245, __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":244 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ goto __pyx_L3; } /* "View.MemoryView":247 * 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, 247, __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, 247, __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, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 247, __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":248 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 248, __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, 248, __pyx_L1_error) /* "View.MemoryView":247 * 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, 247, __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":249 * 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":251 * 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":240 * * @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":277 * 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); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(2, 277, __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, 277, __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":278 * 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":277 * 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":279 * 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":280 * 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":279 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":294 * * @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":296 * 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":300 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":302 * 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":303 * * 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":302 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ } /* "View.MemoryView":305 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":294 * * @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":341 * 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); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(2, 341, __pyx_L3_error) } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); if (value) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 341, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_obj = values[0]; __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 341, __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, 341, __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, 341, __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":342 * * 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":343 * 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":344 * 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":345 * self.flags = flags * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None */ __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(2, 345, __pyx_L1_error) /* "View.MemoryView":346 * 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":347 * __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":348 * 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":346 * 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":344 * 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":351 * * 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":352 * 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":353 * 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":351 * * 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":354 * 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":355 * __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":356 * 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 (__pyx_t_1) { /* "View.MemoryView":357 * self.lock = PyThread_allocate_lock() * if self.lock is NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); __PYX_ERR(2, 357, __pyx_L1_error) /* "View.MemoryView":356 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ } /* "View.MemoryView":354 * 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":359 * 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":360 * * 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":359 * 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":362 * 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":364 * 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":366 * 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":341 * 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":368 * 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; PyThread_type_lock __pyx_t_5; PyThread_type_lock __pyx_t_6; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":369 * * 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":370 * 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":369 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * */ } /* "View.MemoryView":374 * 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":375 * 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; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":376 * 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":377 * 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":378 * 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":380 * 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_5 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_v_i]); /* "View.MemoryView":379 * __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_5; (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_6; /* "View.MemoryView":378 * 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":381 * __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":376 * 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":383 * 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":374 * 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":368 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":385 * 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":387 * 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":389 * 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, 389, __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, 389, __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, 389, __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, 389, __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, 389, __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, 389, __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(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 389, __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":390 * * 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, 390, __pyx_L1_error) __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) __PYX_ERR(2, 390, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":389 * 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":392 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":385 * 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":395 * * * 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":396 * * 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":397 * 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":396 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ } /* "View.MemoryView":399 * 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, 399, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(2, 399, __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, 399, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 399, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 399, __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":402 * * 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, 402, __pyx_L1_error) if (__pyx_t_2) { /* "View.MemoryView":403 * 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, 403, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":402 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ } /* "View.MemoryView":405 * 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 == NULL)) __PYX_ERR(2, 405, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":406 * 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, 406, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":395 * * * 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":408 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* Python wrapper */ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_obj = NULL; int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":409 * * def __setitem__(memoryview self, object index, object value): * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 409, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (likely(__pyx_t_1 != Py_None)) { PyObject* sequence = __pyx_t_1; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(2, 409, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); #else __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 409, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 409, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 409, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_2; __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":411 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 411, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":412 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 412, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_obj = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":413 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 413, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":414 * obj = self.is_slice(value) * if obj: * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< * else: * self.setitem_slice_assign_scalar(self[index], value) */ __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":413 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ goto __pyx_L4; } /* "View.MemoryView":416 * 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_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 416, __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, 416, __pyx_L1_error) __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L4:; /* "View.MemoryView":411 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ goto __pyx_L3; } /* "View.MemoryView":418 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ /*else*/ { __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L3:; /* "View.MemoryView":408 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_obj); __Pyx_XDECREF(__pyx_v_index); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":420 * 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":421 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":422 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|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":423 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 423, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":424 * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) # <<<<<<<<<<<<<< * except TypeError: * return None */ __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 424, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":423 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 423, __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, 423, __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":422 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|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_L11_try_end; __pyx_L4_error:; __Pyx_PyThreadState_assign __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":425 * obj = memoryview(obj, self.flags|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, 425, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":426 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L7_except_return; } goto __pyx_L6_except_error; __pyx_L6_except_error:; /* "View.MemoryView":422 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ __Pyx_PyThreadState_assign __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_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L0; __pyx_L11_try_end:; } /* "View.MemoryView":421 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ } /* "View.MemoryView":428 * 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":420 * 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":430 * 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":434 * 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, 434, __pyx_L1_error) /* "View.MemoryView":435 * * 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, 435, __pyx_L1_error) /* "View.MemoryView":436 * 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, 436, __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, 436, __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, 436, __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, 436, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":434 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(2, 434, __pyx_L1_error) /* "View.MemoryView":430 * 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":438 * 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":440 * 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":445 * 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":447 * 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":448 * * 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":449 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":450 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); __PYX_ERR(2, 450, __pyx_L1_error) /* "View.MemoryView":449 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ } /* "View.MemoryView":451 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; /* "View.MemoryView":447 * 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":453 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":455 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":456 * * 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":457 * 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":456 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ goto __pyx_L8; } /* "View.MemoryView":459 * (<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, 459, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; /* "View.MemoryView":463 * * * 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":464 * * 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, 464, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":463 * * * 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":465 * 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":468 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< * * cdef setitem_indexed(self, index, value): */ /*finally:*/ { /*normal exit:*/{ PyMem_Free(__pyx_v_tmp); goto __pyx_L7; } /*exception exit:*/{ __Pyx_PyThreadState_declare __pyx_L6_error:; __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __Pyx_PyThreadState_assign __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); } __Pyx_PyThreadState_assign 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":438 * 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":470 * 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":471 * * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< * self.assign_item_from_object(itemp, value) * */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) __PYX_ERR(2, 471, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":472 * 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, 472, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":470 * 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":474 * 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":477 * """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, 477, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":480 * 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, 480, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":481 * * 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":482 * 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, 482, __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, 482, __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, 482, __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, 482, __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, 482, __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, 482, __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":481 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ } /* "View.MemoryView":486 * 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":487 * 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(2, 487, __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":486 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ } /* "View.MemoryView":488 * 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_PyThreadState_assign __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":483 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 483, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_8 = __Pyx_PyErr_ExceptionMatches(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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_1, &__pyx_t_5, &__pyx_t_9) < 0) __PYX_ERR(2, 483, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_9); /* "View.MemoryView":484 * 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__19, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 484, __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, 484, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "View.MemoryView":481 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ __Pyx_PyThreadState_assign __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_PyThreadState_assign __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":474 * 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":490 * 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":493 * """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, 493, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":498 * 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":499 * * 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, 499, __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, 499, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 499, __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 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 499, __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, 499, __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, 499, __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, 499, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":498 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ goto __pyx_L3; } /* "View.MemoryView":501 * 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, 501, __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, 501, __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, 501, __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, 501, __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, 501, __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, 501, __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, 501, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":503 * 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, 503, __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":504 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_9; /* "View.MemoryView":503 * 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":504 * * 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":490 * 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":507 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t *__pyx_t_2; char *__pyx_t_3; void *__pyx_t_4; int __pyx_t_5; Py_ssize_t __pyx_t_6; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":508 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":509 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_2 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_2; /* "View.MemoryView":508 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ goto __pyx_L3; } /* "View.MemoryView":511 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L3:; /* "View.MemoryView":513 * 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":514 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_2 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_2; /* "View.MemoryView":513 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ goto __pyx_L4; } /* "View.MemoryView":516 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L4:; /* "View.MemoryView":518 * 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":519 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_2 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_2; /* "View.MemoryView":518 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ goto __pyx_L5; } /* "View.MemoryView":521 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L5:; /* "View.MemoryView":523 * 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":524 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_3 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_3; /* "View.MemoryView":523 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ goto __pyx_L6; } /* "View.MemoryView":526 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L6:; /* "View.MemoryView":528 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_4 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":529 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_5 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_5; /* "View.MemoryView":530 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = 0 */ __pyx_t_6 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_6; /* "View.MemoryView":531 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = 0 * info.obj = self */ __pyx_t_6 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_6; /* "View.MemoryView":532 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = 0 # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_v_info->readonly = 0; /* "View.MemoryView":533 * info.len = self.view.len * info.readonly = 0 * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":507 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* function exit code */ __pyx_r = 0; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":539 * * @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":540 * @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, 540, __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, 540, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":541 * 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 == 0)) __PYX_ERR(2, 541, __pyx_L1_error) /* "View.MemoryView":542 * 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":539 * * @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":545 * * @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":546 * @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":545 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":549 * * @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":550 * @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, 550, __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, 550, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(2, 550, __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, 550, __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":549 * * @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":553 * * @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":554 * @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 (__pyx_t_1) { /* "View.MemoryView":556 * 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__20, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 556, __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, 556, __pyx_L1_error) /* "View.MemoryView":554 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ } /* "View.MemoryView":558 * 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, 558, __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, 558, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(2, 558, __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, 558, __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":553 * * @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":561 * * @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":562 * @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":563 * 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, 563, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__21, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 563, __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":562 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ } /* "View.MemoryView":565 * 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, 565, __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, 565, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(2, 565, __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, 565, __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":561 * * @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":568 * * @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":569 * @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, 569, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":568 * * @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":572 * * @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":573 * @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, 573, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":572 * * @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":576 * * @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":577 * @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, 577, __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, 577, __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, 577, __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":576 * * @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":580 * * @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":581 * @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":582 * 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":584 * 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, 584, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":585 * * 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, 585, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":587 * 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":581 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ } /* "View.MemoryView":589 * 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":580 * * @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":591 * 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":592 * * 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":593 * 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":592 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ } /* "View.MemoryView":595 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":591 * 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":597 * 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":598 * * 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, 598, __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, 598, __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, 598, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":599 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 599, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 599, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":598 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 598, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 598, __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":597 * 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":601 * 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":602 * * 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, 602, __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, 602, __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, 602, __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, 602, __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, 602, __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":601 * 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":605 * * * 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":608 * 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":609 * 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, 609, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":605 * * * 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":611 * 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":614 * 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":615 * 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, 615, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":611 * 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":617 * 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":619 * 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":621 * 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":622 * * 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, 622, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":627 * 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, 627, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":617 * 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":629 * 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":631 * 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":633 * 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":634 * * 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, 634, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":639 * 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, 639, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":629 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":643 * * @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":644 * @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, 644, __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, 644, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 644, __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, 644, __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":645 * 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":646 * 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":643 * * @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":649 * * @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":650 * @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":649 * * @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":652 * 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":657 * 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":658 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 658, __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":657 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ goto __pyx_L3; } /* "View.MemoryView":660 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":662 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 662, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":663 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":664 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":665 * 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, 665, __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, 665, __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, 665, __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, 665, __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, 665, __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, 665, __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(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 665, __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, 665, __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":666 * 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":667 * 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":668 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) __PYX_ERR(2, 668, __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, 668, __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 == -1)) __PYX_ERR(2, 668, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":669 * 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":667 * 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":671 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ /*else*/ { __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__23); if (unlikely(__pyx_t_9 == -1)) __PYX_ERR(2, 671, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":672 * 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":666 * 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":674 * 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 (__pyx_t_1) { /* "View.MemoryView":675 * else: * if not isinstance(item, slice) and not PyIndex_Check(item): * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< * * have_slices = have_slices or isinstance(item, slice) */ __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __PYX_ERR(2, 675, __pyx_L1_error) /* "View.MemoryView":674 * 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":677 * 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":678 * * have_slices = have_slices or isinstance(item, slice) * result.append(item) # <<<<<<<<<<<<<< * * nslices = ndim - len(result) */ __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) __PYX_ERR(2, 678, __pyx_L1_error) } __pyx_L6:; /* "View.MemoryView":665 * 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":680 * result.append(item) * * nslices = ndim - len(result) # <<<<<<<<<<<<<< * if nslices: * result.extend([slice(None)] * nslices) */ __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) __PYX_ERR(2, 680, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":681 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":682 * 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, 682, __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__24); __Pyx_GIVEREF(__pyx_slice__24); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__24); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) __PYX_ERR(2, 682, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":681 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ } /* "View.MemoryView":684 * 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, 684, __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, 684, __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, 684, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 684, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L0; /* "View.MemoryView":652 * 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":686 * 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":687 * * 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":688 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":689 * 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__25, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 689, __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, 689, __pyx_L1_error) /* "View.MemoryView":688 * 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":686 * 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":696 * * @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":697 * @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":704 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); /* "View.MemoryView":708 * 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, 708, __pyx_L1_error) } } #endif /* "View.MemoryView":710 * 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":711 * * 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, 711, __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":712 * 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":710 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ goto __pyx_L3; } /* "View.MemoryView":714 * 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":715 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":721 * * * 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":722 * * 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":727 * * * 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":728 * * 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":732 * 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, 732, __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, 732, __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, 732, __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, 732, __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, 732, __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, 732, __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(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 732, __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":733 * * 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":737 * 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, 737, __pyx_L1_error) /* "View.MemoryView":734 * for dim, index in enumerate(indices): * if PyIndex_Check(index): * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) __PYX_ERR(2, 734, __pyx_L1_error) /* "View.MemoryView":733 * * 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":740 * 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":741 * 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":742 * 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":743 * 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":744 * 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":740 * 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":746 * 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, 746, __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, 746, __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, 746, __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":747 * 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, 747, __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, 747, __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, 747, __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":748 * 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, 748, __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, 748, __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, 748, __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":750 * 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, 750, __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":751 * * 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, 751, __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":752 * 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, 752, __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":754 * have_step = index.step is not None * * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) __PYX_ERR(2, 754, __pyx_L1_error) /* "View.MemoryView":760 * 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":732 * 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":762 * 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":763 * * 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":764 * 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, 764, __pyx_L1_error) } /* "View.MemoryView":765 * 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, 765, __pyx_L1_error) } /* "View.MemoryView":763 * * 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, 763, __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, 763, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":762 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ } /* "View.MemoryView":768 * 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":769 * 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, 768, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":768 * 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, 768, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":696 * * @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":793 * * @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":813 * 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":815 * 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":816 * * 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":815 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ } /* "View.MemoryView":817 * 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":818 * 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 == -1)) __PYX_ERR(2, 818, __pyx_L1_error) /* "View.MemoryView":817 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ } /* "View.MemoryView":813 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ goto __pyx_L3; } /* "View.MemoryView":821 * 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":823 * 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":824 * * 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 == -1)) __PYX_ERR(2, 824, __pyx_L1_error) /* "View.MemoryView":823 * 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":827 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":828 * * 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":829 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":830 * 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":831 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; /* "View.MemoryView":830 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ } /* "View.MemoryView":828 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ goto __pyx_L12; } /* "View.MemoryView":832 * 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":833 * 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":834 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":833 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L14; } /* "View.MemoryView":836 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; /* "View.MemoryView":832 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ } __pyx_L12:; /* "View.MemoryView":827 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ goto __pyx_L11; } /* "View.MemoryView":838 * 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":839 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":838 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L15; } /* "View.MemoryView":841 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":843 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":844 * * 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":845 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":846 * 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":847 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; /* "View.MemoryView":846 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ } /* "View.MemoryView":844 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ goto __pyx_L17; } /* "View.MemoryView":848 * 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":849 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; /* "View.MemoryView":848 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ } __pyx_L17:; /* "View.MemoryView":843 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ goto __pyx_L16; } /* "View.MemoryView":851 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":852 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1L; /* "View.MemoryView":851 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ goto __pyx_L19; } /* "View.MemoryView":854 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":856 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":857 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; /* "View.MemoryView":856 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ } /* "View.MemoryView":861 * * 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":863 * 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":864 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); /* "View.MemoryView":863 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ } /* "View.MemoryView":866 * 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":867 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; /* "View.MemoryView":866 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ } /* "View.MemoryView":870 * * * 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":871 * * 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":872 * 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":875 * * * 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":876 * * 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":875 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ goto __pyx_L23; } /* "View.MemoryView":878 * 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":880 * 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":881 * * 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":882 * 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":883 * 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":882 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ goto __pyx_L26; } /* "View.MemoryView":885 * 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":886 * 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 == -1)) __PYX_ERR(2, 885, __pyx_L1_error) } __pyx_L26:; /* "View.MemoryView":881 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ goto __pyx_L25; } /* "View.MemoryView":888 * "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":880 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ } /* "View.MemoryView":890 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":793 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":896 * * @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":898 * 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":899 * 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":902 * 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":903 * * 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, 903, __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, 903, __pyx_L1_error) } __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); /* "View.MemoryView":904 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; /* "View.MemoryView":902 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ goto __pyx_L3; } /* "View.MemoryView":906 * 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":907 * 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":908 * 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":909 * 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":908 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ } } __pyx_L3:; /* "View.MemoryView":911 * 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":912 * * 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":913 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":914 * 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, 914, __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, 914, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 914, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 914, __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, 914, __pyx_L1_error) /* "View.MemoryView":913 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":911 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ } /* "View.MemoryView":916 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":917 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 917, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 917, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 917, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 917, __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, 917, __pyx_L1_error) /* "View.MemoryView":916 * 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":919 * 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":920 * * 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":921 * 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":920 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ } /* "View.MemoryView":923 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":896 * * @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":929 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_v_ndim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; int __pyx_v_i; int __pyx_v_j; int __pyx_r; int __pyx_t_1; Py_ssize_t *__pyx_t_2; long __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; /* "View.MemoryView":930 * @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":932 * 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":933 * * 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":937 * * 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_v_ndim / 2); for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":938 * 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":939 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< * shape[i], shape[j] = shape[j], shape[i] * */ __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":940 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: */ __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; /* "View.MemoryView":942 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L6_bool_binop_done; } __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L6_bool_binop_done:; if (__pyx_t_6) { /* "View.MemoryView":943 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_8 == -1)) __PYX_ERR(2, 943, __pyx_L1_error) /* "View.MemoryView":942 * 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":945 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":929 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":962 * 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":963 * * 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":962 * 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":965 * __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":966 * * 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":967 * 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, 967, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":966 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ } /* "View.MemoryView":969 * 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, 969, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":965 * __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":971 * 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":972 * * 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":973 * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< * else: * memoryview.assign_item_from_object(self, itemp, value) */ __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) __PYX_ERR(2, 973, __pyx_L1_error) /* "View.MemoryView":972 * * 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":975 * 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, 975, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":971 * 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":978 * * @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":979 * @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":978 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":985 * * @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":993 * 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":994 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "View.MemoryView":993 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ } /* "View.MemoryView":999 * * * 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, 999, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 999, __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, 999, __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":1001 * 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":1002 * * 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":1004 * __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, 1004, __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":1005 * * 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":1007 * 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":1008 * * 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":1009 * 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":1010 * 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":1011 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * result.flags = PyBUF_RECORDS */ Py_INCREF(Py_None); /* "View.MemoryView":1013 * Py_INCREF(Py_None) * * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":1015 * result.flags = PyBUF_RECORDS * * result.view.shape = <Py_ssize_t *> result.from_slice.shape # <<<<<<<<<<<<<< * result.view.strides = <Py_ssize_t *> result.from_slice.strides * */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); /* "View.MemoryView":1016 * * 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":1019 * * * 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":1020 * * 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":1021 * 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":1022 * 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":1023 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L5_break; /* "View.MemoryView":1021 * 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_L5_break:; /* "View.MemoryView":1025 * 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":1026 * * 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, 1026, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1027 * 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, 1027, __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, 1027, __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, 1027, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1029 * 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":1030 * * 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":1032 * 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":985 * * @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":1035 * * @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":1038 * __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":1039 * 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, 1039, __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":1040 * 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":1038 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ } /* "View.MemoryView":1042 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1043 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1035 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1046 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { int __pyx_v_dim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; Py_ssize_t *__pyx_v_suboffsets; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1050 * 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":1051 * * 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":1052 * 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":1054 * 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":1055 * * 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":1057 * dst.data = <char *> memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] */ __pyx_t_2 = __pyx_v_memview->view.ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_dim = __pyx_t_3; /* "View.MemoryView":1058 * * 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":1059 * 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":1060 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object') */ if ((__pyx_v_suboffsets != 0)) { __pyx_t_4 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_4 = -1L; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_4; } /* "View.MemoryView":1046 * * @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":1063 * * @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":1066 * "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":1067 * 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, 1067, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1063 * * @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":1070 * * @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":1077 * 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":1078 * * 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":1079 * 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":1077 * 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":1081 * 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":1082 * 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":1084 * 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":1086 * 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, 1084, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1070 * * @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":1092 * * * 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":1093 * * 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":1094 * 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":1093 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ } /* "View.MemoryView":1096 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1092 * * * 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":1099 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_c_stride; Py_ssize_t __pyx_v_f_stride; char __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1104 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1105 * 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":1107 * 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 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1108 * * 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":1109 * 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":1110 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; /* "View.MemoryView":1108 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ } } __pyx_L4_break:; /* "View.MemoryView":1112 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1113 * * 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":1114 * 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":1115 * 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":1113 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ } } __pyx_L7_break:; /* "View.MemoryView":1117 * 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":1118 * * 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":1117 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ } /* "View.MemoryView":1120 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1099 * * @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":1123 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; Py_ssize_t __pyx_v_dst_extent; Py_ssize_t __pyx_v_src_stride; Py_ssize_t __pyx_v_dst_stride; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; /* "View.MemoryView":1130 * * 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":1131 * 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":1132 * 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":1133 * 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":1135 * 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":1136 * * 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":1137 * 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":1136 * * 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":1138 * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); /* "View.MemoryView":1136 * * 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":1140 * 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; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1141 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); /* "View.MemoryView":1142 * 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":1143 * 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":1135 * 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":1145 * 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; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1146 * 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":1150 * 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":1151 * 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":1123 * * @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":1153 * 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":1156 * __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":1153 * 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":1160 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i */ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_size; Py_ssize_t __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1163 * "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":1165 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< * size *= src.shape[i] * */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1166 * * 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":1168 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1160 * * @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":1171 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { int __pyx_v_idx; Py_ssize_t __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1180 * 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":1181 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_idx = __pyx_t_3; /* "View.MemoryView":1182 * 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":1183 * 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":1180 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ goto __pyx_L3; } /* "View.MemoryView":1185 * 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 > -1L; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1186 * 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":1187 * 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":1189 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1171 * * @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":1192 * * @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; /* "View.MemoryView":1203 * 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":1204 * * 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":1206 * 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":1207 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1208 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) __PYX_ERR(2, 1208, __pyx_L1_error) /* "View.MemoryView":1207 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ } /* "View.MemoryView":1211 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1212 * * 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":1213 * tmpslice.data = <char *> result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1214 * 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":1215 * 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":1217 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); /* "View.MemoryView":1221 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1222 * * 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":1223 * 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":1222 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ } } /* "View.MemoryView":1225 * 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":1226 * * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); /* "View.MemoryView":1225 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ goto __pyx_L9; } /* "View.MemoryView":1228 * 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":1230 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1192 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1235 * * @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 = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1238 * 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, 1238, __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, 1238, __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, 1238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1238, __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":1237 * 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, 1237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1237, __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, 1237, __pyx_L1_error) /* "View.MemoryView":1235 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1241 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1242 * @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, 1242, __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, 1242, __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, 1242, __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); } } if (!__pyx_t_2) { __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1242, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[2] = {__pyx_t_2, __pyx_t_4}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1242, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[2] = {__pyx_t_2, __pyx_t_4}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1242, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else #endif { __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 1242, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1242, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 1242, __pyx_L1_error) /* "View.MemoryView":1241 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1245 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1246 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":1247 * 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, 1247, __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); } } if (!__pyx_t_5) { __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1247, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); } else { #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1247, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1247, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else #endif { __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 1247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(2, 1247, __pyx_L1_error) /* "View.MemoryView":1246 * @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":1249 * 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, 1249, __pyx_L1_error) } /* "View.MemoryView":1245 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1252 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { void *__pyx_v_tmpdata; size_t __pyx_v_itemsize; int __pyx_v_i; char __pyx_v_order; int __pyx_v_broadcasting; int __pyx_v_direct_copy; __Pyx_memviewslice __pyx_v_tmp; int __pyx_v_ndim; int __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; void *__pyx_t_6; int __pyx_t_7; /* "View.MemoryView":1260 * 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":1261 * """ * 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":1263 * 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":1264 * 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":1265 * 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":1268 * 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":1269 * * 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":1268 * 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":1270 * 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":1271 * 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":1270 * 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":1273 * 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":1275 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: */ __pyx_t_5 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1276 * * 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":1277 * 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":1278 * 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":1279 * 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":1277 * 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":1281 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ /*else*/ { __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(2, 1281, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":1276 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ } /* "View.MemoryView":1283 * _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":1284 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(2, 1284, __pyx_L1_error) /* "View.MemoryView":1283 * _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":1286 * _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":1288 * 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":1289 * * 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":1288 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ } /* "View.MemoryView":1291 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) __PYX_ERR(2, 1291, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_6; /* "View.MemoryView":1292 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; /* "View.MemoryView":1286 * _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":1294 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1297 * * * 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":1298 * * 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":1297 * * * 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":1299 * 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":1300 * 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":1299 * 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":1302 * 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":1304 * 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":1305 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) */ memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); /* "View.MemoryView":1306 * 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":1307 * 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":1308 * 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":1302 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ } /* "View.MemoryView":1294 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1310 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ __pyx_t_2 = (__pyx_v_order == 'F'); if (__pyx_t_2) { __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); } __pyx_t_7 = (__pyx_t_2 != 0); if (__pyx_t_7) { /* "View.MemoryView":1313 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) __PYX_ERR(2, 1313, __pyx_L1_error) /* "View.MemoryView":1314 * * transpose_memslice(&src) * transpose_memslice(&dst) # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) __PYX_ERR(2, 1314, __pyx_L1_error) /* "View.MemoryView":1310 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1316 * 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":1317 * * 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":1318 * 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":1320 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1321 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1252 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1324 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { int __pyx_v_i; int __pyx_v_offset; int __pyx_t_1; int __pyx_t_2; /* "View.MemoryView":1328 * 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":1330 * 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 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1331 * * 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":1332 * 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":1333 * 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":1335 * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] */ __pyx_t_1 = __pyx_v_offset; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1336 * * 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":1337 * 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":1338 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1324 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1346 * * @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":1350 * * * 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":1351 * * 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":1350 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ } /* "View.MemoryView":1346 * * @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":1355 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { __Pyx_RefNannyDeclarations #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1358 * 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":1355 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ /* function exit code */ __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1361 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1365 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1366 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_3) { /* "View.MemoryView":1367 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_3 = (__pyx_v_inc != 0); if (__pyx_t_3) { /* "View.MemoryView":1368 * 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":1367 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ goto __pyx_L6; } /* "View.MemoryView":1370 * 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":1366 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ goto __pyx_L5; } /* "View.MemoryView":1372 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ /*else*/ { /* "View.MemoryView":1373 * 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":1375 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1361 * * @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":1381 * * @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":1384 * 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":1385 * 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":1387 * _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":1381 * * @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":1391 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_extent; int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; /* "View.MemoryView":1395 * 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":1396 * 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":1398 * 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":1399 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1400 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); /* "View.MemoryView":1401 * 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":1398 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ goto __pyx_L3; } /* "View.MemoryView":1403 * 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; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1404 * 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":1406 * _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":1391 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ /* function exit code */ } static 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 PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_array___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->mode); Py_CLEAR(p->_format); (*Py_TYPE(o)->tp_free)(o); } static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_array___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { PyObject *v = PyObject_GenericGetAttr(o, n); if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); v = __pyx_array___getattr__(o, n); } return v; } static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { return __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}, {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 = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_array, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_array = { 0, /*mp_length*/ __pyx_array___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_array = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_array_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_array = { PyVarObject_HEAD_INIT(0, 0) "triplet_flow_loss.slow_flow_calculator_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 PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); Py_CLEAR(p->name); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { int e; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; if (p->name) { e = (*v)(p->name, a); if (e) return e; } return 0; } static int __pyx_tp_clear_Enum(PyObject *o) { PyObject* tmp; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; tmp = ((PyObject*)p->name); p->name = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyMethodDef __pyx_methods_Enum[] = { {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "triplet_flow_loss.slow_flow_calculator_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 PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryview___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->obj); Py_CLEAR(p->_size); Py_CLEAR(p->_array_interface); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; if (p->obj) { e = (*v)(p->obj, a); if (e) return e; } if (p->_size) { e = (*v)(p->_size, a); if (e) return e; } if (p->_array_interface) { e = (*v)(p->_array_interface, a); if (e) return e; } if (p->view.obj) { e = (*v)(p->view.obj, a); if (e) return e; } return 0; } static int __pyx_tp_clear_memoryview(PyObject *o) { PyObject* tmp; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; tmp = ((PyObject*)p->obj); p->obj = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_size); p->_size = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_array_interface); p->_array_interface = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); Py_CLEAR(p->view.obj); return 0; } static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_memoryview___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_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}, {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) "triplet_flow_loss.slow_flow_calculator_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 PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryviewslice___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->from_object); PyObject_GC_Track(o); __pyx_tp_dealloc_memoryview(o); } static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; if (p->from_object) { e = (*v)(p->from_object, a); if (e) return e; } return 0; } static int __pyx_tp_clear__memoryviewslice(PyObject *o) { PyObject* tmp; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; __pyx_tp_clear_memoryview(o); tmp = ((PyObject*)p->from_object); p->from_object = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); __PYX_XDEC_MEMVIEW(&p->from_slice, 1); return 0; } static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {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) "triplet_flow_loss.slow_flow_calculator_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 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "slow_flow_calculator_cython", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_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_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, {&__pyx_kp_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_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_array_equal, __pyx_k_array_equal, sizeof(__pyx_k_array_equal), 0, 0, 1, 1}, {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, {&__pyx_n_s_astype, __pyx_k_astype, sizeof(__pyx_k_astype), 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_compute_flow, __pyx_k_compute_flow, sizeof(__pyx_k_compute_flow), 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_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_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_feature_error_arr, __pyx_k_feature_error_arr, sizeof(__pyx_k_feature_error_arr), 0, 0, 1, 1}, {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, {&__pyx_kp_s_home_davidm_DA_RNN_DA_RNN_lib_t, __pyx_k_home_davidm_DA_RNN_DA_RNN_lib_t, sizeof(__pyx_k_home_davidm_DA_RNN_DA_RNN_lib_t), 0, 0, 1, 0}, {&__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_initialization, __pyx_k_initialization, sizeof(__pyx_k_initialization), 0, 0, 1, 1}, {&__pyx_n_s_int32, __pyx_k_int32, sizeof(__pyx_k_int32), 0, 0, 1, 1}, {&__pyx_n_s_interpolate, __pyx_k_interpolate, sizeof(__pyx_k_interpolate), 0, 0, 1, 1}, {&__pyx_n_s_interpolate_after, __pyx_k_interpolate_after, sizeof(__pyx_k_interpolate_after), 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_left_features, __pyx_k_left_features, sizeof(__pyx_k_left_features), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 0, 0, 1, 1}, {&__pyx_n_s_math, __pyx_k_math, sizeof(__pyx_k_math), 0, 0, 1, 1}, {&__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_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_neighborhood_len_import, __pyx_k_neighborhood_len_import, sizeof(__pyx_k_neighborhood_len_import), 0, 0, 1, 1}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_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_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_right_features, __pyx_k_right_features, sizeof(__pyx_k_right_features), 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_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_triplet_flow_loss_slow_flow_calc, __pyx_k_triplet_flow_loss_slow_flow_calc, sizeof(__pyx_k_triplet_flow_loss_slow_flow_calc), 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_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 74, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 218, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 799, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 989, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(2, 146, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(2, 149, __pyx_L1_error) __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(2, 396, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(2, 425, __pyx_L1_error) __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(2, 599, __pyx_L1_error) __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(2, 818, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":30 * interpolate = 0 * feature_error_arr = np.zeros([left_features.shape[0], left_features.shape[1]], dtype=np.float32) * assert np.array_equal(left_features.shape[:2], mask.shape) # <<<<<<<<<<<<<< * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) */ __pyx_slice_ = PySlice_New(Py_None, __pyx_int_2, Py_None); if (unlikely(!__pyx_slice_)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice_); __Pyx_GIVEREF(__pyx_slice_); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":32 * assert np.array_equal(left_features.shape[:2], mask.shape) * assert np.array_equal(left_features.shape, right_features.shape) * assert np.array_equal(left_features.shape[:2], initialization.shape[:2]) # <<<<<<<<<<<<<< * return compute_flow_helper(left_features.astype(np.float32), right_features.astype(np.float32), mask.astype(np.int32), * neighborhood_len_import, initialization.astype(np.float32), feature_error_arr, interpolate) */ __pyx_slice__2 = PySlice_New(Py_None, __pyx_int_2, Py_None); if (unlikely(!__pyx_slice__2)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__2); __Pyx_GIVEREF(__pyx_slice__2); __pyx_slice__3 = PySlice_New(Py_None, __pyx_int_2, Py_None); if (unlikely(!__pyx_slice__3)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__3); __Pyx_GIVEREF(__pyx_slice__3); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 * 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__6 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * * 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__7 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * 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__9 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":989 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":995 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); /* "../../../../../../usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); /* "View.MemoryView":131 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(2, 131, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "View.MemoryView":134 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(2, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__14); __Pyx_GIVEREF(__pyx_tuple__14); /* "View.MemoryView":137 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_tuple__15 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(2, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); /* "View.MemoryView":146 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(2, 146, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":174 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(2, 174, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__17); __Pyx_GIVEREF(__pyx_tuple__17); /* "View.MemoryView":190 * 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__18 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(2, 190, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "View.MemoryView":484 * 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__19 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(2, 484, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); /* "View.MemoryView":556 * 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__20 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(2, 556, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__20); __Pyx_GIVEREF(__pyx_tuple__20); /* "View.MemoryView":563 * 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__21 = PyTuple_New(1); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(2, 563, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__21); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__21, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__21); /* "View.MemoryView":668 * 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, 668, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__22); __Pyx_GIVEREF(__pyx_slice__22); /* "View.MemoryView":671 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ __pyx_slice__23 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__23)) __PYX_ERR(2, 671, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__23); __Pyx_GIVEREF(__pyx_slice__23); /* "View.MemoryView":682 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_slice__24 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__24)) __PYX_ERR(2, 682, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__24); __Pyx_GIVEREF(__pyx_slice__24); /* "View.MemoryView":689 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(2, 689, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":14 * * * def compute_flow(left_features, right_features, mask, initialization, neighborhood_len_import=6, interpolate_after=False): # <<<<<<<<<<<<<< * """ * Calculate optical flow using a nearest neighbor search. */ __pyx_tuple__26 = PyTuple_Pack(8, __pyx_n_s_left_features, __pyx_n_s_right_features, __pyx_n_s_mask, __pyx_n_s_initialization, __pyx_n_s_neighborhood_len_import, __pyx_n_s_interpolate_after, __pyx_n_s_interpolate, __pyx_n_s_feature_error_arr); 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(6, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_davidm_DA_RNN_DA_RNN_lib_t, __pyx_n_s_compute_flow, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 14, __pyx_L1_error) /* "View.MemoryView":282 * 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__28 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__28)) __PYX_ERR(2, 282, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__28); __Pyx_GIVEREF(__pyx_tuple__28); /* "View.MemoryView":283 * * 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_direct); if (unlikely(!__pyx_tuple__29)) __PYX_ERR(2, 283, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__29); __Pyx_GIVEREF(__pyx_tuple__29); /* "View.MemoryView":284 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__30)) __PYX_ERR(2, 284, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__30); __Pyx_GIVEREF(__pyx_tuple__30); /* "View.MemoryView":287 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__31)) __PYX_ERR(2, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__31); __Pyx_GIVEREF(__pyx_tuple__31); /* "View.MemoryView":288 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__32 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(2, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__32); __Pyx_GIVEREF(__pyx_tuple__32); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) __PYX_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_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_6 = PyInt_FromLong(6); if (unlikely(!__pyx_int_6)) __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; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initslow_flow_calculator_cython(void); /*proto*/ PyMODINIT_FUNC initslow_flow_calculator_cython(void) #else PyMODINIT_FUNC PyInit_slow_flow_calculator_cython(void); /*proto*/ PyMODINIT_FUNC PyInit_slow_flow_calculator_cython(void) #endif { PyObject *__pyx_t_1 = NULL; static PyThread_type_lock __pyx_t_2[8]; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_slow_flow_calculator_cython(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __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_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 PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("slow_flow_calculator_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) __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) #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_triplet_flow_loss__slow_flow_calculator_cython) { if (PyObject_SetAttrString(__pyx_m, "__name__", __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, "triplet_flow_loss.slow_flow_calculator_cython")) { if (unlikely(PyDict_SetItemString(modules, "triplet_flow_loss.slow_flow_calculator_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 init code ---*/ generic = Py_None; Py_INCREF(Py_None); strided = Py_None; Py_INCREF(Py_None); indirect = Py_None; Py_INCREF(Py_None); contiguous = Py_None; Py_INCREF(Py_None); indirect_contiguous = Py_None; Py_INCREF(Py_None); /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ __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, 103, __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, 103, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 275, __pyx_L1_error) __pyx_type___pyx_MemviewEnum.tp_print = 0; __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 326, __pyx_L1_error) __pyx_type___pyx_memoryview.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(2, 326, __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, 951, __pyx_L1_error) __pyx_type___pyx_memoryviewslice.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(2, 951, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(3, 9, __pyx_L1_error) __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) __PYX_ERR(1, 155, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) __PYX_ERR(1, 168, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) __PYX_ERR(1, 172, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) __PYX_ERR(1, 181, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) __PYX_ERR(1, 861, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":6 * # cython: cdivision=True * * import math # <<<<<<<<<<<<<< * cimport cython * import numpy as np */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_math, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_math, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":8 * import math * cimport cython * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * from libc.math cimport sqrt, fabs */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":14 * * * def compute_flow(left_features, right_features, mask, initialization, neighborhood_len_import=6, interpolate_after=False): # <<<<<<<<<<<<<< * """ * Calculate optical flow using a nearest neighbor search. */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_17triplet_flow_loss_27slow_flow_calculator_cython_1compute_flow, NULL, __pyx_n_s_triplet_flow_loss_slow_flow_calc); 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_compute_flow, __pyx_t_1) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "triplet_flow_loss/slow_flow_calculator_cython.pyx":1 * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION # <<<<<<<<<<<<<< * # distutils: extra_compile_args = -fopenmp * # distutils: extra_link_args = -fopenmp */ __pyx_t_1 = PyDict_New(); 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":207 * 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, 207, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 207, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":282 * 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__28, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 282, __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":283 * * 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(2, 283, __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":284 * 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__30, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 284, __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":287 * * * 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(2, 287, __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":288 * * 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__32, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 288, __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":312 * * 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":313 * 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_2[0] = PyThread_allocate_lock(); __pyx_t_2[1] = PyThread_allocate_lock(); __pyx_t_2[2] = PyThread_allocate_lock(); __pyx_t_2[3] = PyThread_allocate_lock(); __pyx_t_2[4] = PyThread_allocate_lock(); __pyx_t_2[5] = PyThread_allocate_lock(); __pyx_t_2[6] = PyThread_allocate_lock(); __pyx_t_2[7] = PyThread_allocate_lock(); memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); /* "View.MemoryView":535 * 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, 535, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 535, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":981 * 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, 981, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 981, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "View.MemoryView":1391 * * @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: */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init triplet_flow_loss.slow_flow_calculator_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init triplet_flow_loss.slow_flow_calculator_cython"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #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((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* 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 */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS result = PyDict_GetItem(__pyx_d, name); if (likely(result)) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } /* GetItemInt */ static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, 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((n >= 0) & (n < PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) 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)); } /* 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 /* 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; } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL #include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = PyThreadState_GET(); 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 = f->f_localsplus; 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 // CPython < 3.6 #endif // CYTHON_FAST_PYCALL /* 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); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))); 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()); return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs, NULL); } #endif // CYTHON_FAST_PYCCALL /* 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 #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #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 /* 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(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFormatCheck */ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } /* 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; } static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { va_list vargs; char msg[200]; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); Py_FatalError(msg); va_end(vargs); } static CYTHON_INLINE int __pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)++; PyThread_release_lock(lock); return result; } static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)--; PyThread_release_lock(lock); return result; } static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int first_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview || (PyObject *) memview == Py_None) return; if (__pyx_get_slice_count(memview) < 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); first_time = __pyx_add_acquisition_count(memview) == 0; if (first_time) { if (have_gil) { Py_INCREF((PyObject *) memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_INCREF((PyObject *) memview); PyGILState_Release(_gilstate); } } } static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int last_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview ) { return; } else if ((PyObject *) memview == Py_None) { memslice->memview = NULL; return; } if (__pyx_get_slice_count(memview) <= 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); last_time = __pyx_sub_acquisition_count(memview) == 1; memslice->data = NULL; if (last_time) { if (have_gil) { Py_CLEAR(memslice->memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_CLEAR(memslice->memview); PyGILState_Release(_gilstate); } } else { memslice->memview = NULL; } } /* 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 /* 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 PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* 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"); } /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; 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; tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE 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; return 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 tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* ArgTypeTest */ static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } /* 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 = 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; } kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } /* GetAttr */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_COMPILING_IN_CPYTHON #if PY_MAJOR_VERSION >= 3 if (likely(PyUnicode_Check(n))) #else if (likely(PyString_Check(n))) #endif return __Pyx_PyObject_GetAttrStr(o, n); #endif return PyObject_GetAttr(o, n); } /* 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); } } /* 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; 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; *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_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* 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 } 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 } 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 } 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 } 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 } 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 } 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); } /* 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 } /* 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; } /* 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; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __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 (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } Py_DECREF(obj); view->obj = NULL; } #endif /* 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; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (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); } } /* 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;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (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); } } /* MemviewDtypeToObject */ static CYTHON_INLINE PyObject *__pyx_memview_get_float(const char *itemp) { return (PyObject *) PyFloat_FromDouble(*(float *) itemp); } static CYTHON_INLINE int __pyx_memview_set_float(const char *itemp, PyObject *obj) { float value = __pyx_PyFloat_AsFloat(obj); if ((value == (float)-1) && PyErr_Occurred()) return 0; *(float *) 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) -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) -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 char __Pyx_PyInt_As_char(PyObject *x) { const char neg_one = (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; } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (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; } /* 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_dsdsds_float(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__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, 3, &__Pyx_TypeInfo_float, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_int(PyObject *obj) { __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, 2, &__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_dsds_float(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__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, 2, &__Pyx_TypeInfo_float, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* 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; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #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; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (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 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 (PyInt_Check(x) || PyLong_Check(x)) #else if (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 = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif #else res = PyNumber_Int(x); #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #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_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
blurtwo.c
#include <stdlib.h> #include "blurtwo.h" void blurtwo(float* v,int M,int N,float*output){ float* tmp2 = (float*) calloc(1,((N + 1 + 1 + 0)) * (M) * sizeof (float)); for (int H7 = 0; H7 < (N + 1 + 1 + 0); H7++) { for (int H8 = 0; H8 < M; H8++) { if (0 <= H7 - (1) && H7 - (1) < N) { float tmp3 = 0; float tmp4 = 0; if (0 <= H8 - (1)) { tmp4 = v[(((M)) * (H7 - (1))) + H8 - (1)]; } float tmp5 = 0; tmp5 = v[(((M)) * (H7 - (1))) + H8]; tmp3 = tmp4 + tmp5; float tmp6 = 0; if (H8 + 1 < M) { tmp6 = v[(((M)) * (H7 - (1))) + H8 + 1]; } tmp2[(M) * (H7) + H8] = tmp3 + tmp6; } } } float* x0 = tmp2; #pragma omp parallel for for (int H10 = 0; H10 < N; H10++) { for (int H11 = 0; H11 < M; H11++) { float tmp7 = 0; float tmp8 = 0; tmp8 = x0[(((M)) * (H10)) + H11]; float tmp9 = 0; tmp9 = x0[(((M)) * (H10 + 1)) + H11]; tmp7 = tmp8 + tmp9; float tmp10 = 0; tmp10 = x0[(((M)) * (H10 + 2)) + H11]; output[(M) * (H10) + H11] = tmp7 + tmp10; } } free(tmp2); }
truedepscalar-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // loop carried true dep between tmp =.. and ..= tmp. #include <stdlib.h> int main(int argc, char* argv[]) { int i; int tmp; tmp = 10; int len=100; if (argc>1) len = atoi(argv[1]); int a[len]; #pragma omp parallel for for (i=0;i<len;i++) { a[i] = tmp; tmp =a[i]+i; } return 0; }
parallel_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Denis Demidov // Philipp Bucher (https://github.com/philbucher) // #if !defined(KRATOS_PARALLEL_UTILITIES_H_INCLUDED) #define KRATOS_PARALLEL_UTILITIES_H_INCLUDED // System includes #include <iostream> #include <array> #include <vector> #include <tuple> #include <cmath> #include <limits> #include <future> #include <thread> #include <mutex> // External includes #ifdef KRATOS_SMP_OPENMP #include <omp.h> #endif // Project includes #include "includes/define.h" #include "includes/global_variables.h" #include "includes/lock_object.h" #define KRATOS_PREPARE_CATCH_THREAD_EXCEPTION std::stringstream err_stream; #define KRATOS_CATCH_THREAD_EXCEPTION \ } catch(Exception& e) { \ const std::lock_guard<LockObject> scope_lock(ParallelUtilities::GetGlobalLock()); \ err_stream << "Thread #" << i << " caught exception: " << e.what(); \ } catch(std::exception& e) { \ const std::lock_guard<LockObject> scope_lock(ParallelUtilities::GetGlobalLock()); \ err_stream << "Thread #" << i << " caught exception: " << e.what(); \ } catch(...) { \ const std::lock_guard<LockObject> scope_lock(ParallelUtilities::GetGlobalLock()); \ err_stream << "Thread #" << i << " caught unknown exception:"; \ } #define KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION \ const std::string& err_msg = err_stream.str(); \ KRATOS_ERROR_IF_NOT(err_msg.empty()) << "The following errors occured in a parallel region!\n" << err_msg << std::endl; namespace Kratos { ///@addtogroup KratosCore /// Shared memory parallelism related helper class /** Provides access to functionalities for shared memory parallelism * such as the number of threads in usa. */ class KRATOS_API(KRATOS_CORE) ParallelUtilities { public: ///@name Life Cycle ///@{ ///@} ///@name Operations ///@{ /** @brief Returns the current number of threads * @return number of threads */ static int GetNumThreads(); /** @brief Sets the current number of threads * @param NumThreads - the number of threads to be used */ static void SetNumThreads(const int NumThreads); /** @brief Returns the number of processors available to this device * This can include the multiple threads per processing unit * @return number of processors */ static int GetNumProcs(); ///@} /** @brief Returns the global lock * Global lock that can be used for critical sections * @return global lock */ static LockObject& GetGlobalLock(); ///@} private: ///@name Static Member Variables ///@{ static LockObject* mspGlobalLock; static int* mspNumThreads; ///@} ///@name Private Operations ///@{ /// Default constructor. ParallelUtilities() = delete; /** @brief Initializes the number of threads to be used. * @return number of threads */ static int InitializeNumberOfThreads(); ///@} ///@name Private Access ///@{ static int& GetNumberOfThreads(); ///@} }; // Class ParallelUtilities //*********************************************************************************** //*********************************************************************************** //*********************************************************************************** /** @param TContainerType - the type of the container used in the loop (must provide random access iterators) * @param TIteratorType - type of iterator (by default as provided by the TContainerType) * @param TMaxThreads - maximum number of threads allowed in the partitioning. * must be known at compile time to avoid heap allocations in the partitioning */ template< class TContainerType, class TIteratorType=decltype(std::declval<TContainerType>().begin()), int TMaxThreads=Globals::MaxAllowedThreads > class BlockPartition { public: /** @param it_begin - iterator pointing at the beginning of the container * @param it_end - iterator pointing to the end of the container * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ BlockPartition(TIteratorType it_begin, TIteratorType it_end, int Nchunks = ParallelUtilities::GetNumThreads()) { KRATOS_ERROR_IF(Nchunks < 1) << "Number of chunks must be > 0 (and not " << Nchunks << ")" << std::endl; const std::ptrdiff_t size_container = it_end-it_begin; if (size_container == 0) { mNchunks = Nchunks; } else { // in case the container is smaller than the number of chunks mNchunks = std::min(static_cast<int>(size_container), Nchunks); } const std::ptrdiff_t block_partition_size = size_container / mNchunks; mBlockPartition[0] = it_begin; mBlockPartition[mNchunks] = it_end; for (int i=1; i<mNchunks; i++) { mBlockPartition[i] = mBlockPartition[i-1] + block_partition_size; } } /** @param rData - the continer to be iterated upon * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ template <class TData> BlockPartition(TData &&rData, int Nchunks = ParallelUtilities::GetNumThreads()) : BlockPartition(rData.begin(), rData.end(), Nchunks) {} virtual ~BlockPartition() = default; /** @brief simple iteration loop. f called on every entry in rData * @param f - must be a unary function accepting as input TContainerType::value_type& */ template <class TUnaryFunction> inline void for_each(TUnaryFunction&& f) { KRATOS_PREPARE_CATCH_THREAD_EXCEPTION #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { f(*it); //note that we pass the value to the function, not the iterator } KRATOS_CATCH_THREAD_EXCEPTION } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION } /** @brief loop allowing reductions. f called on every entry in rData * the function f needs to return the values to be used by the reducer * @param TReducer template parameter specifying the reduction operation to be done * @param f - must be a unary function accepting as input TContainerType::value_type& */ template <class TReducer, class TUnaryFunction> inline typename TReducer::return_type for_each(TUnaryFunction &&f) { KRATOS_PREPARE_CATCH_THREAD_EXCEPTION TReducer global_reducer; #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY TReducer local_reducer; for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { local_reducer.LocalReduce(f(*it)); } global_reducer.ThreadSafeReduce(local_reducer); KRATOS_CATCH_THREAD_EXCEPTION } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION return global_reducer.GetValue(); } /** @brief loop with thread local storage (TLS). f called on every entry in rData * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TThreadLocalStorage, class TFunction> inline void for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); KRATOS_PREPARE_CATCH_THREAD_EXCEPTION #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for(int i=0; i<mNchunks; ++i){ KRATOS_TRY for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it){ f(*it, thread_local_storage); // note that we pass the value to the function, not the iterator } KRATOS_CATCH_THREAD_EXCEPTION } } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION } /** @brief loop with thread local storage (TLS) allowing reductions. f called on every entry in rData * the function f needs to return the values to be used by the reducer * @param TReducer template parameter specifying the reduction operation to be done * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TReducer, class TThreadLocalStorage, class TFunction> inline typename TReducer::return_type for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); KRATOS_PREPARE_CATCH_THREAD_EXCEPTION TReducer global_reducer; #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY TReducer local_reducer; for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { local_reducer.LocalReduce(f(*it, thread_local_storage)); } global_reducer.ThreadSafeReduce(local_reducer); KRATOS_CATCH_THREAD_EXCEPTION } } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION return global_reducer.GetValue(); } private: int mNchunks; std::array<TIteratorType, TMaxThreads> mBlockPartition; }; /** @brief simplified version of the basic loop (without reduction) to enable template type deduction * @param v - containers to be looped upon * @param func - must be a unary function accepting as input TContainerType::value_type& */ template <class TContainerType, class TFunctionType> void block_for_each(TContainerType &&v, TFunctionType &&func) { BlockPartition<TContainerType>(v.begin(), v.end()).for_each(std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with reduction to enable template type deduction * @param v - containers to be looped upon * @param func - must be a unary function accepting as input TContainerType::value_type& */ template <class TReducer, class TContainerType, class TFunctionType> typename TReducer::return_type block_for_each(TContainerType &&v, TFunctionType &&func) { return BlockPartition<TContainerType>(v.begin(), v.end()).template for_each<TReducer>(std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with thread local storage (TLS) to enable template type deduction * @param v - containers to be looped upon * @param tls - thread local storage * @param func - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TContainerType, class TThreadLocalStorage, class TFunctionType> void block_for_each(TContainerType &&v, const TThreadLocalStorage& tls, TFunctionType &&func) { BlockPartition<TContainerType>(v.begin(), v.end()).for_each(tls, std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with reduction and thread local storage (TLS) to enable template type deduction * @param v - containers to be looped upon * @param tls - thread local storage * @param func - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TReducer, class TContainerType, class TThreadLocalStorage, class TFunctionType> typename TReducer::return_type block_for_each(TContainerType &&v, const TThreadLocalStorage& tls, TFunctionType &&func) { return BlockPartition<TContainerType>(v.begin(), v.end()).template for_each<TReducer>(tls, std::forward<TFunctionType>(func)); } //*********************************************************************************** //*********************************************************************************** //*********************************************************************************** /** @brief This class is useful for index iteration over containers * @param TIndexType type of index to be used in the loop * @param TMaxThreads - maximum number of threads allowed in the partitioning. * must be known at compile time to avoid heap allocations in the partitioning */ template<class TIndexType=std::size_t, int TMaxThreads=Globals::MaxAllowedThreads> class IndexPartition { public: /** @brief constructor using the size of the partition to be used * @param Size - the size of the partition * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ IndexPartition(TIndexType Size, int Nchunks = ParallelUtilities::GetNumThreads()) { KRATOS_ERROR_IF(Nchunks < 1) << "Number of chunks must be > 0 (and not " << Nchunks << ")" << std::endl; if (Size == 0) { mNchunks = Nchunks; } else { // in case the container is smaller than the number of chunks mNchunks = std::min(static_cast<int>(Size), Nchunks); } const int block_partition_size = Size / mNchunks; mBlockPartition[0] = 0; mBlockPartition[mNchunks] = Size; for (int i=1; i<mNchunks; i++) { mBlockPartition[i] = mBlockPartition[i-1] + block_partition_size; } } virtual ~IndexPartition() = default; //NOT COMMENTING IN DOXYGEN - THIS SHOULD BE SORT OF HIDDEN UNTIL GIVEN PRIME TIME //pure c++11 version (can handle exceptions) template <class TUnaryFunction> inline void for_pure_c11(TUnaryFunction &&f) { std::vector< std::future<void> > runners(mNchunks); const auto& partition = mBlockPartition; for (int i=0; i<mNchunks; ++i) { runners[i] = std::async(std::launch::async, [&partition, i, &f]() { for (auto k = partition[i]; k < partition[i+1]; ++k) { f(k); } }); } //here we impose a syncronization and we check the exceptions for(int i=0; i<mNchunks; ++i) { try { runners[i].get(); } catch(Exception& e) { KRATOS_ERROR << std::endl << "THREAD number: " << i << " caught exception " << e.what() << std::endl; } catch(std::exception& e) { KRATOS_ERROR << std::endl << "THREAD number: " << i << " caught exception " << e.what() << std::endl; } catch(...) { KRATOS_ERROR << std::endl << "unknown error" << std::endl; } } } /** simple version of for_each (no reduction) to be called for each index in the partition * @param f - must be a unary function accepting as input IndexType */ template <class TUnaryFunction> inline void for_each(TUnaryFunction &&f) { KRATOS_PREPARE_CATCH_THREAD_EXCEPTION #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { f(k); //note that we pass a reference to the value, not the iterator } KRATOS_CATCH_THREAD_EXCEPTION } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION } /** version with reduction to be called for each index in the partition * function f is expected to return the values to be reduced * @param TReducer - template parameter specifying the type of reducer to be applied * @param f - must be a unary function accepting as input IndexType */ template <class TReducer, class TUnaryFunction> inline typename TReducer::return_type for_each(TUnaryFunction &&f) { KRATOS_PREPARE_CATCH_THREAD_EXCEPTION TReducer global_reducer; #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY TReducer local_reducer; for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { local_reducer.LocalReduce(f(k)); } global_reducer.ThreadSafeReduce(local_reducer); KRATOS_CATCH_THREAD_EXCEPTION } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION return global_reducer.GetValue(); } /** @brief loop with thread local storage (TLS). f called on every entry in rData * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input IndexType and the thread local storage */ template <class TThreadLocalStorage, class TFunction> inline void for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); KRATOS_PREPARE_CATCH_THREAD_EXCEPTION #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { f(k, thread_local_storage); //note that we pass a reference to the value, not the iterator } KRATOS_CATCH_THREAD_EXCEPTION } } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION } /** version with reduction and thread local storage (TLS) to be called for each index in the partition * function f is expected to return the values to be reduced * @param TReducer - template parameter specifying the type of reducer to be applied * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input IndexType and the thread local storage */ template <class TReducer, class TThreadLocalStorage, class TFunction> inline typename TReducer::return_type for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); KRATOS_PREPARE_CATCH_THREAD_EXCEPTION TReducer global_reducer; #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { KRATOS_TRY TReducer local_reducer; for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { local_reducer.LocalReduce(f(k, thread_local_storage)); } global_reducer.ThreadSafeReduce(local_reducer); KRATOS_CATCH_THREAD_EXCEPTION } } KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION return global_reducer.GetValue(); } private: int mNchunks; std::array<TIndexType, TMaxThreads> mBlockPartition; }; } // namespace Kratos. #undef KRATOS_PREPARE_CATCH_THREAD_EXCEPTION #undef KRATOS_CATCH_THREAD_EXCEPTION #undef KRATOS_CHECK_AND_THROW_THREAD_EXCEPTION #endif // KRATOS_PARALLEL_UTILITIES_H_INCLUDED defined
omp_for_schedule_static.c
<ompts:test> <ompts:testdescription>Test which checks the static option of the omp for schedule directive.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp for schedule(static)</ompts:directive> <ompts:dependences>omp for nowait,omp flush,omp critical,omp single</ompts:dependences> <ompts:testcode> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "omp_testsuite.h" #include "omp_my_sleep.h" #define NUMBER_OF_THREADS 10 #define CFSMAX_SIZE 1000 #define MAX_TIME 0.01 #ifdef SLEEPTIME #undef SLEEPTIME #define SLEEPTIME 0.0005 #endif int <ompts:testcode:functionname>omp_for_schedule_static</ompts:testcode:functionname> (FILE * logFile) { int threads; int i,lasttid; <ompts:orphan:vars> int * tids; int notout; int maxiter; int chunk_size; </ompts:orphan:vars> int counter = 0; int tmp_count=1; int lastthreadsstarttid = -1; int result = 1; chunk_size = 7; tids = (int *) malloc (sizeof (int) * (CFSMAX_SIZE + 1)); notout = 1; maxiter = 0; #pragma omp parallel shared(tids,counter) { /* begin of parallel*/ #pragma omp single { threads = omp_get_num_threads (); } /* end of single */ } /* end of parallel */ if (threads < 2) { printf ("This test only works with at least two threads"); fprintf (logFile,"This test only works with at least two threads"); return 0; } else { fprintf (logFile,"Using an internal count of %d\nUsing a specified chunksize of %d\n", CFSMAX_SIZE, chunk_size); tids[CFSMAX_SIZE] = -1; /* setting endflag */ #pragma omp parallel shared(tids) { /* begin of parallel */ <ompts:orphan> double count; int tid; int j; tid = omp_get_thread_num (); #pragma omp for nowait <ompts:check>schedule(static,chunk_size)</ompts:check> for(j = 0; j < CFSMAX_SIZE; ++j) { count = 0.; #pragma omp flush(maxiter) if (j > maxiter) { #pragma omp critical { maxiter = j; } /* end of critical */ } /*printf ("thread %d sleeping\n", tid);*/ while (notout && (count < MAX_TIME) && (maxiter == j)) { #pragma omp flush(maxiter,notout) my_sleep (SLEEPTIME); count += SLEEPTIME; printf("."); } #ifdef VERBOSE if (count > 0.) printf(" waited %lf s\n", count); #endif /*printf ("thread %d awake\n", tid);*/ tids[j] = tid; #ifdef VERBOSE printf("%d finished by %d\n",j,tid); #endif } /* end of for */ notout = 0; #pragma omp flush(maxiter,notout) </ompts:orphan> } /* end of parallel */ /**** analysing the data in array tids ****/ lasttid = tids[0]; tmp_count = 0; for (i = 0; i < CFSMAX_SIZE + 1; ++i) { /* If the work was done by the same thread increase tmp_count by one. */ if (tids[i] == lasttid) { tmp_count++; #ifdef VERBOSE fprintf (logFile, "%d: %d \n", i, tids[i]); #endif continue; } /* Check if the next thread had has the right thread number. When finding * threadnumber -1 the end should be reached. */ if (tids[i] == (lasttid + 1) % threads || tids[i] == -1) { /* checking for the right chunk size */ if (tmp_count == chunk_size) { tmp_count = 1; lasttid = tids[i]; #ifdef VERBOSE fprintf (logFile, "OK\n"); #endif } /* If the chunk size was wrong, check if the end was reached */ else { if (tids[i] == -1) { if (i == CFSMAX_SIZE) { fprintf (logFile, "Last thread had chunk size %d\n", tmp_count); break; } else { fprintf (logFile, "ERROR: Last thread (thread with number -1) was found before the end.\n"); result = 0; } } else { fprintf (logFile, "ERROR: chunk size was %d. (assigned was %d)\n", tmp_count, chunk_size); result = 0; } } } else { fprintf(logFile, "ERROR: Found thread with number %d (should be inbetween 0 and %d).", tids[i], threads - 1); result = 0; } #ifdef VERBOSE fprintf (logFile, "%d: %d \n", i, tids[i]); #endif } } return result; } </ompts:testcode> </ompts:test>
data.h
/*! * Copyright (c) 2015 by Contributors * \file data.h * \brief The input data structure of xgboost. * \author Tianqi Chen */ #ifndef XGBOOST_DATA_H_ #define XGBOOST_DATA_H_ #include <dmlc/base.h> #include <dmlc/data.h> #include <rabit/rabit.h> #include <xgboost/base.h> #include <xgboost/span.h> #include <xgboost/host_device_vector.h> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <utility> #include <vector> namespace xgboost { // forward declare learner. class LearnerImpl; // forward declare dmatrix. class DMatrix; /*! \brief data type accepted by xgboost interface */ enum DataType { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4 }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of rows in the data */ uint64_t num_row_{0}; /*! \brief number of columns in the data */ uint64_t num_col_{0}; /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; /*! * \brief specified root index of each instance, * can be used for multi task setting */ std::vector<bst_uint> root_index_; /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_uint> group_ptr_; /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; /*! * \brief initialized margins, * if specified, xgboost will start from this init margin * can be used to specify initial prediction to boost from. */ HostDeviceVector<bst_float> base_margin_; /*! \brief default constructor */ MetaInfo() = default; /*! * \brief Get weight of each instances. * \param i Instance index. * \return The weight. */ inline bst_float GetWeight(size_t i) const { return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f; } /*! * \brief Get the root index of i-th instance. * \param i Instance index. * \return The pre-defined root index of i-th instance. */ inline unsigned GetRoot(size_t i) const { return !root_index_.empty() ? root_index_[i] : 0U; } /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */ inline const std::vector<size_t>& LabelAbsSort() const { if (label_order_cache_.size() == labels_.Size()) { return label_order_cache_; } label_order_cache_.resize(labels_.Size()); std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0); const auto& l = labels_.HostVector(); XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(), [&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);}); return label_order_cache_; } /*! \brief clear all the information */ void Clear(); /*! * \brief Load the Meta info from binary stream. * \param fi The input stream */ void LoadBinary(dmlc::Stream* fi); /*! * \brief Save the Meta info to binary stream * \param fo The output stream. */ void SaveBinary(dmlc::Stream* fo) const; /*! * \brief Set information in the meta info. * \param key The key of the information. * \param dptr The data pointer of the source array. * \param dtype The type of the source data. * \param num Number of elements in the source array. */ void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num); /*! * \brief Set information in the meta info with array interface. * \param key The key of the information. * \param interface_str String representation of json format array interface. * * [ column_0, column_1, ... column_n ] * * Right now only 1 column is permitted. */ void SetInfo(const char* key, std::string const& interface_str); private: /*! \brief argsort of labels */ mutable std::vector<size_t> label_order_cache_; }; /*! \brief Element from a sparse vector */ struct Entry { /*! \brief feature index */ bst_uint index; /*! \brief feature value */ bst_float fvalue; /*! \brief default constructor */ Entry() = default; /*! * \brief constructor with index and value * \param index The feature or row index. * \param fvalue The feature value. */ Entry(bst_uint index, bst_float fvalue) : index(index), fvalue(fvalue) {} /*! \brief reversely compare feature values */ inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; } inline bool operator==(const Entry& other) const { return (this->index == other.index && this->fvalue == other.fvalue); } }; /*! * \brief Parameters for constructing batches. */ struct BatchParam { /*! \brief The GPU device to use. */ int gpu_id; /*! \brief Maximum number of bins per feature for histograms. */ int max_bin; /*! \brief Number of rows in a GPU batch, used for finding quantiles on GPU. */ int gpu_batch_nrows; }; /*! * \brief In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<size_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid{}; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; /*! \brief get i-th row from the batch */ inline Inst operator[](size_t i) const { const auto& data_vec = data.HostVector(); const auto& offset_vec = offset.HostVector(); size_t size; // in distributed mode, some partitions may not get any instance for a feature. Therefore // we should set the size as zero if (rabit::IsDistributed() && i + 1 >= offset_vec.size()) { size = 0; } else { size = offset_vec[i + 1] - offset_vec[i]; } return {data_vec.data() + offset_vec[i], static_cast<Inst::index_type>(size)}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return Number of instances in the page. */ inline size_t Size() const { return offset.Size() - 1; } /*! \return estimation of memory cost of this page */ inline size_t MemCostBytes() const { return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry); } /*! \brief clear the page */ inline void Clear() { base_rowid = 0; auto& offset_vec = offset.HostVector(); offset_vec.clear(); offset_vec.push_back(0); data.HostVector().clear(); } /*! \brief Set the base row id for this page. */ inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; } SparsePage GetTranspose(int num_columns) const; void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); #pragma omp parallel for default(none) shared(ncol) schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) { std::sort( this->data.HostVector().begin() + this->offset.HostVector()[i], this->data.HostVector().begin() + this->offset.HostVector()[i + 1], Entry::CmpValue); } } } /*! * \brief Push row block into the page. * \param batch the row batch. */ void Push(const dmlc::RowBlock<uint32_t>& batch); /*! * \brief Push a sparse page * \param batch the row page */ void Push(const SparsePage &batch); /*! * \brief Push a SparsePage stored in CSC format * \param batch The row batch to be pushed */ void PushCSC(const SparsePage& batch); }; class CSCPage: public SparsePage { public: CSCPage() : SparsePage() {} explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class SortedCSCPage : public SparsePage { public: SortedCSCPage() : SparsePage() {} explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class EllpackPageImpl; /*! * \brief A page stored in ELLPACK format. * * This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid * including CUDA-specific implementation details in the header. */ class EllpackPage { public: /*! * \brief Default constructor. * * This is used in the external memory case. An empty ELLPACK page is constructed with its content * set later by the reader. */ EllpackPage(); /*! * \brief Constructor from an existing DMatrix. * * This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix * in CSR format. */ explicit EllpackPage(DMatrix* dmat, const BatchParam& param); /*! \brief Destructor. */ ~EllpackPage(); /*! \return Number of instances in the page. */ size_t Size() const; /*! \brief Set the base row id for this page. */ void SetBaseRowId(size_t row_id); const EllpackPageImpl* Impl() const { return impl_.get(); } EllpackPageImpl* Impl() { return impl_.get(); } private: std::unique_ptr<EllpackPageImpl> impl_; }; template<typename T> class BatchIteratorImpl { public: virtual ~BatchIteratorImpl() = default; virtual T& operator*() = 0; virtual const T& operator*() const = 0; virtual void operator++() = 0; virtual bool AtEnd() const = 0; }; template<typename T> class BatchIterator { public: using iterator_category = std::forward_iterator_tag; explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); } void operator++() { CHECK(impl_ != nullptr); ++(*impl_); } T& operator*() { CHECK(impl_ != nullptr); return *(*impl_); } const T& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator& rhs) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } private: std::shared_ptr<BatchIteratorImpl<T>> impl_; }; template<typename T> class BatchSet { public: explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(begin_iter) {} BatchIterator<T> begin() { return begin_iter_; } BatchIterator<T> end() { return BatchIterator<T>(nullptr); } private: BatchIterator<T> begin_iter_; }; /*! * \brief This is data structure that user can pass to DMatrix::Create * to create a DMatrix for training, user can create this data structure * for customized Data Loading on single machine. * * On distributed setting, usually an customized dmlc::Parser is needed instead. */ template<typename T> class DataSource : public dmlc::DataIter<T> { public: /*! * \brief Meta information about the dataset * The subclass need to be able to load this correctly from data. */ MetaInfo info; }; /*! * \brief Internal data structured used by XGBoost during training. * There are two ways to create a customized DMatrix that reads in user defined-format. * * - Provide a dmlc::Parser and pass into the DMatrix::Create * - Alternatively, if data can be represented by an URL, define a new dmlc::Parser and register by * DMLC_REGISTER_DATA_PARSER; * - This works best for user defined data input source, such as data-base, filesystem. * - Provide a DataSource, that can be passed to DMatrix::Create * This can be used to re-use inmemory data structure into DMatrix. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /** * \brief Gets batches. Use range based for loop over BatchSet to access individual batches. */ template<typename T> BatchSet<T> GetBatches(const BatchParam& param = {}); // the following are column meta data, should be able to answer them fast. /*! \return Whether the data columns single column block. */ virtual bool SingleColBlock() const = 0; /*! \brief get column density */ virtual float GetColDensity(size_t cidx) = 0; /*! \brief virtual destructor */ virtual ~DMatrix() = default; /*! * \brief Save DMatrix to local file. * The saved file only works for non-sharded dataset(single machine training). * This API is deprecated and dis-encouraged to use. * \param fname The file name to be saved. * \return The created DMatrix. */ virtual void SaveToLocalFile(const std::string& fname); /*! \brief Whether the matrix is dense. */ bool IsDense() const { return Info().num_nonzero_ == Info().num_row_ * Info().num_col_; } /*! * \brief Load DMatrix from URI. * \param uri The URI of input. * \param silent Whether print information during loading. * \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode. * \param file_format The format type of the file, used for dmlc::Parser::Create. * By default "auto" will be able to load in both local binary file. * \param page_size Page size for external memory. * \return The created DMatrix. */ static DMatrix* Load(const std::string& uri, bool silent, bool load_row_split, const std::string& file_format = "auto", size_t page_size = kPageSize); /*! * \brief create a new DMatrix, by wrapping a row_iterator, and meta info. * \param source The source iterator of the data, the create function takes ownership of the source. * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \return a Created DMatrix. */ static DMatrix* Create(std::unique_ptr<DataSource<SparsePage>>&& source, const std::string& cache_prefix = ""); /*! * \brief Create a DMatrix by loading data from parser. * Parser can later be deleted after the DMatrix i created. * \param parser The input data parser * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \param page_size Page size for external memory. * \sa dmlc::Parser * \note dmlc-core provides efficient distributed data parser for libsvm format. * User can create and register customized parser to load their own format using DMLC_REGISTER_DATA_PARSER. * See "dmlc-core/include/dmlc/data.h" for detail. * \return A created DMatrix. */ static DMatrix* Create(dmlc::Parser<uint32_t>* parser, const std::string& cache_prefix = "", size_t page_size = kPageSize); /*! \brief page size 32 MB */ static const size_t kPageSize = 32UL << 20UL; protected: virtual BatchSet<SparsePage> GetRowBatches() = 0; virtual BatchSet<CSCPage> GetColumnBatches() = 0; virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0; virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0; }; template<> inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) { return GetRowBatches(); } template<> inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) { return GetColumnBatches(); } template<> inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) { return GetSortedColumnBatches(); } template<> inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) { return GetEllpackBatches(param); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); } #endif // XGBOOST_DATA_H_
munit.c
/* Copyright (c) 2013-2018 Evan Nemerson <evan@nemerson.com> * * 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. */ /*** Configuration ***/ /* This is just where the output from the test goes. It's really just * meant to let you choose stdout or stderr, but if anyone really want * to direct it to a file let me know, it would be fairly easy to * support. */ #if !defined(MUNIT_OUTPUT_FILE) # define MUNIT_OUTPUT_FILE stdout #endif /* This is a bit more useful; it tells µnit how to format the seconds in * timed tests. If your tests run for longer you might want to reduce * it, and if your computer is really fast and your tests are tiny you * can increase it. */ #if !defined(MUNIT_TEST_TIME_FORMAT) # define MUNIT_TEST_TIME_FORMAT "0.8f" #endif /* If you have long test names you might want to consider bumping * this. The result information takes 43 characters. */ #if !defined(MUNIT_TEST_NAME_LEN) # define MUNIT_TEST_NAME_LEN 37 #endif /* If you don't like the timing information, you can disable it by * defining MUNIT_DISABLE_TIMING. */ #if !defined(MUNIT_DISABLE_TIMING) # define MUNIT_ENABLE_TIMING #endif /*** End configuration ***/ #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L) # undef _POSIX_C_SOURCE #endif #if !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200809L #endif /* Solaris freaks out if you try to use a POSIX or SUS standard without * the "right" C standard. */ #if defined(_XOPEN_SOURCE) # undef _XOPEN_SOURCE #endif #if defined(__STDC_VERSION__) # if __STDC_VERSION__ >= 201112L # define _XOPEN_SOURCE 700 # elif __STDC_VERSION__ >= 199901L # define _XOPEN_SOURCE 600 # endif #endif /* Because, according to Microsoft, POSIX is deprecated. You've got * to appreciate the chutzpah. */ #if defined(_MSC_VER) && !defined(_CRT_NONSTDC_NO_DEPRECATE) # define _CRT_NONSTDC_NO_DEPRECATE #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # include <stdbool.h> #elif defined(_WIN32) /* https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx */ #endif #include <limits.h> #include <time.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #if !defined(MUNIT_NO_NL_LANGINFO) && !defined(_WIN32) #define MUNIT_NL_LANGINFO #include <locale.h> #include <langinfo.h> #include <strings.h> #endif #if !defined(_WIN32) # include <unistd.h> # include <sys/types.h> # include <sys/wait.h> #else # include <windows.h> # include <io.h> # include <fcntl.h> # if !defined(STDERR_FILENO) # define STDERR_FILENO _fileno(stderr) # endif #endif #include "munit.h" #define MUNIT_STRINGIFY(x) #x #define MUNIT_XSTRINGIFY(x) MUNIT_STRINGIFY(x) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) # define MUNIT_THREAD_LOCAL __thread #elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) || defined(_Thread_local) # define MUNIT_THREAD_LOCAL _Thread_local #elif defined(_WIN32) # define MUNIT_THREAD_LOCAL __declspec(thread) #endif /* MSVC 12.0 will emit a warning at /W4 for code like 'do { ... } * while (0)', or 'do { ... } while (1)'. I'm pretty sure nobody * at Microsoft compiles with /W4. */ #if defined(_MSC_VER) && (_MSC_VER <= 1800) #pragma warning(disable: 4127) #endif #if defined(_WIN32) || defined(__EMSCRIPTEN__) # define MUNIT_NO_FORK #endif #if defined(__EMSCRIPTEN__) # define MUNIT_NO_BUFFER #endif /*** Logging ***/ static MunitLogLevel munit_log_level_visible = MUNIT_LOG_INFO; static MunitLogLevel munit_log_level_fatal = MUNIT_LOG_ERROR; #if defined(MUNIT_THREAD_LOCAL) static MUNIT_THREAD_LOCAL munit_bool munit_error_jmp_buf_valid = 0; static MUNIT_THREAD_LOCAL jmp_buf munit_error_jmp_buf; #endif /* At certain warning levels, mingw will trigger warnings about * suggesting the format attribute, which we've explicity *not* set * because it will then choke on our attempts to use the MS-specific * I64 modifier for size_t (which we have to use since MSVC doesn't * support the C99 z modifier). */ #if defined(__MINGW32__) || defined(__MINGW64__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsuggest-attribute=format" #endif MUNIT_PRINTF(5,0) static void munit_logf_exv(MunitLogLevel level, FILE* fp, const char* filename, int line, const char* format, va_list ap) { if (level < munit_log_level_visible) return; switch (level) { case MUNIT_LOG_DEBUG: fputs("Debug", fp); break; case MUNIT_LOG_INFO: fputs("Info", fp); break; case MUNIT_LOG_WARNING: fputs("Warning", fp); break; case MUNIT_LOG_ERROR: fputs("Error", fp); break; default: munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Invalid log level (%d)", level); return; } fputs(": ", fp); if (filename != NULL) fprintf(fp, "%s:%d: ", filename, line); vfprintf(fp, format, ap); fputc('\n', fp); } MUNIT_PRINTF(3,4) static void munit_logf_internal(MunitLogLevel level, FILE* fp, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, fp, NULL, 0, format, ap); va_end(ap); } static void munit_log_internal(MunitLogLevel level, FILE* fp, const char* message) { munit_logf_internal(level, fp, "%s", message); } void munit_logf_ex(MunitLogLevel level, const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, stderr, filename, line, format, ap); va_end(ap); if (level >= munit_log_level_fatal) { #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } } void munit_errorf_ex(const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(MUNIT_LOG_ERROR, stderr, filename, line, format, ap); va_end(ap); #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } #if defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC diagnostic pop #endif #if !defined(MUNIT_STRERROR_LEN) # define MUNIT_STRERROR_LEN 80 #endif static void munit_log_errno(MunitLogLevel level, FILE* fp, const char* msg) { #if defined(MUNIT_NO_STRERROR_R) || (defined(__MINGW32__) && !defined(MINGW_HAS_SECURE_API)) munit_logf_internal(level, fp, "%s: %s (%d)", msg, strerror(errno), errno); #else char munit_error_str[MUNIT_STRERROR_LEN]; munit_error_str[0] = '\0'; #if !defined(_WIN32) strerror_r(errno, munit_error_str, MUNIT_STRERROR_LEN); #else strerror_s(munit_error_str, MUNIT_STRERROR_LEN, errno); #endif munit_logf_internal(level, fp, "%s: %s (%d)", msg, munit_error_str, errno); #endif } /*** Memory allocation ***/ void* munit_malloc_ex(const char* filename, int line, size_t size) { void* ptr; if (size == 0) return NULL; ptr = calloc(1, size); if (MUNIT_UNLIKELY(ptr == NULL)) { munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Failed to allocate %" MUNIT_SIZE_MODIFIER "u bytes.", size); } return ptr; } /*** Timer code ***/ #if defined(MUNIT_ENABLE_TIMING) #define psnip_uint64_t munit_uint64_t #define psnip_uint32_t munit_uint32_t /* Code copied from portable-snippets * <https://github.com/nemequ/portable-snippets/>. If you need to * change something, please do it there so we can keep the code in * sync. */ /* Clocks (v1) * Portable Snippets - https://gitub.com/nemequ/portable-snippets * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ */ #if !defined(PSNIP_CLOCK_H) #define PSNIP_CLOCK_H #if !defined(psnip_uint64_t) # include "../exact-int/exact-int.h" #endif #if !defined(PSNIP_CLOCK_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_CLOCK__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_CLOCK__COMPILER_ATTRIBUTES # endif # define PSNIP_CLOCK__FUNCTION PSNIP_CLOCK__COMPILER_ATTRIBUTES static #endif enum PsnipClockType { /* This clock provides the current time, in units since 1970-01-01 * 00:00:00 UTC not including leap seconds. In other words, UNIX * time. Keep in mind that this clock doesn't account for leap * seconds, and can go backwards (think NTP adjustments). */ PSNIP_CLOCK_TYPE_WALL = 1, /* The CPU time is a clock which increases only when the current * process is active (i.e., it doesn't increment while blocking on * I/O). */ PSNIP_CLOCK_TYPE_CPU = 2, /* Monotonic time is always running (unlike CPU time), but it only ever moves forward unless you reboot the system. Things like NTP adjustments have no effect on this clock. */ PSNIP_CLOCK_TYPE_MONOTONIC = 3 }; struct PsnipClockTimespec { psnip_uint64_t seconds; psnip_uint64_t nanoseconds; }; /* Methods we support: */ #define PSNIP_CLOCK_METHOD_CLOCK_GETTIME 1 #define PSNIP_CLOCK_METHOD_TIME 2 #define PSNIP_CLOCK_METHOD_GETTIMEOFDAY 3 #define PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER 4 #define PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME 5 #define PSNIP_CLOCK_METHOD_CLOCK 6 #define PSNIP_CLOCK_METHOD_GETPROCESSTIMES 7 #define PSNIP_CLOCK_METHOD_GETRUSAGE 8 #define PSNIP_CLOCK_METHOD_GETSYSTEMTIMEPRECISEASFILETIME 9 #define PSNIP_CLOCK_METHOD_GETTICKCOUNT64 10 #include <assert.h> #if defined(HEDLEY_UNREACHABLE) # define PSNIP_CLOCK_UNREACHABLE() HEDLEY_UNREACHABLE() #else # define PSNIP_CLOCK_UNREACHABLE() assert(0) #endif /* Choose an implementation */ /* #undef PSNIP_CLOCK_WALL_METHOD */ /* #undef PSNIP_CLOCK_CPU_METHOD */ /* #undef PSNIP_CLOCK_MONOTONIC_METHOD */ /* We want to be able to detect the libc implementation, so we include <limits.h> (<features.h> isn't available everywhere). */ #if defined(__unix__) || defined(__unix) || defined(__linux__) # include <limits.h> # include <unistd.h> #endif #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) /* These are known to work without librt. If you know of others * please let us know so we can add them. */ # if \ (defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17))) || \ (defined(__FreeBSD__)) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # elif !defined(PSNIP_CLOCK_NO_LIBRT) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # endif #endif #if defined(_WIN32) # if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_GETPROCESSTIMES # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER # endif #endif #if defined(__MACH__) && !defined(__gnu_hurd__) # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME # endif #endif #if defined(PSNIP_CLOCK_HAVE_CLOCK_GETTIME) # include <time.h> # if !defined(PSNIP_CLOCK_WALL_METHOD) # if defined(CLOCK_REALTIME_PRECISE) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME_PRECISE # elif !defined(__sun) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME # endif # endif # if !defined(PSNIP_CLOCK_CPU_METHOD) # if defined(_POSIX_CPUTIME) || defined(CLOCK_PROCESS_CPUTIME_ID) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_PROCESS_CPUTIME_ID # elif defined(CLOCK_VIRTUAL) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_VIRTUAL # endif # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # if defined(CLOCK_MONOTONIC_RAW) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # elif defined(CLOCK_MONOTONIC_PRECISE) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC_PRECISE # elif defined(_POSIX_MONOTONIC_CLOCK) || defined(CLOCK_MONOTONIC) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # endif # endif #endif #if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200112L) # if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_GETTIMEOFDAY # endif #endif #if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_TIME #endif #if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK #endif /* Primarily here for testing. */ #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) && defined(PSNIP_CLOCK_REQUIRE_MONOTONIC) # error No monotonic clock found. #endif /* Implementations */ #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_TIME)) # include <time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) # include <sys/time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) # include <windows.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) # include <sys/time.h> # include <sys/resource.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) # include <CoreServices/CoreServices.h> # include <mach/mach.h> # include <mach/mach_time.h> #endif /*** Implementations ***/ #define PSNIP_CLOCK_NSEC_PER_SEC ((psnip_uint32_t) (1000000000ULL)) #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock__clock_getres (clockid_t clk_id) { struct timespec res; int r; r = clock_getres(clk_id, &res); if (r != 0) return 0; return (psnip_uint32_t) (PSNIP_CLOCK_NSEC_PER_SEC / res.tv_nsec); } PSNIP_CLOCK__FUNCTION int psnip_clock__clock_gettime (clockid_t clk_id, struct PsnipClockTimespec* res) { struct timespec ts; if (clock_gettime(clk_id, &ts) != 0) return -10; res->seconds = (psnip_uint64_t) (ts.tv_sec); res->nanoseconds = (psnip_uint64_t) (ts.tv_nsec); return 0; } #endif PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_wall_get_precision (void) { #if !defined(PSNIP_CLOCK_WALL_METHOD) return 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_WALL); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY return 1000000; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME return 1; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_wall_get_time (struct PsnipClockTimespec* res) { (void) res; #if !defined(PSNIP_CLOCK_WALL_METHOD) return -2; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_WALL, res); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME res->seconds = time(NULL); res->nanoseconds = 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY struct timeval tv; if (gettimeofday(&tv, NULL) != 0) return -6; res->seconds = tv.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_cpu_get_precision (void) { #if !defined(PSNIP_CLOCK_CPU_METHOD) return 0; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_CPU); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK return CLOCKS_PER_SEC; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES return PSNIP_CLOCK_NSEC_PER_SEC / 100; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_cpu_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_CPU_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_CPU, res); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK clock_t t = clock(); if (t == ((clock_t) -1)) return -5; res->seconds = t / CLOCKS_PER_SEC; res->nanoseconds = (t % CLOCKS_PER_SEC) * (PSNIP_CLOCK_NSEC_PER_SEC / CLOCKS_PER_SEC); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES FILETIME CreationTime, ExitTime, KernelTime, UserTime; LARGE_INTEGER date, adjust; if (!GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime)) return -7; /* http://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/ */ date.HighPart = UserTime.dwHighDateTime; date.LowPart = UserTime.dwLowDateTime; adjust.QuadPart = 11644473600000 * 10000; date.QuadPart -= adjust.QuadPart; res->seconds = date.QuadPart / 10000000; res->nanoseconds = (date.QuadPart % 10000000) * (PSNIP_CLOCK_NSEC_PER_SEC / 100); #elif PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE struct rusage usage; if (getrusage(RUSAGE_SELF, &usage) != 0) return -8; res->seconds = usage.ru_utime.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else (void) res; return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_monotonic_get_precision (void) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) return 0; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); return (psnip_uint32_t) (tbi.numer / tbi.denom); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 return 1000; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); return (psnip_uint32_t) ((Frequency.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) ? PSNIP_CLOCK_NSEC_PER_SEC : Frequency.QuadPart); #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_monotonic_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC, res); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME psnip_uint64_t nsec = mach_absolute_time(); static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); nsec *= ((psnip_uint64_t) tbi.numer) / ((psnip_uint64_t) tbi.denom); res->seconds = nsec / PSNIP_CLOCK_NSEC_PER_SEC; res->nanoseconds = nsec % PSNIP_CLOCK_NSEC_PER_SEC; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER t, f; if (QueryPerformanceCounter(&t) == 0) return -12; QueryPerformanceFrequency(&f); res->seconds = t.QuadPart / f.QuadPart; res->nanoseconds = t.QuadPart % f.QuadPart; if (f.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) res->nanoseconds /= f.QuadPart / PSNIP_CLOCK_NSEC_PER_SEC; else res->nanoseconds *= PSNIP_CLOCK_NSEC_PER_SEC / f.QuadPart; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 const ULONGLONG msec = GetTickCount64(); res->seconds = msec / 1000; res->nanoseconds = sec % 1000; #else return -2; #endif return 0; } /* Returns the number of ticks per second for the specified clock. * For example, a clock with millisecond precision would return 1000, * and a clock with 1 second (such as the time() function) would * return 1. * * If the requested clock isn't available, it will return 0. * Hopefully this will be rare, but if it happens to you please let us * know so we can work on finding a way to support your system. * * Note that different clocks on the same system often have a * different precisions. */ PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_get_precision (enum PsnipClockType clock_type) { switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_precision (); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_precision (); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_precision (); } PSNIP_CLOCK_UNREACHABLE(); return 0; } /* Set the provided timespec to the requested time. Returns 0 on * success, or a negative value on failure. */ PSNIP_CLOCK__FUNCTION int psnip_clock_get_time (enum PsnipClockType clock_type, struct PsnipClockTimespec* res) { assert(res != NULL); switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_time (res); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_time (res); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_time (res); } return -1; } #endif /* !defined(PSNIP_CLOCK_H) */ static psnip_uint64_t munit_clock_get_elapsed(struct PsnipClockTimespec* start, struct PsnipClockTimespec* end) { psnip_uint64_t r = (end->seconds - start->seconds) * PSNIP_CLOCK_NSEC_PER_SEC; if (end->nanoseconds < start->nanoseconds) { r -= (start->nanoseconds - end->nanoseconds); } else { r += (end->nanoseconds - start->nanoseconds); } return r; } #else # include <time.h> #endif /* defined(MUNIT_ENABLE_TIMING) */ /*** PRNG stuff ***/ /* This is (unless I screwed up, which is entirely possible) the * version of PCG with 32-bit state. It was chosen because it has a * small enough state that we should reliably be able to use CAS * instead of requiring a lock for thread-safety. * * If I did screw up, I probably will not bother changing it unless * there is a significant bias. It's really not important this be * particularly strong, as long as it is fairly random it's much more * important that it be reproducible, so bug reports have a better * chance of being reproducible. */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) && !defined(__EMSCRIPTEN__) && (!defined(__GNUC_MINOR__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)) # define HAVE_STDATOMIC #elif defined(__clang__) # if __has_extension(c_atomic) # define HAVE_CLANG_ATOMICS # endif #endif /* Workaround for http://llvm.org/bugs/show_bug.cgi?id=26911 */ #if defined(__clang__) && defined(_WIN32) # undef HAVE_STDATOMIC # if defined(__c2__) # undef HAVE_CLANG_ATOMICS # endif #endif #if defined(_OPENMP) # define ATOMIC_UINT32_T uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(HAVE_STDATOMIC) # include <stdatomic.h> # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) ATOMIC_VAR_INIT(x) #elif defined(HAVE_CLANG_ATOMICS) # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(_WIN32) # define ATOMIC_UINT32_T volatile LONG # define ATOMIC_UINT32_INIT(x) (x) #else # define ATOMIC_UINT32_T volatile uint32_t # define ATOMIC_UINT32_INIT(x) (x) #endif static ATOMIC_UINT32_T munit_rand_state = ATOMIC_UINT32_INIT(42); #if defined(_OPENMP) static inline void munit_atomic_store(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T value) { #pragma omp critical (munit_atomics) *dest = value; } static inline uint32_t munit_atomic_load(ATOMIC_UINT32_T* src) { int ret; #pragma omp critical (munit_atomics) ret = *src; return ret; } static inline uint32_t munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { munit_bool ret; #pragma omp critical (munit_atomics) { if (*dest == *expected) { *dest = desired; ret = 1; } else { ret = 0; } } return ret; } #elif defined(HAVE_STDATOMIC) # define munit_atomic_store(dest, value) atomic_store(dest, value) # define munit_atomic_load(src) atomic_load(src) # define munit_atomic_cas(dest, expected, value) atomic_compare_exchange_weak(dest, expected, value) #elif defined(HAVE_CLANG_ATOMICS) # define munit_atomic_store(dest, value) __c11_atomic_store(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __c11_atomic_load(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __c11_atomic_compare_exchange_weak(dest, expected, value, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) # define munit_atomic_store(dest, value) __atomic_store_n(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __atomic_load_n(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __atomic_compare_exchange_n(dest, expected, value, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ >= 4) # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) __sync_bool_compare_and_swap(dest, *expected, value) #elif defined(_WIN32) /* Untested */ # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) InterlockedCompareExchange((dest), (value), *(expected)) #else # warning No atomic implementation, PRNG will not be thread-safe # define munit_atomic_store(dest, value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) static inline munit_bool munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { if (*dest == *expected) { *dest = desired; return 1; } else { return 0; } } #endif #define MUNIT_PRNG_MULTIPLIER (747796405U) #define MUNIT_PRNG_INCREMENT (1729U) static munit_uint32_t munit_rand_next_state(munit_uint32_t state) { return state * MUNIT_PRNG_MULTIPLIER + MUNIT_PRNG_INCREMENT; } static munit_uint32_t munit_rand_from_state(munit_uint32_t state) { munit_uint32_t res = ((state >> ((state >> 28) + 4)) ^ state) * (277803737U); res ^= res >> 22; return res; } void munit_rand_seed(munit_uint32_t seed) { munit_uint32_t state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); munit_atomic_store(&munit_rand_state, state); } static munit_uint32_t munit_rand_generate_seed(void) { munit_uint32_t seed, state; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wc = { 0, }; psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wc); seed = (munit_uint32_t) wc.nanoseconds; #else seed = (munit_uint32_t) time(NULL); #endif state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); return munit_rand_from_state(state); } static munit_uint32_t munit_rand_state_uint32(munit_uint32_t* state) { const munit_uint32_t old = *state; *state = munit_rand_next_state(old); return munit_rand_from_state(old); } munit_uint32_t munit_rand_uint32(void) { munit_uint32_t old, state; do { old = munit_atomic_load(&munit_rand_state); state = munit_rand_next_state(old); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return munit_rand_from_state(old); } static void munit_rand_state_memory(munit_uint32_t* state, size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { size_t members_remaining = size / sizeof(munit_uint32_t); size_t bytes_remaining = size % sizeof(munit_uint32_t); munit_uint8_t* b = data; munit_uint32_t rv; while (members_remaining-- > 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, sizeof(munit_uint32_t)); b += sizeof(munit_uint32_t); } if (bytes_remaining != 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, bytes_remaining); } } void munit_rand_memory(size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { munit_uint32_t old, state; do { state = old = munit_atomic_load(&munit_rand_state); munit_rand_state_memory(&state, size, data); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); } static munit_uint32_t munit_rand_state_at_most(munit_uint32_t* state, munit_uint32_t salt, munit_uint32_t max) { /* We want (UINT32_MAX + 1) % max, which in unsigned arithmetic is the same * as (UINT32_MAX + 1 - max) % max = -max % max. We compute -max using not * to avoid compiler warnings. */ const munit_uint32_t min = (~max + 1U) % max; munit_uint32_t x; if (max == (~((munit_uint32_t) 0U))) return munit_rand_state_uint32(state) ^ salt; max++; do { x = munit_rand_state_uint32(state) ^ salt; } while (x < min); return x % max; } static munit_uint32_t munit_rand_at_most(munit_uint32_t salt, munit_uint32_t max) { munit_uint32_t old, state; munit_uint32_t retval; do { state = old = munit_atomic_load(&munit_rand_state); retval = munit_rand_state_at_most(&state, salt, max); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } int munit_rand_int_range(int min, int max) { munit_uint64_t range = (munit_uint64_t) max - (munit_uint64_t) min; if (min > max) return munit_rand_int_range(max, min); if (range > (~((munit_uint32_t) 0U))) range = (~((munit_uint32_t) 0U)); return min + munit_rand_at_most(0, (munit_uint32_t) range); } double munit_rand_double(void) { munit_uint32_t old, state; double retval = 0.0; do { state = old = munit_atomic_load(&munit_rand_state); /* See http://mumble.net/~campbell/tmp/random_real.c for how to do * this right. Patches welcome if you feel that this is too * biased. */ retval = munit_rand_state_uint32(&state) / ((~((munit_uint32_t) 0U)) + 1.0); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } /*** Test suite handling ***/ typedef struct { unsigned int successful; unsigned int skipped; unsigned int failed; unsigned int errored; #if defined(MUNIT_ENABLE_TIMING) munit_uint64_t cpu_clock; munit_uint64_t wall_clock; #endif } MunitReport; typedef struct { const char* prefix; const MunitSuite* suite; const char** tests; munit_uint32_t seed; unsigned int iterations; MunitParameter* parameters; munit_bool single_parameter_mode; void* user_data; MunitReport report; munit_bool colorize; munit_bool fork; munit_bool show_stderr; munit_bool fatal_failures; } MunitTestRunner; const char* munit_parameters_get(const MunitParameter params[], const char* key) { const MunitParameter* param; for (param = params ; param != NULL && param->name != NULL ; param++) if (strcmp(param->name, key) == 0) return param->value; return NULL; } #if defined(MUNIT_ENABLE_TIMING) static void munit_print_time(FILE* fp, munit_uint64_t nanoseconds) { fprintf(fp, "%" MUNIT_TEST_TIME_FORMAT, ((double) nanoseconds) / ((double) PSNIP_CLOCK_NSEC_PER_SEC)); } #endif /* Add a paramter to an array of parameters. */ static MunitResult munit_parameters_add(size_t* params_size, MunitParameter* params[MUNIT_ARRAY_PARAM(*params_size)], char* name, char* value) { *params = realloc(*params, sizeof(MunitParameter) * (*params_size + 2)); if (*params == NULL) return MUNIT_ERROR; (*params)[*params_size].name = name; (*params)[*params_size].value = value; (*params_size)++; (*params)[*params_size].name = NULL; (*params)[*params_size].value = NULL; return MUNIT_OK; } /* Concatenate two strings, but just return one of the components * unaltered if the other is NULL or "". */ static char* munit_maybe_concat(size_t* len, char* prefix, char* suffix) { char* res; size_t res_l; const size_t prefix_l = prefix != NULL ? strlen(prefix) : 0; const size_t suffix_l = suffix != NULL ? strlen(suffix) : 0; if (prefix_l == 0 && suffix_l == 0) { res = NULL; res_l = 0; } else if (prefix_l == 0 && suffix_l != 0) { res = suffix; res_l = suffix_l; } else if (prefix_l != 0 && suffix_l == 0) { res = prefix; res_l = prefix_l; } else { res_l = prefix_l + suffix_l; res = malloc(res_l + 1); memcpy(res, prefix, prefix_l); memcpy(res + prefix_l, suffix, suffix_l); res[res_l] = 0; } if (len != NULL) *len = res_l; return res; } /* Possbily free a string returned by munit_maybe_concat. */ static void munit_maybe_free_concat(char* s, const char* prefix, const char* suffix) { if (prefix != s && suffix != s) free(s); } /* Cheap string hash function, just used to salt the PRNG. */ static munit_uint32_t munit_str_hash(const char* name) { const char *p; munit_uint32_t h = 5381U; for (p = name; *p != '\0'; p++) h = (h << 5) + h + *p; return h; } static void munit_splice(int from, int to) { munit_uint8_t buf[1024]; #if !defined(_WIN32) ssize_t len; ssize_t bytes_written; ssize_t write_res; #else int len; int bytes_written; int write_res; #endif do { len = read(from, buf, sizeof(buf)); if (len > 0) { bytes_written = 0; do { write_res = write(to, buf + bytes_written, len - bytes_written); if (write_res < 0) break; bytes_written += write_res; } while (bytes_written < len); } else break; } while (1); } /* This is the part that should be handled in the child process */ static MunitResult munit_test_runner_exec(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[], MunitReport* report) { unsigned int iterations = runner->iterations; MunitResult result = MUNIT_FAIL; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wall_clock_begin = { 0, }, wall_clock_end = { 0, }; struct PsnipClockTimespec cpu_clock_begin = { 0, }, cpu_clock_end = { 0, }; #endif unsigned int i = 0; if ((test->options & MUNIT_TEST_OPTION_SINGLE_ITERATION) == MUNIT_TEST_OPTION_SINGLE_ITERATION) iterations = 1; else if (iterations == 0) iterations = runner->suite->iterations; munit_rand_seed(runner->seed); do { void* data = (test->setup == NULL) ? runner->user_data : test->setup(params, runner->user_data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_begin); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_begin); #endif result = test->test(params, data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_end); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_end); #endif if (test->tear_down != NULL) test->tear_down(data); if (MUNIT_LIKELY(result == MUNIT_OK)) { report->successful++; #if defined(MUNIT_ENABLE_TIMING) report->wall_clock += munit_clock_get_elapsed(&wall_clock_begin, &wall_clock_end); report->cpu_clock += munit_clock_get_elapsed(&cpu_clock_begin, &cpu_clock_end); #endif } else { switch ((int) result) { case MUNIT_SKIP: report->skipped++; break; case MUNIT_FAIL: report->failed++; break; case MUNIT_ERROR: report->errored++; break; default: break; } break; } } while (++i < iterations); return result; } #if defined(MUNIT_EMOTICON) # define MUNIT_RESULT_STRING_OK ":)" # define MUNIT_RESULT_STRING_SKIP ":|" # define MUNIT_RESULT_STRING_FAIL ":(" # define MUNIT_RESULT_STRING_ERROR ":o" # define MUNIT_RESULT_STRING_TODO ":/" #else # define MUNIT_RESULT_STRING_OK "OK " # define MUNIT_RESULT_STRING_SKIP "SKIP " # define MUNIT_RESULT_STRING_FAIL "FAIL " # define MUNIT_RESULT_STRING_ERROR "ERROR" # define MUNIT_RESULT_STRING_TODO "TODO " #endif static void munit_test_runner_print_color(const MunitTestRunner* runner, const char* string, char color) { if (runner->colorize) fprintf(MUNIT_OUTPUT_FILE, "\x1b[3%cm%s\x1b[39m", color, string); else fputs(string, MUNIT_OUTPUT_FILE); } #if !defined(MUNIT_NO_BUFFER) static int munit_replace_stderr(FILE* stderr_buf) { if (stderr_buf != NULL) { const int orig_stderr = dup(STDERR_FILENO); int errfd = fileno(stderr_buf); if (MUNIT_UNLIKELY(errfd == -1)) { exit(EXIT_FAILURE); } dup2(errfd, STDERR_FILENO); return orig_stderr; } return -1; } static void munit_restore_stderr(int orig_stderr) { if (orig_stderr != -1) { dup2(orig_stderr, STDERR_FILENO); close(orig_stderr); } } #endif /* !defined(MUNIT_NO_BUFFER) */ /* Run a test with the specified parameters. */ static void munit_test_runner_run_test_with_params(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[]) { MunitResult result = MUNIT_OK; MunitReport report = { 0, 0, 0, 0, #if defined(MUNIT_ENABLE_TIMING) 0, 0 #endif }; unsigned int output_l; munit_bool first; const MunitParameter* param; FILE* stderr_buf; #if !defined(MUNIT_NO_FORK) int pipefd[2]; pid_t fork_pid; int orig_stderr; ssize_t bytes_written = 0; ssize_t write_res; ssize_t bytes_read = 0; ssize_t read_res; int status = 0; pid_t changed_pid; #endif if (params != NULL) { output_l = 2; fputs(" ", MUNIT_OUTPUT_FILE); first = 1; for (param = params ; param != NULL && param->name != NULL ; param++) { if (!first) { fputs(", ", MUNIT_OUTPUT_FILE); output_l += 2; } else { first = 0; } output_l += fprintf(MUNIT_OUTPUT_FILE, "%s=%s", param->name, param->value); } while (output_l++ < MUNIT_TEST_NAME_LEN) { fputc(' ', MUNIT_OUTPUT_FILE); } } fflush(MUNIT_OUTPUT_FILE); stderr_buf = NULL; #if !defined(_WIN32) || defined(__MINGW32__) stderr_buf = tmpfile(); #else tmpfile_s(&stderr_buf); #endif if (stderr_buf == NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create buffer for stderr"); result = MUNIT_ERROR; goto print_result; } #if !defined(MUNIT_NO_FORK) if (runner->fork) { pipefd[0] = -1; pipefd[1] = -1; if (pipe(pipefd) != 0) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create pipe"); result = MUNIT_ERROR; goto print_result; } fork_pid = fork(); if (fork_pid == 0) { close(pipefd[0]); orig_stderr = munit_replace_stderr(stderr_buf); munit_test_runner_exec(runner, test, params, &report); /* Note that we don't restore stderr. This is so we can buffer * things written to stderr later on (such as by * asan/tsan/ubsan, valgrind, etc.) */ close(orig_stderr); do { write_res = write(pipefd[1], ((munit_uint8_t*) (&report)) + bytes_written, sizeof(report) - bytes_written); if (write_res < 0) { if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to write to pipe"); } exit(EXIT_FAILURE); } bytes_written += write_res; } while ((size_t) bytes_written < sizeof(report)); if (stderr_buf != NULL) fclose(stderr_buf); close(pipefd[1]); exit(EXIT_SUCCESS); } else if (fork_pid == -1) { close(pipefd[0]); close(pipefd[1]); if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to fork"); } report.errored++; result = MUNIT_ERROR; } else { close(pipefd[1]); do { read_res = read(pipefd[0], ((munit_uint8_t*) (&report)) + bytes_read, sizeof(report) - bytes_read); if (read_res < 1) break; bytes_read += read_res; } while (bytes_read < (ssize_t) sizeof(report)); changed_pid = waitpid(fork_pid, &status, 0); if (MUNIT_LIKELY(changed_pid == fork_pid) && MUNIT_LIKELY(WIFEXITED(status))) { if (bytes_read != sizeof(report)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited unexpectedly with status %d", WEXITSTATUS(status)); report.errored++; } else if (WEXITSTATUS(status) != EXIT_SUCCESS) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited with status %d", WEXITSTATUS(status)); report.errored++; } } else { if (WIFSIGNALED(status)) { #if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700) munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status))); #else munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d", WTERMSIG(status)); #endif } else if (WIFSTOPPED(status)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child stopped by signal %d", WSTOPSIG(status)); } report.errored++; } close(pipefd[0]); waitpid(fork_pid, NULL, 0); } } else #endif { #if !defined(MUNIT_NO_BUFFER) const volatile int orig_stderr = munit_replace_stderr(stderr_buf); #endif #if defined(MUNIT_THREAD_LOCAL) if (MUNIT_UNLIKELY(setjmp(munit_error_jmp_buf) != 0)) { result = MUNIT_FAIL; report.failed++; } else { munit_error_jmp_buf_valid = 1; result = munit_test_runner_exec(runner, test, params, &report); } #else result = munit_test_runner_exec(runner, test, params, &report); #endif #if !defined(MUNIT_NO_BUFFER) munit_restore_stderr(orig_stderr); #endif /* Here just so that the label is used on Windows and we don't get * a warning */ goto print_result; } print_result: fputs("[ ", MUNIT_OUTPUT_FILE); if ((test->options & MUNIT_TEST_OPTION_TODO) == MUNIT_TEST_OPTION_TODO) { if (report.failed != 0 || report.errored != 0 || report.skipped != 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_TODO, '3'); result = MUNIT_OK; } else { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); if (MUNIT_LIKELY(stderr_buf != NULL)) munit_log_internal(MUNIT_LOG_ERROR, stderr_buf, "Test marked TODO, but was successful."); runner->report.failed++; result = MUNIT_ERROR; } } else if (report.failed > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_FAIL, '1'); runner->report.failed++; result = MUNIT_FAIL; } else if (report.errored > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); runner->report.errored++; result = MUNIT_ERROR; } else if (report.skipped > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_SKIP, '3'); runner->report.skipped++; result = MUNIT_SKIP; } else if (report.successful > 1) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock / report.successful); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock / report.successful); fprintf(MUNIT_OUTPUT_FILE, " CPU ]\n %-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s Total: [ ", ""); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } else if (report.successful > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } fputs(" ]\n", MUNIT_OUTPUT_FILE); if (stderr_buf != NULL) { if (result == MUNIT_FAIL || result == MUNIT_ERROR || runner->show_stderr) { fflush(MUNIT_OUTPUT_FILE); rewind(stderr_buf); munit_splice(fileno(stderr_buf), STDERR_FILENO); fflush(stderr); } fclose(stderr_buf); } } static void munit_test_runner_run_test_wild(MunitTestRunner* runner, const MunitTest* test, const char* test_name, MunitParameter* params, MunitParameter* p) { const MunitParameterEnum* pe; char** values; MunitParameter* next; for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { if (p->name == pe->name) break; } if (pe == NULL) return; for (values = pe->values ; *values != NULL ; values++) { next = p + 1; p->value = *values; if (next->name == NULL) { munit_test_runner_run_test_with_params(runner, test, params); } else { munit_test_runner_run_test_wild(runner, test, test_name, params, next); } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) break; } } /* Run a single test, with every combination of parameters * requested. */ static void munit_test_runner_run_test(MunitTestRunner* runner, const MunitTest* test, const char* prefix) { char* test_name = munit_maybe_concat(NULL, (char*) prefix, (char*) test->name); /* The array of parameters to pass to * munit_test_runner_run_test_with_params */ MunitParameter* params = NULL; size_t params_l = 0; /* Wildcard parameters are parameters which have possible values * specified in the test, but no specific value was passed to the * CLI. That means we want to run the test once for every * possible combination of parameter values or, if --single was * passed to the CLI, a single time with a random set of * parameters. */ MunitParameter* wild_params = NULL; size_t wild_params_l = 0; const MunitParameterEnum* pe; const MunitParameter* cli_p; munit_bool filled; unsigned int possible; char** vals; size_t first_wild; const MunitParameter* wp; int pidx; munit_rand_seed(runner->seed); fprintf(MUNIT_OUTPUT_FILE, "%-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s", test_name); if (test->parameters == NULL) { /* No parameters. Simple, nice. */ munit_test_runner_run_test_with_params(runner, test, NULL); } else { fputc('\n', MUNIT_OUTPUT_FILE); for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { /* Did we received a value for this parameter from the CLI? */ filled = 0; for (cli_p = runner->parameters ; cli_p != NULL && cli_p->name != NULL ; cli_p++) { if (strcmp(cli_p->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, cli_p->value) != MUNIT_OK)) goto cleanup; filled = 1; break; } } if (filled) continue; /* Nothing from CLI, is the enum NULL/empty? We're not a * fuzzer… */ if (pe->values == NULL || pe->values[0] == NULL) continue; /* If --single was passed to the CLI, choose a value from the * list of possibilities randomly. */ if (runner->single_parameter_mode) { possible = 0; for (vals = pe->values ; *vals != NULL ; vals++) possible++; /* We want the tests to be reproducible, even if you're only * running a single test, but we don't want every test with * the same number of parameters to choose the same parameter * number, so use the test name as a primitive salt. */ pidx = munit_rand_at_most(munit_str_hash(test_name), possible - 1); if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[pidx]) != MUNIT_OK)) goto cleanup; } else { /* We want to try every permutation. Put in a placeholder * entry, we'll iterate through them later. */ if (MUNIT_UNLIKELY(munit_parameters_add(&wild_params_l, &wild_params, pe->name, NULL) != MUNIT_OK)) goto cleanup; } } if (wild_params_l != 0) { first_wild = params_l; for (wp = wild_params ; wp != NULL && wp->name != NULL ; wp++) { for (pe = test->parameters ; pe != NULL && pe->name != NULL && pe->values != NULL ; pe++) { if (strcmp(wp->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[0]) != MUNIT_OK)) goto cleanup; } } } munit_test_runner_run_test_wild(runner, test, test_name, params, params + first_wild); } else { munit_test_runner_run_test_with_params(runner, test, params); } cleanup: free(params); free(wild_params); } munit_maybe_free_concat(test_name, prefix, test->name); } /* Recurse through the suite and run all the tests. If a list of * tests to run was provied on the command line, run only those * tests. */ static void munit_test_runner_run_suite(MunitTestRunner* runner, const MunitSuite* suite, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const char** test_name; const MunitSuite* child_suite; /* Run the tests. */ for (test = suite->tests ; test != NULL && test->test != NULL ; test++) { if (runner->tests != NULL) { /* Specific tests were requested on the CLI */ for (test_name = runner->tests ; test_name != NULL && *test_name != NULL ; test_name++) { if ((pre_l == 0 || strncmp(pre, *test_name, pre_l) == 0) && strncmp(test->name, *test_name + pre_l, strlen(*test_name + pre_l)) == 0) { munit_test_runner_run_test(runner, test, pre); if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; } } } else { /* Run all tests */ munit_test_runner_run_test(runner, test, pre); } } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; /* Run any child suites. */ for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_test_runner_run_suite(runner, child_suite, pre); } cleanup: munit_maybe_free_concat(pre, prefix, suite->prefix); } static void munit_test_runner_run(MunitTestRunner* runner) { munit_test_runner_run_suite(runner, runner->suite, NULL); } static void munit_print_help(int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], void* user_data, const MunitArgument arguments[]) { const MunitArgument* arg; (void) argc; printf("USAGE: %s [OPTIONS...] [TEST...]\n\n", argv[0]); puts(" --seed SEED\n" " Value used to seed the PRNG. Must be a 32-bit integer in decimal\n" " notation with no separators (commas, decimals, spaces, etc.), or\n" " hexidecimal prefixed by \"0x\".\n" " --iterations N\n" " Run each test N times. 0 means the default number.\n" " --param name value\n" " A parameter key/value pair which will be passed to any test with\n" " takes a parameter of that name. If not provided, the test will be\n" " run once for each possible parameter value.\n" " --list Write a list of all available tests.\n" " --list-params\n" " Write a list of all available tests and their possible parameters.\n" " --single Run each parameterized test in a single configuration instead of\n" " every possible combination\n" " --log-visible debug|info|warning|error\n" " --log-fatal debug|info|warning|error\n" " Set the level at which messages of different severities are visible,\n" " or cause the test to terminate.\n" #if !defined(MUNIT_NO_FORK) " --no-fork Do not execute tests in a child process. If this option is supplied\n" " and a test crashes (including by failing an assertion), no further\n" " tests will be performed.\n" #endif " --fatal-failures\n" " Stop executing tests as soon as a failure is found.\n" " --show-stderr\n" " Show data written to stderr by the tests, even if the test succeeds.\n" " --color auto|always|never\n" " Colorize (or don't) the output.\n" /* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */ " --help Print this help message and exit.\n"); #if defined(MUNIT_NL_LANGINFO) setlocale(LC_ALL, ""); fputs((strcasecmp("UTF-8", nl_langinfo(CODESET)) == 0) ? "µnit" : "munit", stdout); #else puts("munit"); #endif printf(" %d.%d.%d\n" "Full documentation at: https://nemequ.github.io/munit/\n", (MUNIT_CURRENT_VERSION >> 16) & 0xff, (MUNIT_CURRENT_VERSION >> 8) & 0xff, (MUNIT_CURRENT_VERSION >> 0) & 0xff); for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) arg->write_help(arg, user_data); } static const MunitArgument* munit_arguments_find(const MunitArgument arguments[], const char* name) { const MunitArgument* arg; for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) if (strcmp(arg->name, name) == 0) return arg; return NULL; } static void munit_suite_list_tests(const MunitSuite* suite, munit_bool show_params, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const MunitParameterEnum* params; munit_bool first; char** val; const MunitSuite* child_suite; for (test = suite->tests ; test != NULL && test->name != NULL ; test++) { if (pre != NULL) fputs(pre, stdout); puts(test->name); if (show_params) { for (params = test->parameters ; params != NULL && params->name != NULL ; params++) { fprintf(stdout, " - %s: ", params->name); if (params->values == NULL) { puts("Any"); } else { first = 1; for (val = params->values ; *val != NULL ; val++ ) { if(!first) { fputs(", ", stdout); } else { first = 0; } fputs(*val, stdout); } putc('\n', stdout); } } } } for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_suite_list_tests(child_suite, show_params, pre); } munit_maybe_free_concat(pre, prefix, suite->prefix); } static munit_bool munit_stream_supports_ansi(FILE *stream) { #if !defined(_WIN32) return isatty(fileno(stream)); #else #if !defined(__MINGW32__) size_t ansicon_size = 0; #endif if (isatty(fileno(stream))) { #if !defined(__MINGW32__) getenv_s(&ansicon_size, NULL, 0, "ANSICON"); return ansicon_size != 0; #else return getenv("ANSICON") != NULL; #endif } return 0; #endif } int munit_suite_main_custom(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], const MunitArgument arguments[]) { int result = EXIT_FAILURE; MunitTestRunner runner; size_t parameters_size = 0; size_t tests_size = 0; int arg; char* envptr; unsigned long ts; char* endptr; unsigned long long iterations; MunitLogLevel level; const MunitArgument* argument; const char** runner_tests; unsigned int tests_run; unsigned int tests_total; runner.prefix = NULL; runner.suite = NULL; runner.tests = NULL; runner.seed = 0; runner.iterations = 0; runner.parameters = NULL; runner.single_parameter_mode = 0; runner.user_data = NULL; runner.report.successful = 0; runner.report.skipped = 0; runner.report.failed = 0; runner.report.errored = 0; #if defined(MUNIT_ENABLE_TIMING) runner.report.cpu_clock = 0; runner.report.wall_clock = 0; #endif runner.colorize = 0; #if !defined(_WIN32) runner.fork = 1; #else runner.fork = 0; #endif runner.show_stderr = 0; runner.fatal_failures = 0; runner.suite = suite; runner.user_data = user_data; runner.seed = munit_rand_generate_seed(); runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); for (arg = 1 ; arg < argc ; arg++) { if (strncmp("--", argv[arg], 2) == 0) { if (strcmp("seed", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } envptr = argv[arg + 1]; ts = strtoul(argv[arg + 1], &envptr, 0); if (*envptr != '\0' || ts > (~((munit_uint32_t) 0U))) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.seed = (munit_uint32_t) ts; arg++; } else if (strcmp("iterations", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } endptr = argv[arg + 1]; iterations = strtoul(argv[arg + 1], &endptr, 0); if (*endptr != '\0' || iterations > UINT_MAX) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.iterations = (unsigned int) iterations; arg++; } else if (strcmp("param", argv[arg] + 2) == 0) { if (arg + 2 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires two arguments", argv[arg]); goto cleanup; } runner.parameters = realloc(runner.parameters, sizeof(MunitParameter) * (parameters_size + 2)); if (runner.parameters == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.parameters[parameters_size].name = (char*) argv[arg + 1]; runner.parameters[parameters_size].value = (char*) argv[arg + 2]; parameters_size++; runner.parameters[parameters_size].name = NULL; runner.parameters[parameters_size].value = NULL; arg += 2; } else if (strcmp("color", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "always") == 0) runner.colorize = 1; else if (strcmp(argv[arg + 1], "never") == 0) runner.colorize = 0; else if (strcmp(argv[arg + 1], "auto") == 0) runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } arg++; } else if (strcmp("help", argv[arg] + 2) == 0) { munit_print_help(argc, argv, user_data, arguments); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("single", argv[arg] + 2) == 0) { runner.single_parameter_mode = 1; } else if (strcmp("show-stderr", argv[arg] + 2) == 0) { runner.show_stderr = 1; #if !defined(_WIN32) } else if (strcmp("no-fork", argv[arg] + 2) == 0) { runner.fork = 0; #endif } else if (strcmp("fatal-failures", argv[arg] + 2) == 0) { runner.fatal_failures = 1; } else if (strcmp("log-visible", argv[arg] + 2) == 0 || strcmp("log-fatal", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "debug") == 0) level = MUNIT_LOG_DEBUG; else if (strcmp(argv[arg + 1], "info") == 0) level = MUNIT_LOG_INFO; else if (strcmp(argv[arg + 1], "warning") == 0) level = MUNIT_LOG_WARNING; else if (strcmp(argv[arg + 1], "error") == 0) level = MUNIT_LOG_ERROR; else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } if (strcmp("log-visible", argv[arg] + 2) == 0) munit_log_level_visible = level; else munit_log_level_fatal = level; arg++; } else if (strcmp("list", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 0, NULL); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("list-params", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 1, NULL); result = EXIT_SUCCESS; goto cleanup; } else { argument = munit_arguments_find(arguments, argv[arg] + 2); if (argument == NULL) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "unknown argument ('%s')", argv[arg]); goto cleanup; } if (!argument->parse_argument(suite, user_data, &arg, argc, argv)) goto cleanup; } } else { runner_tests = realloc((void*) runner.tests, sizeof(char*) * (tests_size + 2)); if (runner_tests == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.tests = runner_tests; runner.tests[tests_size++] = argv[arg]; runner.tests[tests_size] = NULL; } } fflush(stderr); fprintf(MUNIT_OUTPUT_FILE, "Running test suite with seed 0x%08" PRIx32 "...\n", runner.seed); munit_test_runner_run(&runner); tests_run = runner.report.successful + runner.report.failed + runner.report.errored; tests_total = tests_run + runner.report.skipped; if (tests_run == 0) { fprintf(stderr, "No tests run, %d (100%%) skipped.\n", runner.report.skipped); } else { fprintf(MUNIT_OUTPUT_FILE, "%d of %d (%0.0f%%) tests successful, %d (%0.0f%%) test skipped.\n", runner.report.successful, tests_run, (((double) runner.report.successful) / ((double) tests_run)) * 100.0, runner.report.skipped, (((double) runner.report.skipped) / ((double) tests_total)) * 100.0); } if (runner.report.failed == 0 && runner.report.errored == 0) { result = EXIT_SUCCESS; } cleanup: free(runner.parameters); free((void*) runner.tests); return result; } int munit_suite_main(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)]) { return munit_suite_main_custom(suite, user_data, argc, argv, NULL); }
test_utils.h
#pragma once #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <limits> #include <utility> #include <cstdint> extern "C" { #include "mmio.h" } #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #include <library_types.h> #include <thrust/host_vector.h> #include <thrust/adjacent_difference.h> #include <thrust/reduce.h> #include <thrust/functional.h> #include <thrust/device_vector.h> #include <thrust/sequence.h> #include "cugraph.h" #ifndef CUDA_RT_CALL #define CUDA_RT_CALL( call ) \ { \ cudaError_t cudaStatus = call; \ if ( cudaSuccess != cudaStatus ) { \ fprintf(stderr, "ERROR: CUDA RT call \"%s\" in line %d of file %s failed with %s (%d).\n", \ #call, __LINE__, __FILE__, cudaGetErrorString(cudaStatus), cudaStatus); \ } \ } #endif std::function<void(gdf_column*)> gdf_col_deleter = [](gdf_column* col){ if (col) { col->size = 0; if(col->data){ CUDA_RT_CALL(cudaFree(col->data)); } delete col; } }; using gdf_column_ptr = typename std::unique_ptr<gdf_column, decltype(gdf_col_deleter)>; std::function<void(gdf_graph*)> gdf_graph_deleter = [](gdf_graph* G){delete G;}; using gdf_graph_ptr = typename std::unique_ptr<gdf_graph,decltype(gdf_graph_deleter)>; std::string getFileName(const std::string& s) { char sep = '/'; #ifdef _WIN32 sep = '\\'; #endif size_t i = s.rfind(sep, s.length()); if (i != std::string::npos) { return(s.substr(i+1, s.length() - i)); } return(""); } template <typename T> void verbose_diff(std::vector<T> & v1, std::vector<T> & v2) { for (unsigned int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { std::cout << "[" << i <<"] : " << v1[i] << " vs. "<< v2[i]<<std::endl; } } } template <typename T> int eq(std::vector<T> & v1, std::vector<T> & v2) { if (v1 == v2) return 0; else { verbose_diff(v1,v2); return 1; } } template <typename T> void printv(size_t n, T* vec, int offset) { thrust::device_ptr<T> dev_ptr(vec); std::cout.precision(15); std::cout << "sample size = "<< n << ", offset = "<< offset << std::endl; thrust::copy(dev_ptr+offset,dev_ptr+offset+n, std::ostream_iterator<T>(std::cout, " ")); std::cout << std::endl; } template <typename T_ELEM> void ref_csr2csc (int m, int n, int nnz, const T_ELEM *csrVals, const int *csrRowptr, const int *csrColInd, T_ELEM *cscVals, int *cscRowind, int *cscColptr, int base=0){ int i,j, row, col, index; int * counters; T_ELEM val; /* early return */ if ((m <= 0) || (n <= 0) || (nnz <= 0)){ return; } /* build compressed column pointers */ memset(cscColptr, 0, (n+1)*sizeof(cscColptr[0])); cscColptr[0]=base; for (i=0; i<nnz; i++){ cscColptr[1+csrColInd[i]-base]++; } for(i=0; i<n; i++){ cscColptr[i+1]+=cscColptr[i]; } /* expand row indecis and copy them and values into csc arrays according to permutation */ counters = (int *)malloc(n*sizeof(counters[0])); memset(counters, 0, n*sizeof(counters[0])); for (i=0; i<m; i++){ for (j=csrRowptr[i]; j<csrRowptr[i+1]; j++){ row = i+base; col = csrColInd[j-base]; index=cscColptr[col-base]-base+counters[col-base]; counters[col-base]++; cscRowind[index]=row; if(csrVals!=NULL || cscVals!=NULL){ val = csrVals[j-base]; cscVals[index] = val; } } } free(counters); } template <typename T> int transition_matrix_cpu(int n, int e, int *csrRowPtrA, int *csrColIndA, T *weight, T* is_leaf) //omp_set_num_threads(4); //#pragma omp parallel { int j,row, row_size; //#pragma omp for for (row=0; row<n; row++) { row_size = csrRowPtrA[row+1] - csrRowPtrA[row]; if (row_size == 0) is_leaf[row]=1.0; else { is_leaf[row]=0.0; for (j=csrRowPtrA[row]; j<csrRowPtrA[row+1]; j++) weight[j] = 1.0/row_size; } } return 0; } template <typename T> void printCsrMatI(int m, int n, int nnz,std::vector<int> & csrRowPtr, std::vector<uint16_t> & csrColInd, std::vector<T> & csrVal) { std::vector<T> v(n); std::stringstream ss; ss.str(std::string()); ss << std::fixed; ss << std::setprecision(2); for (int i = 0; i < m; i++) { std::fill(v.begin(),v.end(),0); for (int j = csrRowPtr[i]; j < csrRowPtr[i+1]; j++) v[csrColInd[j]] = csrVal[j]; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); ss << "\n"; } ss << "\n"; std::cout<<ss.str(); } /// Read matrix properties from Matrix Market file /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param t (Output) MM_typecode with matrix properties. * @param m (Output) Number of matrix rows. * @param n (Output) Number of matrix columns. * @param nnz (Output) Number of non-zero matrix entries. * @return Zero if properties were read successfully. Otherwise * non-zero. */ template <typename IndexType_> int mm_properties(FILE * f, int tg, MM_typecode * t, IndexType_ * m, IndexType_ * n, IndexType_ * nnz) { // Read matrix properties from file int mint, nint, nnzint; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(*t) || !mm_is_coordinate(*t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&mint,&nint,&nnzint)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(*t) && !mm_is_real(*t) && !mm_is_integer(*t) && !mm_is_complex(*t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } *m = mint; *n = nint; *nnz = nnzint; // Find total number of non-zero entries if(tg && !mm_is_general(*t)) { // Non-diagonal entries should be counted twice IndexType_ nnzOld = *nnz; *nnz *= 2; // Diagonal entries should not be double-counted int i; int st; for(i=0; i<nnzOld; ++i) { // Read matrix entry IndexType_ row, col; double rval, ival; if (mm_is_pattern(*t)) st = fscanf(f, "%d %d\n", &row, &col); else if (mm_is_real(*t) || mm_is_integer(*t)) st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Check if entry is diagonal if(row == col) --(*nnz); } } return 0; } /// Read Matrix Market file and convert to COO format matrix /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param nnz Number of non-zero matrix entries. * @param cooRowInd (Output) Row indices for COO matrix. Should have * at least nnz entries. * @param cooColInd (Output) Column indices for COO matrix. Should * have at least nnz entries. * @param cooRVal (Output) Real component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @param cooIVal (Output) Imaginary component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @return Zero if matrix was read successfully. Otherwise non-zero. */ template <typename IndexType_, typename ValueType_> int mm_to_coo(FILE *f, int tg, IndexType_ nnz, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal , ValueType_ * cooIVal) { // Read matrix properties from file MM_typecode t; int m, n, nnzOld; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,&t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(t) || !mm_is_coordinate(t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&m,&n,&nnzOld)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(t) && !mm_is_real(t) && !mm_is_integer(t) && !mm_is_complex(t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } // Add each matrix entry in file to COO format matrix IndexType_ i; // Entry index in Matrix Market file IndexType_ j = 0; // Entry index in COO format matrix for(i=0;i<nnzOld;++i) { // Read entry from file int row, col; double rval, ival; int st; if (mm_is_pattern(t)) { st = fscanf(f, "%d %d\n", &row, &col); rval = 1.0; ival = 0.0; } else if (mm_is_real(t) || mm_is_integer(t)) { st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); ival = 0.0; } else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Switch to 0-based indexing --row; --col; // Record entry cooRowInd[j] = row; cooColInd[j] = col; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; // Add symmetric complement of non-diagonal entries if(tg && !mm_is_general(t) && (row!=col)) { // Modify entry value if matrix is skew symmetric or Hermitian if(mm_is_skew(t)) { rval = -rval; ival = -ival; } else if(mm_is_hermitian(t)) { ival = -ival; } // Record entry cooRowInd[j] = col; cooColInd[j] = row; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; } } return 0; } /// Compare two tuples based on the element indexed by i class lesser_tuple { const int i; public: lesser_tuple(int _i) : i(_i) {} template<typename Tuple1, typename Tuple2> __host__ __device__ bool operator()(const Tuple1 t1, const Tuple2 t2) { switch(i) { case 0: return (thrust::get<0>(t1) < thrust::get<0>(t2)); case 1: return (thrust::get<1>(t1) < thrust::get<1>(t2)); default: return (thrust::get<0>(t1) < thrust::get<0>(t2)); } } }; /// Sort entries in COO format matrix /** Sort is stable. * * @param nnz Number of non-zero matrix entries. * @param sort_by_row Boolean indicating whether matrix entries * will be sorted by row index or by column index. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component for COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component COO matrix entries. Ignored if * null pointer. */ template <typename IndexType_, typename ValueType_> void coo_sort(IndexType_ nnz, int sort_by_row, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal, ValueType_ * cooIVal) { // Determine whether to sort by row or by column int i; if(sort_by_row == 0) i = 1; else i = 0; // Apply stable sort using namespace thrust; if((cooRVal==NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz)), lesser_tuple(i)); else if((cooRVal==NULL) && (cooIVal!=NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooIVal+nnz)), lesser_tuple(i)); else if((cooRVal!=NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooRVal+nnz)), lesser_tuple(i)); else stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz, cooRVal+nnz,cooIVal+nnz)), lesser_tuple(i)); } /// Compress sorted list of indices /** For use in converting COO format matrix to CSR or CSC format. * * @param n Maximum index. * @param nnz Number of non-zero matrix entries. * @param sortedIndices Sorted list of indices (COO format). * @param compressedIndices (Output) Compressed list of indices (CSR * or CSC format). Should have at least n+1 entries. */ template <typename IndexType_> void coo_compress(IndexType_ m, IndexType_ n, IndexType_ nnz, const IndexType_ * __restrict__ sortedIndices, IndexType_ * __restrict__ compressedIndices) { IndexType_ i; // Initialize everything to zero memset(compressedIndices, 0, (m+1)*sizeof(IndexType_)); // Count number of elements per row for(i=0; i<nnz; ++i) ++(compressedIndices[sortedIndices[i]+1]); // Compute cumulative sum to obtain row offsets/pointers for(i=0; i<m; ++i) compressedIndices[i+1] += compressedIndices[i]; } /// Convert COO format matrix to CSR format /** On output, matrix entries in COO format matrix will be sorted * (primarily by row index, secondarily by column index). * * @param m Number of matrix rows. * @param n Number of matrix columns. * @param nnz Number of non-zero matrix entries. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component of COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component of COO matrix entries. Ignored * if null pointer. * @param csrRowPtr Row pointers for CSR matrix. Should have at least * n+1 entries. * @param csrColInd Column indices for CSR matrix (identical to * output of cooColInd). Should have at least nnz entries. Ignored if * null pointer. * @param csrRVal Real component of CSR matrix entries (identical to * output of cooRVal). Should have at least nnz entries. Ignored if * null pointer. * @param csrIVal Imaginary component of CSR matrix entries * (identical to output of cooIVal). Should have at least nnz * entries. Ignored if null pointer. * @return Zero if matrix was converted successfully. Otherwise * non-zero. */ template <typename IndexType_, typename ValueType_> int coo_to_csr(IndexType_ m, IndexType_ n, IndexType_ nnz, IndexType_ * __restrict__ cooRowInd, IndexType_ * __restrict__ cooColInd, ValueType_ * __restrict__ cooRVal, ValueType_ * __restrict__ cooIVal, IndexType_ * __restrict__ csrRowPtr, IndexType_ * __restrict__ csrColInd, ValueType_ * __restrict__ csrRVal, ValueType_ * __restrict__ csrIVal) { // Convert COO to CSR matrix coo_sort(nnz, 0, cooRowInd, cooColInd, cooRVal, cooIVal); coo_sort(nnz, 1, cooRowInd, cooColInd, cooRVal, cooIVal); coo_compress(m, n, nnz, cooRowInd, csrRowPtr); // Copy arrays if(csrColInd!=NULL) memcpy(csrColInd, cooColInd, nnz*sizeof(IndexType_)); if((cooRVal!=NULL) && (csrRVal!=NULL)) memcpy(csrRVal, cooRVal, nnz*sizeof(ValueType_)); if((cooIVal!=NULL) && (csrIVal!=NULL)) memcpy(csrIVal, cooIVal, nnz*sizeof(ValueType_)); return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<float>& val ) { size_t is_read1; double* t_storage = new double[n]; is_read1 = fread(t_storage, sizeof(double), n, fpin); for (int i = 0; i < n; i++) { if (t_storage[i] == DBL_MAX) val[i] = FLT_MAX; else if (t_storage[i] == -DBL_MAX) val[i] = -FLT_MAX; else val[i] = static_cast<float>(t_storage[i]); } delete[] t_storage; if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<double>& val ) { size_t is_read1; is_read1 = fread(&val[0], sizeof(double), n, fpin); if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } // Creates a gdf_column from a std::vector template <typename col_type> gdf_column_ptr create_gdf_column(std::vector<col_type> const & host_vector) { // Create a new instance of a gdf_column with a custom deleter that will free // the associated device memory when it eventually goes out of scope gdf_column_ptr the_column{new gdf_column, gdf_col_deleter}; // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaMallocManaged(&(the_column->data), input_size_bytes); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; return the_column; } // Creates a gdf_column from a std::vector template <typename col_type> void create_gdf_column(std::vector<col_type> const & host_vector, gdf_column * the_column) { // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaMallocManaged(&(the_column->data), input_size_bytes); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; } void gdf_col_delete(gdf_column* col) { if (col) { col->size = 0; if(col->data) if (cudaFree(col->data) != cudaSuccess) std::cerr << "CUDA ERROR : " << cudaGetErrorString(cudaGetLastError()) <<std::endl; delete col; col->data = nullptr; col = nullptr; } }
blurpart.c
#include <stdlib.h> #include "blurpart.h" void blurpart(float* v,int m,int n,float*output){ #pragma omp parallel for for (int H32 = 0; H32 < 1; H32++) { for (int H33 = 0; H33 < m; H33++) { float tmp2 = 0; float tmp3 = 0; if (0 <= H32 - (1)) { float tmp4 = 0; float tmp5 = 0; if (0 <= H33 - (1)) { tmp5 = v[(((m)) * (H32 - (1))) + H33 - (1)]; } float tmp6 = 0; tmp6 = v[(((m)) * (H32 - (1))) + H33]; tmp4 = tmp5 + tmp6; float tmp7 = 0; if (H33 + 1 < m) { tmp7 = v[(((m)) * (H32 - (1))) + H33 + 1]; } tmp3 = tmp4 + tmp7; } float tmp8 = 0; float tmp9 = 0; float tmp10 = 0; if (0 <= H33 - (1)) { tmp10 = v[(((m)) * (H32)) + H33 - (1)]; } float tmp11 = 0; tmp11 = v[(((m)) * (H32)) + H33]; tmp9 = tmp10 + tmp11; float tmp12 = 0; if (H33 + 1 < m) { tmp12 = v[(((m)) * (H32)) + H33 + 1]; } tmp8 = tmp9 + tmp12; tmp2 = tmp3 + tmp8; float tmp13 = 0; float tmp14 = 0; float tmp15 = 0; if (0 <= H33 - (1)) { tmp15 = v[(((m)) * (H32 + 1)) + H33 - (1)]; } float tmp16 = 0; tmp16 = v[(((m)) * (H32 + 1)) + H33]; tmp14 = tmp15 + tmp16; float tmp17 = 0; if (H33 + 1 < m) { tmp17 = v[(((m)) * (H32 + 1)) + H33 + 1]; } tmp13 = tmp14 + tmp17; output[(m) * (H32) + H33] = tmp2 + tmp13; } } #pragma omp parallel for for (int H34 = 1; H34 < (n - (1 + 0)); H34++) { for (int H43 = 0; H43 < 1; H43++) { float tmp18 = 0; float tmp19 = 0; float tmp20 = 0; float tmp21 = 0; if (0 <= H43 - (1)) { tmp21 = v[(((m)) * (H34 - (1))) + H43 - (1)]; } float tmp22 = 0; tmp22 = v[(((m)) * (H34 - (1))) + H43]; tmp20 = tmp21 + tmp22; float tmp23 = 0; tmp23 = v[(((m)) * (H34 - (1))) + H43 + 1]; tmp19 = tmp20 + tmp23; float tmp24 = 0; float tmp25 = 0; float tmp26 = 0; if (0 <= H43 - (1)) { tmp26 = v[(((m)) * (H34)) + H43 - (1)]; } float tmp27 = 0; tmp27 = v[(((m)) * (H34)) + H43]; tmp25 = tmp26 + tmp27; float tmp28 = 0; tmp28 = v[(((m)) * (H34)) + H43 + 1]; tmp24 = tmp25 + tmp28; tmp18 = tmp19 + tmp24; float tmp29 = 0; float tmp30 = 0; float tmp31 = 0; if (0 <= H43 - (1)) { tmp31 = v[(((m)) * (H34 + 1)) + H43 - (1)]; } float tmp32 = 0; tmp32 = v[(((m)) * (H34 + 1)) + H43]; tmp30 = tmp31 + tmp32; float tmp33 = 0; tmp33 = v[(((m)) * (H34 + 1)) + H43 + 1]; tmp29 = tmp30 + tmp33; output[(((1 + ((m - (1 + 0)) - (1))) + (m - (m - (1))))) * (((H34 - (1)) + 1)) + H43] = tmp18 + tmp29; } for (int H44 = 1; H44 < (m - (1 + 0)); H44++) { float tmp34 = 0; float tmp35 = 0; float tmp36 = 0; float tmp37 = 0; tmp37 = v[(((m)) * (H34 - (1))) + H44 - (1)]; float tmp38 = 0; tmp38 = v[(((m)) * (H34 - (1))) + H44]; tmp36 = tmp37 + tmp38; float tmp39 = 0; tmp39 = v[(((m)) * (H34 - (1))) + H44 + 1]; tmp35 = tmp36 + tmp39; float tmp40 = 0; float tmp41 = 0; float tmp42 = 0; tmp42 = v[(((m)) * (H34)) + H44 - (1)]; float tmp43 = 0; tmp43 = v[(((m)) * (H34)) + H44]; tmp41 = tmp42 + tmp43; float tmp44 = 0; tmp44 = v[(((m)) * (H34)) + H44 + 1]; tmp40 = tmp41 + tmp44; tmp34 = tmp35 + tmp40; float tmp45 = 0; float tmp46 = 0; float tmp47 = 0; tmp47 = v[(((m)) * (H34 + 1)) + H44 - (1)]; float tmp48 = 0; tmp48 = v[(((m)) * (H34 + 1)) + H44]; tmp46 = tmp47 + tmp48; float tmp49 = 0; tmp49 = v[(((m)) * (H34 + 1)) + H44 + 1]; tmp45 = tmp46 + tmp49; output[(((1 + ((m - (1 + 0)) - (1))) + (m - (m - (1))))) * (((H34 - (1)) + 1)) + ((H44 - (1)) + 1)] = tmp34 + tmp45; } for (int H45 = m - (1); H45 < m; H45++) { float tmp50 = 0; float tmp51 = 0; float tmp52 = 0; float tmp53 = 0; float tmp54 = 0; tmp54 = v[(((m)) * (H34 - (1))) + H45 - (1)]; float tmp55 = 0; tmp55 = v[(((m)) * (H34 - (1))) + H45]; tmp53 = tmp54 + tmp55; float tmp56 = 0; if (H45 + 1 < m) { tmp56 = v[(((m)) * (H34 - (1))) + H45 + 1]; } tmp52 = tmp53 + tmp56; float tmp57 = 0; float tmp58 = 0; float tmp59 = 0; tmp59 = v[(((m)) * (H34)) + H45 - (1)]; float tmp60 = 0; tmp60 = v[(((m)) * (H34)) + H45]; tmp58 = tmp59 + tmp60; float tmp61 = 0; if (H45 + 1 < m) { tmp61 = v[(((m)) * (H34)) + H45 + 1]; } tmp57 = tmp58 + tmp61; tmp51 = tmp52 + tmp57; float tmp62 = 0; float tmp63 = 0; tmp63 = v[(((m)) * (H34 + 1)) + H45 - (1)]; float tmp64 = 0; tmp64 = v[(((m)) * (H34 + 1)) + H45]; tmp62 = tmp63 + tmp64; tmp50 = tmp51 + tmp62; float tmp65 = 0; if (H45 + 1 < m) { tmp65 = v[(((m)) * (H34 + 1)) + H45 + 1]; } output[(((1 + ((m - (1 + 0)) - (1))) + (m - (m - (1))))) * (((H34 - (1)) + 1)) + ((H45 - (m - (1))) + (1 + ((m - (1 + 0)) - (1))))] = tmp50 + tmp65; } } #pragma omp parallel for for (int H46 = n - (1); H46 < n; H46++) { for (int H47 = 0; H47 < m; H47++) { float tmp66 = 0; float tmp67 = 0; float tmp68 = 0; float tmp69 = 0; if (0 <= H47 - (1)) { tmp69 = v[(((m)) * (H46 - (1))) + H47 - (1)]; } float tmp70 = 0; tmp70 = v[(((m)) * (H46 - (1))) + H47]; tmp68 = tmp69 + tmp70; float tmp71 = 0; if (H47 + 1 < m) { tmp71 = v[(((m)) * (H46 - (1))) + H47 + 1]; } tmp67 = tmp68 + tmp71; float tmp72 = 0; float tmp73 = 0; float tmp74 = 0; if (0 <= H47 - (1)) { tmp74 = v[(((m)) * (H46)) + H47 - (1)]; } float tmp75 = 0; tmp75 = v[(((m)) * (H46)) + H47]; tmp73 = tmp74 + tmp75; float tmp76 = 0; if (H47 + 1 < m) { tmp76 = v[(((m)) * (H46)) + H47 + 1]; } tmp72 = tmp73 + tmp76; tmp66 = tmp67 + tmp72; float tmp77 = 0; if (H46 + 1 < n) { float tmp78 = 0; float tmp79 = 0; if (0 <= H47 - (1)) { tmp79 = v[(((m)) * (H46 + 1)) + H47 - (1)]; } float tmp80 = 0; tmp80 = v[(((m)) * (H46 + 1)) + H47]; tmp78 = tmp79 + tmp80; float tmp81 = 0; if (H47 + 1 < m) { tmp81 = v[(((m)) * (H46 + 1)) + H47 + 1]; } tmp77 = tmp78 + tmp81; } output[(m) * (((H46 - (n - (1))) + (1 + ((n - (1 + 0)) - (1))))) + H47] = tmp66 + tmp77; } } }
par_cheby.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Chebyshev setup and solve * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "_hypre_parcsr_mv.h" #include "float.h" /****************************************************************************** Chebyshev relaxation Can specify order 1-4 (this is the order of the resid polynomial)- here we explicitly code the coefficients (instead of iteratively determining) variant 0: standard chebyshev this is rlx 11 if scale = 0, and 16 if scale == 1 variant 1: modified cheby: T(t)* f(t) where f(t) = (1-b/t) this is rlx 15 if scale = 0, and 17 if scale == 1 ratio indicates the percentage of the whole spectrum to use (so .5 means half, and .1 means 10percent) *******************************************************************************/ /** * @brief Setups of coefficients (and optional diagonal scaling elements) for * Chebyshev relaxation * * Will calculate ds_ptr on device/host depending on where A is located * * @param[in] A Matrix for which to seteup * @param[in] max_eig Maximum eigenvalue * @param[in] min_eig Maximum eigenvalue * @param[in] fraction Fraction used to calculate lower bound * @param[in] order Polynomial order to use [1,4] * @param[in] scale Whether or not to scale by the diagonal * @param[in] variant Whether or not to use a variant of Chebyshev (0 standard, 1 variant) * @param[out] coefs_ptr *coefs_ptr will be allocated to contain coefficients of the polynomial * @param[out] ds_ptr *ds_ptr will be allocated to allow scaling by the diagonal */ HYPRE_Int hypre_ParCSRRelax_Cheby_Setup(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Real max_eig, HYPRE_Real min_eig, HYPRE_Real fraction, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, HYPRE_Real **coefs_ptr, HYPRE_Real **ds_ptr) /* initial/updated approximation */ { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real theta, delta; HYPRE_Real den; HYPRE_Real upper_bound = 0.0, lower_bound = 0.0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Real *coefs = NULL; HYPRE_Int cheby_order; HYPRE_Real *ds_data = NULL; /* u = u + p(A)r */ if (order > 4) { order = 4; } if (order < 1) { order = 1; } coefs = hypre_CTAlloc(HYPRE_Real, order+1, HYPRE_MEMORY_HOST); /* we are using the order of p(A) */ cheby_order = order - 1; if (min_eig >= 0.0) { /* make sure we are large enough - Adams et al. 2003 */ upper_bound = max_eig * 1.1; /* lower_bound = max_eig/fraction; */ lower_bound = (upper_bound - min_eig) * fraction + min_eig; } else if (max_eig <= 0.0) { upper_bound = min_eig * 1.1; lower_bound = max_eig - (max_eig - upper_bound) * fraction; } /* theta and delta */ theta = (upper_bound + lower_bound)/2; delta = (upper_bound - lower_bound)/2; if (variant == 1) { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less that resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* (del - t + 2*th)/(th^2 + del*th) */ den = (theta*theta + delta*theta); coefs[0] = (delta + 2*theta)/den; coefs[1] = -1.0/den; break; case 2: /* (4*del*th - del^2 - t*(2*del + 6*th) + 2*t^2 + 6*th^2)/(2*del*th^2 - del^2*th - del^3 + 2*th^3)*/ den = 2*delta*theta*theta - delta*delta*theta - pow(delta,3) + 2*pow(theta,3); coefs[0] = (4*delta*theta - pow(delta,2) + 6*pow(theta,2))/den; coefs[1] = -(2*delta + 6*theta)/den; coefs[2] = 2/den; break; case 3: /* -(6*del^2*th - 12*del*th^2 - t^2*(4*del + 16*th) + t*(12*del*th - 3*del^2 + 24*th^2) + 3*del^3 + 4*t^3 - 16*th^3)/(4*del*th^3 - 3*del^2*th^2 - 3*del^3*th + 4*th^4)*/ den = - (4*delta*pow(theta,3) - 3*pow(delta,2)*pow(theta,2) - 3*pow(delta,3)*theta + 4*pow(theta,4) ); coefs[0] = (6*pow(delta,2)*theta - 12*delta*pow(theta,2) + 3*pow(delta,3) - 16*pow(theta,3) )/den; coefs[1] = (12*delta*theta - 3*pow(delta,2) + 24*pow(theta,2))/den; coefs[2] = -( 4*delta + 16*theta)/den; coefs[3] = 4/den; break; } } else /* standard chebyshev */ { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less thatn resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* ( 2*t - 4*th)/(del^2 - 2*th^2) */ den = delta*delta - 2*theta*theta; coefs[0] = -4*theta/den; coefs[1] = 2/den; break; case 2: /* (3*del^2 - 4*t^2 + 12*t*th - 12*th^2)/(3*del^2*th - 4*th^3)*/ den = 3*(delta*delta)*theta - 4*(theta*theta*theta); coefs[0] = (3*delta*delta - 12 *theta*theta)/den; coefs[1] = 12*theta/den; coefs[2] = -4/den; break; case 3: /*(t*(8*del^2 - 48*th^2) - 16*del^2*th + 32*t^2*th - 8*t^3 + 32*th^3)/(del^4 - 8*del^2*th^2 + 8*th^4)*/ den = pow(delta,4) - 8*delta*delta*theta*theta + 8*pow(theta,4); coefs[0] = (32*pow(theta,3)- 16*delta*delta*theta)/den; coefs[1] = (8*delta*delta - 48*theta*theta)/den; coefs[2] = 32*theta/den; coefs[3] = -8/den; break; } } *coefs_ptr = coefs; if (scale) { /*grab 1/sqrt(abs(diagonal)) */ ds_data = hypre_CTAlloc(HYPRE_Real, num_rows, hypre_ParCSRMatrixMemoryLocation(A)); hypre_CSRMatrixExtractDiagonal(hypre_ParCSRMatrixDiag(A), ds_data, 4); } /* end of scaling code */ *ds_ptr = ds_data; return hypre_error_flag; } /** * @brief Solve using a chebyshev polynomial on the host * * @param[in] A Matrix to relax with * @param[in] f right-hand side * @param[in] ds_data Diagonal information * @param[in] coefs Polynomial coefficients * @param[in] order Order of the polynomial * @param[in] scale Whether or not to scale by diagonal * @param[in] scale Whether or not to use a variant * @param[in,out] u Initial/updated approximation * @param[in] v Temp vector * @param[in] r Temp Vector * @param[in] orig_u_vec Temp Vector * @param[in] tmp Temp Vector */ HYPRE_Int hypre_ParCSRRelax_Cheby_SolveHost(hypre_ParCSRMatrix *A, /* matrix to relax with */ hypre_ParVector *f, /* right-hand side */ HYPRE_Real *ds_data, HYPRE_Real *coefs, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, hypre_ParVector *u, /* initial/updated approximation */ hypre_ParVector *v, /* temporary vector */ hypre_ParVector *r, /* another vector */ hypre_ParVector *orig_u_vec, /*another temp vector */ hypre_ParVector *tmp_vec) /*a potential temp vector */ { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); HYPRE_Real *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f)); HYPRE_Real *v_data = hypre_VectorData(hypre_ParVectorLocalVector(v)); HYPRE_Real *r_data = hypre_VectorData(hypre_ParVectorLocalVector(r)); HYPRE_Int i, j; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Real mult; HYPRE_Real *orig_u; HYPRE_Int cheby_order; HYPRE_Real *tmp_data; /* u = u + p(A)r */ if (order > 4) order = 4; if (order < 1) order = 1; /* we are using the order of p(A) */ cheby_order = order -1; hypre_assert(hypre_VectorSize(hypre_ParVectorLocalVector(orig_u_vec)) >= num_rows); orig_u = hypre_VectorData(hypre_ParVectorLocalVector(orig_u_vec)); if (!scale) { /* get residual: r = f - A*u */ hypre_ParVectorCopy(f, r); hypre_ParCSRMatrixMatvec(-1.0, A, u, 1.0, r); /* o = u; u = r .* coef */ for ( i = 0; i < num_rows; i++ ) { orig_u[i] = u_data[i]; u_data[i] = r_data[i] * coefs[cheby_order]; } for (i = cheby_order - 1; i >= 0; i-- ) { hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, v); mult = coefs[i]; /* u = mult * r + v */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = mult * r_data[j] + v_data[j]; } } /* u = o + u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for ( i = 0; i < num_rows; i++ ) { u_data[i] = orig_u[i] + u_data[i]; } } else /* scaling! */ { /*grab 1/sqrt(diagonal) */ tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(tmp_vec)); /* get ds_data and get scaled residual: r = D^(-1/2)f - * D^(-1/2)A*u */ hypre_ParCSRMatrixMatvec(-1.0, A, u, 0.0, tmp_vec); /* r = ds .* (f + tmp) */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { r_data[j] = ds_data[j] * (f_data[j] + tmp_data[j]); } /* save original u, then start the iteration by multiplying r by the cheby coef.*/ /* o = u; u = r * coef */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { orig_u[j] = u_data[j]; /* orig, unscaled u */ u_data[j] = r_data[j] * coefs[cheby_order]; } /* now do the other coefficients */ for (i = cheby_order - 1; i >= 0; i-- ) { /* v = D^(-1/2)AD^(-1/2)u */ /* tmp = ds .* u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { tmp_data[j] = ds_data[j] * u_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, tmp_vec, 0.0, v); /* u_new = coef*r + v*/ mult = coefs[i]; /* u = coef * r + ds .* v */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = mult * r_data[j] + ds_data[j]*v_data[j]; } } /* end of cheby_order loop */ /* now we have to scale u_data before adding it to u_orig*/ /* u = orig_u + ds .* u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = orig_u[j] + ds_data[j]*u_data[j]; } }/* end of scaling code */ return hypre_error_flag; } /** * @brief Solve using a chebyshev polynomial * * Determines whether to solve on host or device * * @param[in] A Matrix to relax with * @param[in] f right-hand side * @param[in] ds_data Diagonal information * @param[in] coefs Polynomial coefficients * @param[in] order Order of the polynomial * @param[in] scale Whether or not to scale by diagonal * @param[in] scale Whether or not to use a variant * @param[in,out] u Initial/updated approximation * @param[out] v Temp vector * @param[out] r Temp Vector * @param[out] orig_u_vec Temp Vector * @param[out] tmp_vec Temp Vector */ HYPRE_Int hypre_ParCSRRelax_Cheby_Solve(hypre_ParCSRMatrix *A, /* matrix to relax with */ hypre_ParVector *f, /* right-hand side */ HYPRE_Real *ds_data, HYPRE_Real *coefs, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, hypre_ParVector *u, /* initial/updated approximation */ hypre_ParVector *v, /* temporary vector */ hypre_ParVector *r, /*another temp vector */ hypre_ParVector *orig_u_vec, /*another temp vector */ hypre_ParVector *tmp_vec) /*another temp vector */ { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ParCSRRelaxChebySolve"); #endif HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(hypre_ParCSRMatrixMemoryLocation(A)); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { ierr = hypre_ParCSRRelax_Cheby_SolveHost(A, f, ds_data, coefs, order, scale, variant, u, v, r, orig_u_vec, tmp_vec); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) else { ierr = hypre_ParCSRRelax_Cheby_SolveDevice(A, f, ds_data, coefs, order, scale, variant, u, v, r, orig_u_vec, tmp_vec); } #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; }
resize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE % % R R E SS I ZZ E % % RRRR EEE SSS I ZZZ EEE % % R R E SS I ZZ E % % R R EEEEE SSSSS IIIII ZZZZZ EEEEE % % % % % % MagickCore Image Resize Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.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/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/magick.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resize-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #if defined(MAGICKCORE_LQR_DELEGATE) #include <lqr.h> #endif /* Typedef declarations. */ struct _ResizeFilter { double (*filter)(const double,const ResizeFilter *), (*window)(const double,const ResizeFilter *), support, /* filter region of support - the filter support limit */ window_support, /* window support, usally equal to support (expert only) */ scale, /* dimension scaling to fit window support (usally 1.0) */ blur, /* x-scale (blur-sharpen) */ coefficient[7]; /* cubic coefficents for BC-cubic filters */ ResizeWeightingFunctionType filterWeightingType, windowWeightingType; size_t signature; }; /* Forward declaractions. */ static double I0(double x), BesselOrderOne(double), Sinc(const double, const ResizeFilter *), SincFast(const double, const ResizeFilter *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F i l t e r F u n c t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % These are the various filter and windowing functions that are provided. % % They are internal to this module only. See AcquireResizeFilterInfo() for % details of the access to these functions, via the GetResizeFilterSupport() % and GetResizeFilterWeight() API interface. % % The individual filter functions have this format... % % static MagickRealtype *FilterName(const double x,const double support) % % A description of each parameter follows: % % o x: the distance from the sampling point generally in the range of 0 to % support. The GetResizeFilterWeight() ensures this a positive value. % % o resize_filter: current filter information. This allows function to % access support, and possibly other pre-calculated information defining % the functions. % */ static double Blackman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Blackman: 2nd order cosine windowing function: 0.42 + 0.5 cos(pi x) + 0.08 cos(2pi x) Refactored by Chantal Racette and Nicolas Robidoux to one trig call and five flops. */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.34+cosine*(0.5+cosine*0.16)); } static double Bohman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Bohman: 2rd Order cosine windowing function: (1-x) cos(pi x) + sin(pi x) / pi. Refactored by Nicolas Robidoux to one trig call, one sqrt call, and 7 flops, taking advantage of the fact that the support of Bohman is 1.0 (so that we know that sin(pi x) >= 0). */ const double cosine = cos((double) (MagickPI*x)); const double sine=sqrt(1.0-cosine*cosine); magick_unreferenced(resize_filter); return((1.0-x)*cosine+(1.0/MagickPI)*sine); } static double Box(const double magick_unused(x), const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(x); magick_unreferenced(resize_filter); /* A Box filter is a equal weighting function (all weights equal). DO NOT LIMIT results by support or resize point sampling will work as it requests points beyond its normal 0.0 support size. */ return(1.0); } static double Cosine(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Cosine window function: cos((pi/2)*x). */ return(cos((double) (MagickPI2*x))); } static double CubicBC(const double x,const ResizeFilter *resize_filter) { /* Cubic Filters using B,C determined values: Mitchell-Netravali B = 1/3 C = 1/3 "Balanced" cubic spline filter Catmull-Rom B = 0 C = 1/2 Interpolatory and exact on linears Spline B = 1 C = 0 B-Spline Gaussian approximation Hermite B = 0 C = 0 B-Spline interpolator See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics, Volume 22, Number 4, August 1988 http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/ Mitchell.pdf. Coefficents are determined from B,C values: P0 = ( 6 - 2*B )/6 = coeff[0] P1 = 0 P2 = (-18 +12*B + 6*C )/6 = coeff[1] P3 = ( 12 - 9*B - 6*C )/6 = coeff[2] Q0 = ( 8*B +24*C )/6 = coeff[3] Q1 = ( -12*B -48*C )/6 = coeff[4] Q2 = ( 6*B +30*C )/6 = coeff[5] Q3 = ( - 1*B - 6*C )/6 = coeff[6] which are used to define the filter: P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1 Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x < 2 which ensures function is continuous in value and derivative (slope). */ if (x < 1.0) return(resize_filter->coefficient[0]+x*(x* (resize_filter->coefficient[1]+x*resize_filter->coefficient[2]))); if (x < 2.0) return(resize_filter->coefficient[3]+x*(resize_filter->coefficient[4]+x* (resize_filter->coefficient[5]+x*resize_filter->coefficient[6]))); return(0.0); } static double CubicSpline(const double x,const ResizeFilter *resize_filter) { if (resize_filter->support <= 2.0) { /* 2-lobe Spline filter. */ if (x < 1.0) return(((x-9.0/5.0)*x-1.0/5.0)*x+1.0); if (x < 2.0) return(((-1.0/3.0*(x-1.0)+4.0/5.0)*(x-1.0)-7.0/15.0)*(x-1.0)); return(0.0); } if (resize_filter->support <= 3.0) { /* 3-lobe Spline filter. */ if (x < 1.0) return(((13.0/11.0*x-453.0/209.0)*x-3.0/209.0)*x+1.0); if (x < 2.0) return(((-6.0/11.0*(x-1.0)+270.0/209.0)*(x-1.0)-156.0/209.0)*(x-1.0)); if (x < 3.0) return(((1.0/11.0*(x-2.0)-45.0/209.0)*(x-2.0)+26.0/209.0)*(x-2.0)); return(0.0); } /* 4-lobe Spline filter. */ if (x < 1.0) return(((49.0/41.0*x-6387.0/2911.0)*x-3.0/2911.0)*x+1.0); if (x < 2.0) return(((-24.0/41.0*(x-1.0)+4032.0/2911.0)*(x-1.0)-2328.0/2911.0)*(x-1.0)); if (x < 3.0) return(((6.0/41.0*(x-2.0)-1008.0/2911.0)*(x-2.0)+582.0/2911.0)*(x-2.0)); if (x < 4.0) return(((-1.0/41.0*(x-3.0)+168.0/2911.0)*(x-3.0)-97.0/2911.0)*(x-3.0)); return(0.0); } static double Gaussian(const double x,const ResizeFilter *resize_filter) { /* Gaussian with a sigma = 1/2 (or as user specified) Gaussian Formula (1D) ... exp( -(x^2)/((2.0*sigma^2) ) / (sqrt(2*PI)*sigma^2)) Gaussian Formula (2D) ... exp( -(x^2+y^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) or for radius exp( -(r^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) Note that it is only a change from 1-d to radial form is in the normalization multiplier which is not needed or used when Gaussian is used as a filter. The constants are pre-calculated... coeff[0]=sigma; coeff[1]=1.0/(2.0*sigma^2); coeff[2]=1.0/(sqrt(2*PI)*sigma^2); exp( -coeff[1]*(x^2)) ) * coeff[2]; However the multiplier coeff[1] is need, the others are informative only. This separates the gaussian 'sigma' value from the 'blur/support' settings allowing for its use in special 'small sigma' gaussians, without the filter 'missing' pixels because the support becomes too small. */ return(exp((double)(-resize_filter->coefficient[1]*x*x))); } static double Hann(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Cosine window function: 0.5+0.5*cos(pi*x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.5+0.5*cosine); } static double Hamming(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Offset cosine window function: .54 + .46 cos(pi x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.54+0.46*cosine); } static double Jinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* See Pratt "Digital Image Processing" p.97 for Jinc/Bessel functions. http://mathworld.wolfram.com/JincFunction.html and page 11 of http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf The original "zoom" program by Paul Heckbert called this "Bessel". But really it is more accurately named "Jinc". */ if (x == 0.0) return(0.5*MagickPI); return(BesselOrderOne(MagickPI*x)/x); } static double Kaiser(const double x,const ResizeFilter *resize_filter) { /* Kaiser Windowing Function (bessel windowing) I0( beta * sqrt( 1-x^2) ) / IO(0) Beta (coeff[0]) is a free value from 5 to 8 (defaults to 6.5). However it is typically defined in terms of Alpha*PI The normalization factor (coeff[1]) is not actually needed, but without it the filters has a large value at x=0 making it difficult to compare the function with other windowing functions. */ return(resize_filter->coefficient[1]*I0(resize_filter->coefficient[0]* sqrt((double) (1.0-x*x)))); } static double Lagrange(const double x,const ResizeFilter *resize_filter) { double value; ssize_t i; ssize_t n, order; /* Lagrange piecewise polynomial fit of sinc: N is the 'order' of the lagrange function and depends on the overall support window size of the filter. That is: for a support of 2, it gives a lagrange-4 (piecewise cubic function). "n" identifies the piece of the piecewise polynomial. See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging, Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064. */ if (x > resize_filter->support) return(0.0); order=(ssize_t) (2.0*resize_filter->window_support); /* number of pieces */ n=(ssize_t) (resize_filter->window_support+x); value=1.0f; for (i=0; i < order; i++) if (i != n) value*=(n-i-x)/(n-i); return(value); } static double Quadratic(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 2rd order (quadratic) B-Spline approximation of Gaussian. */ if (x < 0.5) return(0.75-x*x); if (x < 1.5) return(0.5*(x-1.5)*(x-1.5)); return(0.0); } static double Sinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Scaled sinc(x) function using a trig call: sinc(x) == sin(pi x)/(pi x). */ if (x != 0.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } return((double) 1.0); } static double SincFast(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Approximations of the sinc function sin(pi x)/(pi x) over the interval [-4,4] constructed by Nicolas Robidoux and Chantal Racette with funding from the Natural Sciences and Engineering Research Council of Canada. Although the approximations are polynomials (for low order of approximation) and quotients of polynomials (for higher order of approximation) and consequently are similar in form to Taylor polynomials / Pade approximants, the approximations are computed with a completely different technique. Summary: These approximations are "the best" in terms of bang (accuracy) for the buck (flops). More specifically: Among the polynomial quotients that can be computed using a fixed number of flops (with a given "+ - * / budget"), the chosen polynomial quotient is the one closest to the approximated function with respect to maximum absolute relative error over the given interval. The Remez algorithm, as implemented in the boost library's minimax package, is the key to the construction: http://www.boost.org/doc/libs/1_36_0/libs/ math/doc/sf_and_dist/html/math_toolkit/backgrounders/remez.html If outside of the interval of approximation, use the standard trig formula. */ if (x > 4.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } { /* The approximations only depend on x^2 (sinc is an even function). */ const double xx = x*x; #if MAGICKCORE_QUANTUM_DEPTH <= 8 /* Maximum absolute relative error 6.3e-6 < 1/2^17. */ const double c0 = 0.173610016489197553621906385078711564924e-2L; const double c1 = -0.384186115075660162081071290162149315834e-3L; const double c2 = 0.393684603287860108352720146121813443561e-4L; const double c3 = -0.248947210682259168029030370205389323899e-5L; const double c4 = 0.107791837839662283066379987646635416692e-6L; const double c5 = -0.324874073895735800961260474028013982211e-8L; const double c6 = 0.628155216606695311524920882748052490116e-10L; const double c7 = -0.586110644039348333520104379959307242711e-12L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #elif MAGICKCORE_QUANTUM_DEPTH <= 16 /* Max. abs. rel. error 2.2e-8 < 1/2^25. */ const double c0 = 0.173611107357320220183368594093166520811e-2L; const double c1 = -0.384240921114946632192116762889211361285e-3L; const double c2 = 0.394201182359318128221229891724947048771e-4L; const double c3 = -0.250963301609117217660068889165550534856e-5L; const double c4 = 0.111902032818095784414237782071368805120e-6L; const double c5 = -0.372895101408779549368465614321137048875e-8L; const double c6 = 0.957694196677572570319816780188718518330e-10L; const double c7 = -0.187208577776590710853865174371617338991e-11L; const double c8 = 0.253524321426864752676094495396308636823e-13L; const double c9 = -0.177084805010701112639035485248501049364e-15L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*(c7+xx*(c8+xx*c9)))))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #else /* Max. abs. rel. error 1.2e-12 < 1/2^39. */ const double c0 = 0.173611111110910715186413700076827593074e-2L; const double c1 = -0.289105544717893415815859968653611245425e-3L; const double c2 = 0.206952161241815727624413291940849294025e-4L; const double c3 = -0.834446180169727178193268528095341741698e-6L; const double c4 = 0.207010104171026718629622453275917944941e-7L; const double c5 = -0.319724784938507108101517564300855542655e-9L; const double c6 = 0.288101675249103266147006509214934493930e-11L; const double c7 = -0.118218971804934245819960233886876537953e-13L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); const double d0 = 1.0L; const double d1 = 0.547981619622284827495856984100563583948e-1L; const double d2 = 0.134226268835357312626304688047086921806e-2L; const double d3 = 0.178994697503371051002463656833597608689e-4L; const double d4 = 0.114633394140438168641246022557689759090e-6L; const double q = d0+xx*(d1+xx*(d2+xx*(d3+xx*d4))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)/q*p); #endif } } static double Triangle(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 1st order (linear) B-Spline, bilinear interpolation, Tent 1D filter, or a Bartlett 2D Cone filter. Also used as a Bartlett Windowing function for Sinc(). */ if (x < 1.0) return(1.0-x); return(0.0); } static double Welch(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Welch parabolic windowing filter. */ if (x < 1.0) return(1.0-x*x); return(0.0); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireResizeFilter() allocates the ResizeFilter structure. Choose from % these filters: % % FIR (Finite impulse Response) Filters % Box Triangle Quadratic % Spline Hermite Catrom % Mitchell % % IIR (Infinite impulse Response) Filters % Gaussian Sinc Jinc (Bessel) % % Windowed Sinc/Jinc Filters % Blackman Bohman Lanczos % Hann Hamming Cosine % Kaiser Welch Parzen % Bartlett % % Special Purpose Filters % Cubic SincFast LanczosSharp Lanczos2 Lanczos2Sharp % Robidoux RobidouxSharp % % The users "-filter" selection is used to lookup the default 'expert' % settings for that filter from a internal table. However any provided % 'expert' settings (see below) may override this selection. % % FIR filters are used as is, and are limited to that filters support window % (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also % simply clipped by its support size (currently 1.5 or approximately 3*sigma % as recommended by many references) % % The special a 'cylindrical' filter flag will promote the default 4-lobed % Windowed Sinc filter to a 3-lobed Windowed Jinc equivalent, which is better % suited to this style of image resampling. This typically happens when using % such a filter for images distortions. % % SPECIFIC FILTERS: % % Directly requesting 'Sinc', 'Jinc' function as a filter will force the use % of function without any windowing, or promotion for cylindrical usage. This % is not recommended, except by image processing experts, especially as part % of expert option filter function selection. % % Two forms of the 'Sinc' function are available: Sinc and SincFast. Sinc is % computed using the traditional sin(pi*x)/(pi*x); it is selected if the user % specifically specifies the use of a Sinc filter. SincFast uses highly % accurate (and fast) polynomial (low Q) and rational (high Q) approximations, % and will be used by default in most cases. % % The Lanczos filter is a special 3-lobed Sinc-windowed Sinc filter (promoted % to Jinc-windowed Jinc for cylindrical (Elliptical Weighted Average) use). % The Sinc version is the most popular windowed filter. % % LanczosSharp is a slightly sharpened (blur=0.9812505644269356 < 1) form of % the Lanczos filter, specifically designed for EWA distortion (as a % Jinc-Jinc); it can also be used as a slightly sharper orthogonal Lanczos % (Sinc-Sinc) filter. The chosen blur value comes as close as possible to % satisfying the following condition without changing the character of the % corresponding EWA filter: % % 'No-Op' Vertical and Horizontal Line Preservation Condition: Images with % only vertical or horizontal features are preserved when performing 'no-op" % with EWA distortion. % % The Lanczos2 and Lanczos2Sharp filters are 2-lobe versions of the Lanczos % filters. The 'sharp' version uses a blur factor of 0.9549963639785485, % again chosen because the resulting EWA filter comes as close as possible to % satisfying the above condition. % % Robidoux is another filter tuned for EWA. It is the Keys cubic filter % defined by B=(228 - 108 sqrt(2))/199. Robidoux satisfies the "'No-Op' % Vertical and Horizontal Line Preservation Condition" exactly, and it % moderately blurs high frequency 'pixel-hash' patterns under no-op. It turns % out to be close to both Mitchell and Lanczos2Sharp. For example, its first % crossing is at (36 sqrt(2) + 123)/(72 sqrt(2) + 47), almost the same as the % first crossing of Mitchell and Lanczos2Sharp. % % RobidouxSharp is a slightly sharper version of Robidoux, some believe it % is too sharp. It is designed to minimize the maximum possible change in % a pixel value which is at one of the extremes (e.g., 0 or 255) under no-op % conditions. Amazingly Mitchell falls roughly between Robidoux and % RobidouxSharp, though this seems to have been pure coincidence. % % 'EXPERT' OPTIONS: % % These artifact "defines" are not recommended for production use without % expert knowledge of resampling, filtering, and the effects they have on the % resulting resampled (resized or distorted) image. % % They can be used to override any and all filter default, and it is % recommended you make good use of "filter:verbose" to make sure that the % overall effect of your selection (before and after) is as expected. % % "filter:verbose" controls whether to output the exact results of the % filter selections made, as well as plotting data for graphing the % resulting filter over the filters support range. % % "filter:filter" select the main function associated with this filter % name, as the weighting function of the filter. This can be used to % set a windowing function as a weighting function, for special % purposes, such as graphing. % % If a "filter:window" operation has not been provided, a 'Box' % windowing function will be set to denote that no windowing function is % being used. % % "filter:window" Select this windowing function for the filter. While any % filter could be used as a windowing function, using the 'first lobe' of % that filter over the whole support window, using a non-windowing % function is not advisible. If no weighting filter function is specified % a 'SincFast' filter is used. % % "filter:lobes" Number of lobes to use for the Sinc/Jinc filter. This a % simpler method of setting filter support size that will correctly % handle the Sinc/Jinc switch for an operators filtering requirements. % Only integers should be given. % % "filter:support" Set the support size for filtering to the size given. % This not recommended for Sinc/Jinc windowed filters (lobes should be % used instead). This will override any 'filter:lobes' option. % % "filter:win-support" Scale windowing function to this size instead. This % causes the windowing (or self-windowing Lagrange filter) to act is if % the support window it much much larger than what is actually supplied % to the calling operator. The filter however is still clipped to the % real support size given, by the support range supplied to the caller. % If unset this will equal the normal filter support size. % % "filter:blur" Scale the filter and support window by this amount. A value % of > 1 will generally result in a more blurred image with more ringing % effects, while a value <1 will sharpen the resulting image with more % aliasing effects. % % "filter:sigma" The sigma value to use for the Gaussian filter only. % Defaults to '1/2'. Using a different sigma effectively provides a % method of using the filter as a 'blur' convolution. Particularly when % using it for Distort. % % "filter:b" % "filter:c" Override the preset B,C values for a Cubic filter. % If only one of these are given it is assumes to be a 'Keys' type of % filter such that B+2C=1, where Keys 'alpha' value = C. % % Examples: % % Set a true un-windowed Sinc filter with 10 lobes (very slow): % -define filter:filter=Sinc % -define filter:lobes=8 % % Set an 8 lobe Lanczos (Sinc or Jinc) filter: % -filter Lanczos % -define filter:lobes=8 % % The format of the AcquireResizeFilter method is: % % ResizeFilter *AcquireResizeFilter(const Image *image, % const FilterType filter_type,const MagickBooleanType cylindrical, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filter: the filter type, defining a preset filter, window and support. % The artifact settings listed above will override those selections. % % o blur: blur the filter by this amount, use 1.0 if unknown. Image % artifact "filter:blur" will override this API call usage, including any % internal change (such as for cylindrical usage). % % o radial: use a 1D orthogonal filter (Sinc) or 2D cylindrical (radial) % filter (Jinc). % % o exception: return any errors or warnings in this structure. % */ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image, const FilterType filter,const MagickBooleanType cylindrical, ExceptionInfo *exception) { const char *artifact; FilterType filter_type, window_type; double B, C, value; ResizeFilter *resize_filter; /* Table Mapping given Filter, into Weighting and Windowing functions. A 'Box' windowing function means its a simble non-windowed filter. An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a "cylindrical" is requested, unless a 'Sinc' or 'SincFast' filter was specifically requested by the user. WARNING: The order of this table must match the order of the FilterType enumeration specified in "resample.h", or the filter names will not match the filter being setup. You can check filter setups with the "filter:verbose" expert setting. */ static struct { FilterType filter, window; } const mapping[SentinelFilter] = { { UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */ { PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */ { BoxFilter, BoxFilter }, /* Box averaging filter */ { TriangleFilter, BoxFilter }, /* Linear interpolation filter */ { HermiteFilter, BoxFilter }, /* Hermite interpolation filter */ { SincFastFilter, HannFilter }, /* Hann -- cosine-sinc */ { SincFastFilter, HammingFilter }, /* Hamming -- '' variation */ { SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */ { GaussianFilter, BoxFilter }, /* Gaussian blur filter */ { QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */ { CubicFilter, BoxFilter }, /* General Cubic Filter, Spline */ { CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */ { MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */ { JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */ { SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */ { SincFastFilter, BoxFilter }, /* Raw fast sinc ("Pade"-type) */ { SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */ { LanczosFilter, WelchFilter }, /* Welch -- parabolic (3 lobe) */ { SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */ { SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */ { SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */ { LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */ { LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */ { LanczosSharpFilter, LanczosSharpFilter }, /* | these require */ { Lanczos2Filter, Lanczos2Filter }, /* | special handling */ { Lanczos2SharpFilter, Lanczos2SharpFilter }, { RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */ { RobidouxSharpFilter, BoxFilter }, /* Sharper Cubic Keys for EWA */ { LanczosFilter, CosineFilter }, /* Cosine window (3 lobes) */ { SplineFilter, BoxFilter }, /* Spline Cubic Filter */ { LanczosRadiusFilter, LanczosFilter }, /* Lanczos with integer radius */ { CubicSplineFilter, BoxFilter }, /* CubicSpline (2/3/4 lobes) */ }; /* Table mapping the filter/window from the above table to an actual function. The default support size for that filter as a weighting function, the range to scale with to use that function as a sinc windowing function, (typ 1.0). Note that the filter_type -> function is 1 to 1 except for Sinc(), SincFast(), and CubicBC() functions, which may have multiple filter to function associations. See "filter:verbose" handling below for the function -> filter mapping. */ static struct { double (*function)(const double,const ResizeFilter*), support, /* Default lobes/support size of the weighting filter. */ scale, /* Support when function used as a windowing function Typically equal to the location of the first zero crossing. */ B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */ ResizeWeightingFunctionType weightingFunctionType; } const filters[SentinelFilter] = { /* .--- support window (if used as a Weighting Function) | .--- first crossing (if used as a Windowing Function) | | .--- B value for Cubic Function | | | .---- C value for Cubic Function | | | | */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Undefined (default to Box) */ { Box, 0.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Point (special handling) */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Box */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Triangle */ { CubicBC, 1.0, 1.0, 0.0, 0.0, CubicBCWeightingFunction }, /* Hermite (cubic B=C=0) */ { Hann, 1.0, 1.0, 0.0, 0.0, HannWeightingFunction }, /* Hann, cosine window */ { Hamming, 1.0, 1.0, 0.0, 0.0, HammingWeightingFunction }, /* Hamming, '' variation */ { Blackman, 1.0, 1.0, 0.0, 0.0, BlackmanWeightingFunction }, /* Blackman, 2*cosine window */ { Gaussian, 2.0, 1.5, 0.0, 0.0, GaussianWeightingFunction }, /* Gaussian */ { Quadratic, 1.5, 1.5, 0.0, 0.0, QuadraticWeightingFunction },/* Quadratic gaussian */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* General Cubic Filter */ { CubicBC, 2.0, 1.0, 0.0, 0.5, CubicBCWeightingFunction }, /* Catmull-Rom (B=0,C=1/2) */ { CubicBC, 2.0, 8.0/7.0, 1./3., 1./3., CubicBCWeightingFunction }, /* Mitchell (B=C=1/3) */ { Jinc, 3.0, 1.2196698912665045, 0.0, 0.0, JincWeightingFunction }, /* Raw 3-lobed Jinc */ { Sinc, 4.0, 1.0, 0.0, 0.0, SincWeightingFunction }, /* Raw 4-lobed Sinc */ { SincFast, 4.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Raw fast sinc ("Pade"-type) */ { Kaiser, 1.0, 1.0, 0.0, 0.0, KaiserWeightingFunction }, /* Kaiser (square root window) */ { Welch, 1.0, 1.0, 0.0, 0.0, WelchWeightingFunction }, /* Welch (parabolic window) */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Parzen (B-Spline window) */ { Bohman, 1.0, 1.0, 0.0, 0.0, BohmanWeightingFunction }, /* Bohman, 2*Cosine window */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Bartlett (triangle window) */ { Lagrange, 2.0, 1.0, 0.0, 0.0, LagrangeWeightingFunction }, /* Lagrange sinc approximation */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 3-lobed Sinc-Sinc */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Sharpened */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 2-lobed */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos2, sharpened */ /* Robidoux: Keys cubic close to Lanczos2D sharpened */ { CubicBC, 2.0, 1.1685777620836932, 0.37821575509399867, 0.31089212245300067, CubicBCWeightingFunction }, /* RobidouxSharp: Sharper version of Robidoux */ { CubicBC, 2.0, 1.105822933719019, 0.2620145123990142, 0.3689927438004929, CubicBCWeightingFunction }, { Cosine, 1.0, 1.0, 0.0, 0.0, CosineWeightingFunction }, /* Low level cosine window */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Cubic B-Spline (B=1,C=0) */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Interger Radius */ { CubicSpline,2.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Spline Lobes 2-lobed */ }; /* The known zero crossings of the Jinc() or more accurately the Jinc(x*PI) function being used as a filter. It is used by the "filter:lobes" expert setting and for 'lobes' for Jinc functions in the previous table. This way users do not have to deal with the highly irrational lobe sizes of the Jinc filter. Values taken from http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp using Jv-function with v=1, then dividing by PI. */ static double jinc_zeros[16] = { 1.2196698912665045, 2.2331305943815286, 3.2383154841662362, 4.2410628637960699, 5.2427643768701817, 6.2439216898644877, 7.2447598687199570, 8.2453949139520427, 9.2458926849494673, 10.246293348754916, 11.246622794877883, 12.246898461138105, 13.247132522181061, 14.247333735806849, 15.247508563037300, 16.247661874700962 }; /* Allocate resize filter. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(UndefinedFilter < filter && filter < SentinelFilter); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) exception; resize_filter=(ResizeFilter *) AcquireCriticalMemory(sizeof(*resize_filter)); (void) memset(resize_filter,0,sizeof(*resize_filter)); /* Defaults for the requested filter. */ filter_type=mapping[filter].filter; window_type=mapping[filter].window; resize_filter->blur=1.0; /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */ if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) && (filter != SincFastFilter)) filter_type=JincFilter; /* 1D Windowed Sinc => 2D Windowed Jinc filters */ /* Expert filter setting override */ artifact=GetImageArtifact(image,"filter:filter"); if (IsStringTrue(artifact) != MagickFalse) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { /* Raw filter request - no window function. */ filter_type=(FilterType) option; window_type=BoxFilter; } /* Filter override with a specific window function. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) window_type=(FilterType) option; } } else { /* Window specified, but no filter function? Assume Sinc/Jinc. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { filter_type= cylindrical != MagickFalse ? JincFilter : SincFastFilter; window_type=(FilterType) option; } } } /* Assign the real functions to use for the filters selected. */ resize_filter->filter=filters[filter_type].function; resize_filter->support=filters[filter_type].support; resize_filter->filterWeightingType=filters[filter_type].weightingFunctionType; resize_filter->window=filters[window_type].function; resize_filter->windowWeightingType=filters[window_type].weightingFunctionType; resize_filter->scale=filters[window_type].scale; resize_filter->signature=MagickCoreSignature; /* Filter Modifications for orthogonal/cylindrical usage */ if (cylindrical != MagickFalse) switch (filter_type) { case BoxFilter: /* Support for Cylindrical Box should be sqrt(2)/2 */ resize_filter->support=(double) MagickSQ1_2; break; case LanczosFilter: case LanczosSharpFilter: case Lanczos2Filter: case Lanczos2SharpFilter: case LanczosRadiusFilter: resize_filter->filter=filters[JincFilter].function; resize_filter->window=filters[JincFilter].function; resize_filter->scale=filters[JincFilter].scale; /* number of lobes (support window size) remain unchanged */ break; default: break; } /* Global Sharpening (regardless of orthoginal/cylindrical) */ switch (filter_type) { case LanczosSharpFilter: resize_filter->blur *= 0.9812505644269356; break; case Lanczos2SharpFilter: resize_filter->blur *= 0.9549963639785485; break; /* case LanczosRadius: blur adjust is done after lobes */ default: break; } /* Expert Option Modifications. */ /* User Gaussian Sigma Override - no support change */ if ((resize_filter->filter == Gaussian) || (resize_filter->window == Gaussian) ) { value=0.5; /* guassian sigma default, half pixel */ artifact=GetImageArtifact(image,"filter:sigma"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); /* Define coefficents for Gaussian */ resize_filter->coefficient[0]=value; /* note sigma too */ resize_filter->coefficient[1]=PerceptibleReciprocal(2.0*value*value); /* sigma scaling */ resize_filter->coefficient[2]=PerceptibleReciprocal(Magick2PI*value*value); /* normalization - not actually needed or used! */ if ( value > 0.5 ) resize_filter->support *= 2*value; /* increase support linearly */ } /* User Kaiser Alpha Override - no support change */ if ((resize_filter->filter == Kaiser) || (resize_filter->window == Kaiser) ) { value=6.5; /* default beta value for Kaiser bessel windowing function */ artifact=GetImageArtifact(image,"filter:alpha"); /* FUTURE: depreciate */ if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-beta"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-alpha"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL)*MagickPI; /* Define coefficents for Kaiser Windowing Function */ resize_filter->coefficient[0]=value; /* alpha */ resize_filter->coefficient[1]=PerceptibleReciprocal(I0(value)); /* normalization */ } /* Support Overrides */ artifact=GetImageArtifact(image,"filter:lobes"); if (artifact != (const char *) NULL) { ssize_t lobes; lobes=(ssize_t) StringToLong(artifact); if (lobes < 1) lobes=1; resize_filter->support=(double) lobes; } if (resize_filter->filter == Jinc) { /* Convert a Jinc function lobes value to a real support value. */ if (resize_filter->support > 16) resize_filter->support=jinc_zeros[15]; /* largest entry in table */ else resize_filter->support=jinc_zeros[((long) resize_filter->support)-1]; /* Blur this filter so support is a integer value (lobes dependant). */ if (filter_type == LanczosRadiusFilter) resize_filter->blur*=floor(resize_filter->support)/ resize_filter->support; } /* Expert blur override. */ artifact=GetImageArtifact(image,"filter:blur"); if (artifact != (const char *) NULL) resize_filter->blur*=StringToDouble(artifact,(char **) NULL); if (resize_filter->blur < MagickEpsilon) resize_filter->blur=(double) MagickEpsilon; /* Expert override of the support setting. */ artifact=GetImageArtifact(image,"filter:support"); if (artifact != (const char *) NULL) resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL)); /* Scale windowing function separately to the support 'clipping' window that calling operator is planning to actually use. (Expert override) */ resize_filter->window_support=resize_filter->support; /* default */ artifact=GetImageArtifact(image,"filter:win-support"); if (artifact != (const char *) NULL) resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL)); /* Adjust window function scaling to match windowing support for weighting function. This avoids a division on every filter call. */ resize_filter->scale*=PerceptibleReciprocal(resize_filter->window_support); /* Set Cubic Spline B,C values, calculate Cubic coefficients. */ B=0.0; C=0.0; if ((resize_filter->filter == CubicBC) || (resize_filter->window == CubicBC) ) { B=filters[filter_type].B; C=filters[filter_type].C; if (filters[window_type].function == CubicBC) { B=filters[window_type].B; C=filters[window_type].C; } artifact=GetImageArtifact(image,"filter:b"); if (artifact != (const char *) NULL) { B=StringToDouble(artifact,(char **) NULL); C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */ artifact=GetImageArtifact(image,"filter:c"); /* user C override */ if (artifact != (const char *) NULL) C=StringToDouble(artifact,(char **) NULL); } else { artifact=GetImageArtifact(image,"filter:c"); if (artifact != (const char *) NULL) { C=StringToDouble(artifact,(char **) NULL); B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */ } } { const double twoB = B+B; /* Convert B,C values into Cubic Coefficents. See CubicBC(). */ resize_filter->coefficient[0]=1.0-(1.0/3.0)*B; resize_filter->coefficient[1]=-3.0+twoB+C; resize_filter->coefficient[2]=2.0-1.5*B-C; resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C; resize_filter->coefficient[4]=-8.0*C-twoB; resize_filter->coefficient[5]=B+5.0*C; resize_filter->coefficient[6]=(-1.0/6.0)*B-C; } } /* Expert Option Request for verbose details of the resulting filter. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp master { #endif if (IsStringTrue(GetImageArtifact(image,"filter:verbose")) != MagickFalse) { double support, x; /* Set the weighting function properly when the weighting function may not exactly match the filter of the same name. EG: a Point filter is really uses a Box weighting function with a different support than is typically used. */ if (resize_filter->filter == Box) filter_type=BoxFilter; if (resize_filter->filter == Sinc) filter_type=SincFilter; if (resize_filter->filter == SincFast) filter_type=SincFastFilter; if (resize_filter->filter == Jinc) filter_type=JincFilter; if (resize_filter->filter == CubicBC) filter_type=CubicFilter; if (resize_filter->window == Box) window_type=BoxFilter; if (resize_filter->window == Sinc) window_type=SincFilter; if (resize_filter->window == SincFast) window_type=SincFastFilter; if (resize_filter->window == Jinc) window_type=JincFilter; if (resize_filter->window == CubicBC) window_type=CubicFilter; /* Report Filter Details. */ support=GetResizeFilterSupport(resize_filter); /* practical_support */ (void) FormatLocaleFile(stdout, "# Resampling Filter (for graphing)\n#\n"); (void) FormatLocaleFile(stdout,"# filter = %s\n", CommandOptionToMnemonic(MagickFilterOptions,filter_type)); (void) FormatLocaleFile(stdout,"# window = %s\n", CommandOptionToMnemonic(MagickFilterOptions,window_type)); (void) FormatLocaleFile(stdout,"# support = %.*g\n", GetMagickPrecision(),(double) resize_filter->support); (void) FormatLocaleFile(stdout,"# window-support = %.*g\n", GetMagickPrecision(),(double) resize_filter->window_support); (void) FormatLocaleFile(stdout,"# scale-blur = %.*g\n", GetMagickPrecision(),(double) resize_filter->blur); if ((filter_type == GaussianFilter) || (window_type == GaussianFilter)) (void) FormatLocaleFile(stdout,"# gaussian-sigma = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); if ( filter_type == KaiserFilter || window_type == KaiserFilter ) (void) FormatLocaleFile(stdout,"# kaiser-beta = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); (void) FormatLocaleFile(stdout,"# practical-support = %.*g\n", GetMagickPrecision(), (double) support); if ((filter_type == CubicFilter) || (window_type == CubicFilter)) (void) FormatLocaleFile(stdout,"# B,C = %.*g,%.*g\n", GetMagickPrecision(),(double) B,GetMagickPrecision(),(double) C); (void) FormatLocaleFile(stdout,"\n"); /* Output values of resulting filter graph -- for graphing filter result. */ for (x=0.0; x <= support; x+=0.01f) (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",x, GetMagickPrecision(),(double) GetResizeFilterWeight(resize_filter,x)); /* A final value so gnuplot can graph the 'stop' properly. */ (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",support, GetMagickPrecision(),0.0); } /* Output the above once only for each image - remove setting */ (void) DeleteImageArtifact((Image *) image,"filter:verbose"); #if defined(MAGICKCORE_OPENMP_SUPPORT) } #endif return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveResizeImage() adaptively resize image with pixel resampling. % % This is shortcut function for a fast interpolative resize using mesh % interpolation. It works well for small resizes of less than +/- 50% % of the original image size. For larger resizing on images a full % filtered and slower resize function should be used instead. % % The format of the AdaptiveResizeImage method is: % % Image *AdaptiveResizeImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveResizeImage(const Image *image, const size_t columns,const size_t rows,ExceptionInfo *exception) { Image *resize_image; resize_image=InterpolativeResizeImage(image,columns,rows,MeshInterpolatePixel, exception); return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + B e s s e l O r d e r O n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BesselOrderOne() computes the Bessel function of x of the first kind of % order 0. This is used to create the Jinc() filter function below. % % Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8] % % j1(x) = x*j1(x); % % For x in (8,inf) % % j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) % % where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow: % % cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) % = 1/sqrt(2) * (sin(x) - cos(x)) % sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) % = -1/sqrt(2) * (sin(x) + cos(x)) % % The format of the BesselOrderOne method is: % % double BesselOrderOne(double x) % % A description of each parameter follows: % % o x: double value. % */ #undef I0 static double I0(double x) { double sum, t, y; ssize_t i; /* Zeroth order Bessel function of the first kind. */ sum=1.0; y=x*x/4.0; t=y; for (i=2; t > MagickEpsilon; i++) { sum+=t; t*=y/((double) i*i); } return(sum); } #undef J1 static double J1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 }, Qone[] = { 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 }; p=Pone[8]; q=Qone[8]; for (i=7; i >= 0; i--) { p=p*x*x+Pone[i]; q=q*x*x+Qone[i]; } return(p/q); } #undef P1 static double P1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 }, Qone[] = { 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } #undef Q1 static double Q1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } static double BesselOrderOne(double x) { double p, q; if (x == 0.0) return(0.0); p=x; if (x < 0.0) x=(-x); if (x < 8.0) return(p*J1(x)); q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin(x)- cos(x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin(x)+cos(x)))); if (p < 0.0) q=(-q); return(q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyResizeFilter() destroy the resize filter. % % The format of the DestroyResizeFilter method is: % % ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) % % A description of each parameter follows: % % o resize_filter: the resize filter. % */ MagickPrivate ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); resize_filter->signature=(~MagickCoreSignature); resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter); return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r S u p p o r t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterSupport() return the current support window size for this % filter. Note that this may have been enlarged by filter:blur factor. % % The format of the GetResizeFilterSupport method is: % % double GetResizeFilterSupport(const ResizeFilter *resize_filter) % % A description of each parameter follows: % % o filter: Image filter to use. % */ MagickPrivate double *GetResizeFilterCoefficient( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return((double *) resize_filter->coefficient); } MagickPrivate double GetResizeFilterBlur(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->blur); } MagickPrivate double GetResizeFilterScale(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->scale); } MagickPrivate double GetResizeFilterWindowSupport( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->window_support); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->filterWeightingType); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWindowWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->windowWeightingType); } MagickPrivate double GetResizeFilterSupport(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->support*resize_filter->blur); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r W e i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterWeight evaluates the specified resize filter at the point x % which usally lies between zero and the filters current 'support' and % returns the weight of the filter function at that point. % % The format of the GetResizeFilterWeight method is: % % double GetResizeFilterWeight(const ResizeFilter *resize_filter, % const double x) % % A description of each parameter follows: % % o filter: the filter type. % % o x: the point. % */ MagickPrivate double GetResizeFilterWeight(const ResizeFilter *resize_filter, const double x) { double scale, weight, x_blur; /* Windowing function - scale the weighting filter by this amount. */ assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); x_blur=fabs((double) x)*PerceptibleReciprocal(resize_filter->blur); /* X offset with blur scaling */ if ((resize_filter->window_support < MagickEpsilon) || (resize_filter->window == Box)) scale=1.0; /* Point or Box Filter -- avoid division by zero */ else { scale=resize_filter->scale; scale=resize_filter->window(x_blur*scale,resize_filter); } weight=scale*resize_filter->filter(x_blur,resize_filter); return(weight); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolativeResizeImage() resizes an image using the specified % interpolation method. % % The format of the InterpolativeResizeImage method is: % % Image *InterpolativeResizeImage(const Image *image,const size_t columns, % const size_t rows,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *InterpolativeResizeImage(const Image *image, const size_t columns,const size_t rows,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define InterpolativeResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; Image *resize_image; MagickBooleanType status; MagickOffsetType progress; PointInfo scale; ssize_t y; /* Interpolatively resize 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); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(resize_image,DirectClass,exception) == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); scale.x=(double) image->columns/resize_image->columns; scale.y=(double) image->rows/resize_image->rows; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { PointInfo offset; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if (q == (Quantum *) NULL) continue; offset.y=((double) y+0.5)*scale.y-0.5; for (x=0; x < (ssize_t) resize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait resize_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; offset.x=((double) x+0.5)*scale.x-0.5; status=InterpolatePixelChannels(image,image_view,resize_image,method, offset.x,offset.y,q,exception); if (status == MagickFalse) break; } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_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,InterpolativeResizeImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) resize_image=DestroyImage(resize_image); return(resize_image); } #if defined(MAGICKCORE_LQR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i q u i d R e s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiquidRescaleImage() rescales image with seam carving. % % The format of the LiquidRescaleImage method is: % % Image *LiquidRescaleImage(const Image *image,const size_t columns, % const size_t rows,const double delta_x,const double rigidity, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the rescaled image. % % o rows: the number of rows in the rescaled image. % % o delta_x: maximum seam transversal step (0 means straight seams). % % o rigidity: introduce a bias for non-straight seams (typically 0). % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LiquidRescaleImage(const Image *image,const size_t columns, const size_t rows,const double delta_x,const double rigidity, ExceptionInfo *exception) { #define LiquidRescaleImageTag "Rescale/Image" CacheView *image_view, *rescale_view; gfloat *packet, *pixels; Image *rescale_image; int x_offset, y_offset; LqrCarver *carver; LqrRetVal lqr_status; MagickBooleanType status; MemoryInfo *pixel_info; gfloat *q; ssize_t y; /* Liquid rescale 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); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); if ((columns <= 2) || (rows <= 2)) return(ResizeImage(image,columns,rows,image->filter,exception)); pixel_info=AcquireVirtualMemory(image->columns,image->rows*MaxPixelChannels* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) return((Image *) NULL); pixels=(gfloat *) GetVirtualMemoryBlob(pixel_info); status=MagickTrue; q=pixels; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; 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; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) *q++=QuantumScale*p[i]; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); carver=lqr_carver_new_ext(pixels,(int) image->columns,(int) image->rows, (int) GetPixelChannels(image),LQR_COLDEPTH_32F); if (carver == (LqrCarver *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } lqr_carver_set_preserve_input_image(carver); lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity); lqr_status=lqr_carver_resize(carver,(int) columns,(int) rows); (void) lqr_status; rescale_image=CloneImage(image,lqr_carver_get_width(carver), lqr_carver_get_height(carver),MagickTrue,exception); if (rescale_image == (Image *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); return((Image *) NULL); } if (SetImageStorageClass(rescale_image,DirectClass,exception) == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); rescale_image=DestroyImage(rescale_image); return((Image *) NULL); } rescale_view=AcquireAuthenticCacheView(rescale_image,exception); (void) lqr_carver_scan_reset(carver); while (lqr_carver_scan_ext(carver,&x_offset,&y_offset,(void **) &packet) != 0) { Quantum *magick_restrict p; ssize_t i; p=QueueCacheViewAuthenticPixels(rescale_view,x_offset,y_offset,1,1, exception); if (p == (Quantum *) NULL) break; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait rescale_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); rescale_traits=GetPixelChannelTraits(rescale_image,channel); if ((traits == UndefinedPixelTrait) || (rescale_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rescale_image,channel,ClampToQuantum(QuantumRange* packet[i]),p); } if (SyncCacheViewAuthenticPixels(rescale_view,exception) == MagickFalse) break; } rescale_view=DestroyCacheView(rescale_view); pixel_info=RelinquishVirtualMemory(pixel_info); lqr_carver_destroy(carver); return(rescale_image); } #else MagickExport Image *LiquidRescaleImage(const Image *image, const size_t magick_unused(columns),const size_t magick_unused(rows), const double magick_unused(delta_x),const double magick_unused(rigidity), ExceptionInfo *exception) { 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); (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","'%s' (LQR)",image->filename); return((Image *) NULL); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagnifyImage() doubles the size of the image with a pixel art scaling % algorithm. % % The format of the MagnifyImage method is: % % Image *MagnifyImage(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 void CopyPixels(const Quantum *source,const ssize_t source_offset, Quantum *destination,const ssize_t destination_offset,const size_t channels) { ssize_t i; for (i=0; i < (ssize_t) channels; i++) destination[channels*destination_offset+i]=source[source_offset*channels+i]; } static inline void MixPixels(const Quantum *source,const ssize_t *source_offset, const size_t source_size,Quantum *destination, const ssize_t destination_offset,const size_t channels) { ssize_t sum; ssize_t i; for (i=0; i < (ssize_t) channels; i++) { ssize_t j; sum=0; for (j=0; j < (ssize_t) source_size; j++) sum+=source[source_offset[j]*channels+i]; destination[channels*destination_offset+i]=(Quantum) (sum/source_size); } } static inline void Mix2Pixels(const Quantum *source, const ssize_t source_offset1,const ssize_t source_offset2, Quantum *destination,const ssize_t destination_offset,const size_t channels) { const ssize_t offsets[2] = { source_offset1, source_offset2 }; MixPixels(source,offsets,2,destination,destination_offset,channels); } static inline int PixelsEqual(const Quantum *source1,ssize_t offset1, const Quantum *source2,ssize_t offset2,const size_t channels) { ssize_t i; offset1*=channels; offset2*=channels; for (i=0; i < (ssize_t) channels; i++) if (source1[offset1+i] != source2[offset2+i]) return(0); return(1); } static inline void Eagle2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t i; (void) source; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if (PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,0,result,0,channels); if (PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels)) CopyPixels(pixels,2,result,1,channels); if (PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels)) CopyPixels(pixels,6,result,2,channels); if (PixelsEqual(pixels,5,pixels,8,channels) && PixelsEqual(pixels,8,pixels,7,channels)) CopyPixels(pixels,8,result,3,channels); } static void Hq2XHelper(const unsigned int rule,const Quantum *source, Quantum *destination,const ssize_t destination_offset,const size_t channels, const ssize_t e,const ssize_t a,const ssize_t b,const ssize_t d, const ssize_t f,const ssize_t h) { #define caseA(N,A,B,C,D) \ case N: \ { \ const ssize_t \ offsets[4] = { A, B, C, D }; \ \ MixPixels(source,offsets,4,destination,destination_offset,channels);\ break; \ } #define caseB(N,A,B,C,D,E,F,G,H) \ case N: \ { \ const ssize_t \ offsets[8] = { A, B, C, D, E, F, G, H }; \ \ MixPixels(source,offsets,8,destination,destination_offset,channels);\ break; \ } switch (rule) { case 0: { CopyPixels(source,e,destination,destination_offset,channels); break; } caseA(1,e,e,e,a) caseA(2,e,e,e,d) caseA(3,e,e,e,b) caseA(4,e,e,d,b) caseA(5,e,e,a,b) caseA(6,e,e,a,d) caseB(7,e,e,e,e,e,b,b,d) caseB(8,e,e,e,e,e,d,d,b) caseB(9,e,e,e,e,e,e,d,b) caseB(10,e,e,d,d,d,b,b,b) case 11: { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); break; } case 12: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 13: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 14: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 15: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 16: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, e, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 17: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 18: { if (PixelsEqual(source,b,source,f,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, b, b, d }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, d }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } default: { if (PixelsEqual(source,d,source,h,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, d, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } } #undef caseA #undef caseB } static inline unsigned int Hq2XPatternToNumber(const int *pattern) { ssize_t i; unsigned int result, order; result=0; order=1; for (i=7; i >= 0; i--) { result+=order*pattern[i]; order*=2; } return(result); } static inline void Hq2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { static const unsigned int Hq2XTable[] = { 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 12, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 12, 12, 5, 19, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 1, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 18, 5, 3, 16, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 13, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 1, 12, 5, 3, 1, 14 }; const int pattern1[] = { !PixelsEqual(pixels,4,pixels,8,channels), !PixelsEqual(pixels,4,pixels,7,channels), !PixelsEqual(pixels,4,pixels,6,channels), !PixelsEqual(pixels,4,pixels,5,channels), !PixelsEqual(pixels,4,pixels,3,channels), !PixelsEqual(pixels,4,pixels,2,channels), !PixelsEqual(pixels,4,pixels,1,channels), !PixelsEqual(pixels,4,pixels,0,channels) }; #define Rotated(p) p[2], p[4], p[7], p[1], p[6], p[0], p[3], p[5] const int pattern2[] = { Rotated(pattern1) }; const int pattern3[] = { Rotated(pattern2) }; const int pattern4[] = { Rotated(pattern3) }; #undef Rotated (void) source; Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern1)],pixels,result,0, channels,4,0,1,3,5,7); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern2)],pixels,result,1, channels,4,2,5,1,7,3); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern3)],pixels,result,3, channels,4,8,7,5,3,1); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern4)],pixels,result,2, channels,4,6,3,7,1,5); } static void Fish2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { #define Corner(A,B,C,D) \ { \ if (intensities[B] > intensities[A]) \ { \ const ssize_t \ offsets[3] = { B, C, D }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ else \ { \ const ssize_t \ offsets[3] = { A, B, C }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ } #define Line(A,B,C,D) \ { \ if (intensities[C] > intensities[A]) \ Mix2Pixels(pixels,C,D,result,3,channels); \ else \ Mix2Pixels(pixels,A,B,result,3,channels); \ } const ssize_t pixels_offsets[4] = { 0, 1, 3, 4 }; MagickFloatType intensities[9]; int ae, bd, ab, ad, be, de; ssize_t i; for (i=0; i < 9; i++) intensities[i]=GetPixelIntensity(source,pixels + i*channels); CopyPixels(pixels,0,result,0,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[1] ? 0 : 1),result, 1,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[3] ? 0 : 3),result, 2,channels); ae=PixelsEqual(pixels,0,pixels,4,channels); bd=PixelsEqual(pixels,1,pixels,3,channels); ab=PixelsEqual(pixels,0,pixels,1,channels); de=PixelsEqual(pixels,3,pixels,4,channels); ad=PixelsEqual(pixels,0,pixels,3,channels); be=PixelsEqual(pixels,1,pixels,4,channels); if (ae && bd && ab) { CopyPixels(pixels,0,result,3,channels); return; } if (ad && de && !ab) { Corner(1,0,4,3) return; } if (be && de && !ab) { Corner(0,1,3,4) return; } if (ad && ab && !be) { Corner(4,3,1,0) return; } if (ab && be && !ad) { Corner(3,0,4,1) return; } if (ae && (!bd || intensities[1] > intensities[0])) { Mix2Pixels(pixels,0,4,result,3,channels); return; } if (bd && (!ae || intensities[0] > intensities[1])) { Mix2Pixels(pixels,1,3,result,3,channels); return; } if (ab) { Line(0,1,3,4) return; } if (de) { Line(3,4,0,1) return; } if (ad) { Line(0,3,1,4) return; } if (be) { Line(1,4,0,3) return; } MixPixels(pixels,pixels_offsets,4,result,3,channels); #undef Corner #undef Line } static void Xbr2X(const Image *magick_unused(source),const Quantum *pixels, Quantum *result,const size_t channels) { #define WeightVar(M,N) const int w_##M##_##N = \ PixelsEqual(pixels,M,pixels,N,channels) ? 0 : 1; WeightVar(12,11) WeightVar(12,7) WeightVar(12,13) WeightVar(12,17) WeightVar(12,16) WeightVar(12,8) WeightVar(6,10) WeightVar(6,2) WeightVar(11,7) WeightVar(11,17) WeightVar(11,5) WeightVar(7,13) WeightVar(7,1) WeightVar(12,6) WeightVar(12,18) WeightVar(8,14) WeightVar(8,2) WeightVar(13,17) WeightVar(13,9) WeightVar(7,3) WeightVar(16,10) WeightVar(16,22) WeightVar(17,21) WeightVar(11,15) WeightVar(18,14) WeightVar(18,22) WeightVar(17,23) WeightVar(17,19) #undef WeightVar magick_unreferenced(source); if ( w_12_16 + w_12_8 + w_6_10 + w_6_2 + (4 * w_11_7) < w_11_17 + w_11_5 + w_7_13 + w_7_1 + (4 * w_12_6) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_7 ? 11 : 7),12,result,0, channels); else CopyPixels(pixels,12,result,0,channels); if ( w_12_18 + w_12_6 + w_8_14 + w_8_2 + (4 * w_7_13) < w_13_17 + w_13_9 + w_11_7 + w_7_3 + (4 * w_12_8) ) Mix2Pixels(pixels,(ssize_t) (w_12_7 <= w_12_13 ? 7 : 13),12,result,1, channels); else CopyPixels(pixels,12,result,1,channels); if ( w_12_6 + w_12_18 + w_16_10 + w_16_22 + (4 * w_11_17) < w_11_7 + w_11_15 + w_13_17 + w_17_21 + (4 * w_12_16) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_17 ? 11 : 17),12,result,2, channels); else CopyPixels(pixels,12,result,2,channels); if ( w_12_8 + w_12_16 + w_18_14 + w_18_22 + (4 * w_13_17) < w_11_17 + w_17_23 + w_17_19 + w_7_13 + (4 * w_12_18) ) Mix2Pixels(pixels,(ssize_t) (w_12_13 <= w_12_17 ? 13 : 17),12,result,3, channels); else CopyPixels(pixels,12,result,3,channels); } static void Scale2X(const Image *magick_unused(source),const Quantum *pixels, Quantum *result,const size_t channels) { magick_unreferenced(source); if (PixelsEqual(pixels,1,pixels,7,channels) || PixelsEqual(pixels,3,pixels,5,channels)) { ssize_t i; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); return; } if (PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if (PixelsEqual(pixels,1,pixels,5,channels)) CopyPixels(pixels,5,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,3,channels); else CopyPixels(pixels,4,result,3,channels); } static void Epbx2X(const Image *magick_unused(source),const Quantum *pixels, Quantum *result,const size_t channels) { #define HelperCond(a,b,c,d,e,f,g) ( \ PixelsEqual(pixels,a,pixels,b,channels) && ( \ PixelsEqual(pixels,c,pixels,d,channels) || \ PixelsEqual(pixels,c,pixels,e,channels) || \ PixelsEqual(pixels,a,pixels,f,channels) || \ PixelsEqual(pixels,b,pixels,g,channels) \ ) \ ) ssize_t i; magick_unreferenced(source); for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if ( !PixelsEqual(pixels,3,pixels,5,channels) && !PixelsEqual(pixels,1,pixels,7,channels) && ( PixelsEqual(pixels,4,pixels,3,channels) || PixelsEqual(pixels,4,pixels,7,channels) || PixelsEqual(pixels,4,pixels,5,channels) || PixelsEqual(pixels,4,pixels,1,channels) || ( ( !PixelsEqual(pixels,0,pixels,8,channels) || PixelsEqual(pixels,4,pixels,6,channels) || PixelsEqual(pixels,3,pixels,2,channels) ) && ( !PixelsEqual(pixels,6,pixels,2,channels) || PixelsEqual(pixels,4,pixels,0,channels) || PixelsEqual(pixels,4,pixels,8,channels) ) ) ) ) { if (HelperCond(1,3,4,0,8,2,6)) Mix2Pixels(pixels,1,3,result,0,channels); if (HelperCond(5,1,4,2,6,8,0)) Mix2Pixels(pixels,5,1,result,1,channels); if (HelperCond(3,7,4,6,2,0,8)) Mix2Pixels(pixels,3,7,result,2,channels); if (HelperCond(7,5,4,8,0,6,2)) Mix2Pixels(pixels,7,5,result,3,channels); } #undef HelperCond } static inline void Eagle3X(const Image *magick_unused(source), const Quantum *pixels,Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; magick_unreferenced(source); corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); if (corner_tl && corner_tr) Mix2Pixels(pixels,0,2,result,1,channels); else CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); if (corner_tl && corner_bl) Mix2Pixels(pixels,0,6,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if (corner_tr && corner_br) Mix2Pixels(pixels,2,8,result,5,channels); else CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); if (corner_bl && corner_br) Mix2Pixels(pixels,6,8,result,7,channels); else CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Eagle3XB(const Image *magick_unused(source), const Quantum *pixels,Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; magick_unreferenced(source); corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Scale3X(const Image *magick_unused(source), const Quantum *pixels,Quantum *result,const size_t channels) { magick_unreferenced(source); if (!PixelsEqual(pixels,1,pixels,7,channels) && !PixelsEqual(pixels,3,pixels,5,channels)) { if (PixelsEqual(pixels,3,pixels,1,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) || ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,1,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,5,pixels,1,channels)) CopyPixels(pixels,5,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) || ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,3,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if ( ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) ) CopyPixels(pixels,5,result,5,channels); else CopyPixels(pixels,4,result,5,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,6,channels); else CopyPixels(pixels,4,result,6,channels); if ( ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) ) CopyPixels(pixels,7,result,7,channels); else CopyPixels(pixels,4,result,7,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,8,channels); else CopyPixels(pixels,4,result,8,channels); } else { ssize_t i; for (i=0; i < 9; i++) CopyPixels(pixels,4,result,i,channels); } } MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception) { #define MagnifyImageTag "Magnify/Image" CacheView *image_view, *magnify_view; const char *option; Image *source_image, *magnify_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; RectangleInfo rectangle; ssize_t y; unsigned char magnification, width; void (*scaling_method)(const Image *,const Quantum *,Quantum *,size_t); /* Initialize magnified 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); option=GetImageOption(image->image_info,"magnify:method"); if (option == (char *) NULL) option="scale2x"; scaling_method=Scale2X; magnification=1; width=1; switch (*option) { case 'e': { if (LocaleCompare(option,"eagle2x") == 0) { scaling_method=Eagle2X; magnification=2; width=3; break; } if (LocaleCompare(option,"eagle3x") == 0) { scaling_method=Eagle3X; magnification=3; width=3; break; } if (LocaleCompare(option,"eagle3xb") == 0) { scaling_method=Eagle3XB; magnification=3; width=3; break; } if (LocaleCompare(option,"epbx2x") == 0) { scaling_method=Epbx2X; magnification=2; width=3; break; } break; } case 'f': { if (LocaleCompare(option,"fish2x") == 0) { scaling_method=Fish2X; magnification=2; width=3; break; } break; } case 'h': { if (LocaleCompare(option,"hq2x") == 0) { scaling_method=Hq2X; magnification=2; width=3; break; } break; } case 's': { if (LocaleCompare(option,"scale2x") == 0) { scaling_method=Scale2X; magnification=2; width=3; break; } if (LocaleCompare(option,"scale3x") == 0) { scaling_method=Scale3X; magnification=3; width=3; break; } break; } case 'x': { if (LocaleCompare(option,"xbr2x") == 0) { scaling_method=Xbr2X; magnification=2; width=5; } break; } default: break; } /* Make a working copy of the source image and convert it to RGB colorspace. */ source_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (source_image == (Image *) NULL) return((Image *) NULL); offset.x=0; offset.y=0; rectangle.x=0; rectangle.y=0; rectangle.width=image->columns; rectangle.height=image->rows; (void) CopyImagePixels(source_image,image,&rectangle,&offset,exception); (void) SetImageColorspace(source_image,RGBColorspace,exception); magnify_image=CloneImage(source_image,magnification*source_image->columns, magnification*source_image->rows,MagickTrue,exception); if (magnify_image == (Image *) NULL) { source_image=DestroyImage(source_image); return((Image *) NULL); } /* Magnify the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(source_image,exception); magnify_view=AcquireAuthenticCacheView(magnify_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,magnify_image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { Quantum r[128]; /* to hold result pixels */ Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(magnify_view,0,magnification*y, magnify_image->columns,magnification,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } /* Magnify this row of pixels. */ for (x=0; x < (ssize_t) source_image->columns; x++) { const Quantum *magick_restrict p; size_t channels; ssize_t i; ssize_t j; p=GetCacheViewVirtualPixels(image_view,x-width/2,y-width/2,width,width, exception); channels=GetPixelChannels(source_image); scaling_method(source_image,p,r,channels); /* Copy the result pixels into the final image. */ for (j=0; j < (ssize_t) magnification; j++) for (i=0; i < (ssize_t) (channels*magnification); i++) q[j*channels*magnify_image->columns+i]=r[j*magnification*channels+i]; q+=magnification*GetPixelChannels(magnify_image); } if (SyncCacheViewAuthenticPixels(magnify_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,MagnifyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } magnify_view=DestroyCacheView(magnify_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); if (status == MagickFalse) magnify_image=DestroyImage(magnify_image); return(magnify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinifyImage() is a convenience method that scales an image proportionally to % half its size. % % The format of the MinifyImage method is: % % Image *MinifyImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MinifyImage(const Image *image,ExceptionInfo *exception) { Image *minify_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); minify_image=ResizeImage(image,image->columns/2,image->rows/2,SplineFilter, exception); return(minify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResampleImage() resize image in terms of its pixel size, so that when % displayed at the given resolution it will be the same size in terms of % real world units as the original image at the original resolution. % % The format of the ResampleImage method is: % % Image *ResampleImage(Image *image,const double x_resolution, % const double y_resolution,const FilterType filter, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be resized to fit the given resolution. % % o x_resolution: the new image x resolution. % % o y_resolution: the new image y resolution. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ResampleImage(const Image *image,const double x_resolution, const double y_resolution,const FilterType filter,ExceptionInfo *exception) { #define ResampleImageTag "Resample/Image" Image *resample_image; size_t height, width; /* Initialize sampled 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); width=(size_t) (x_resolution*image->columns/(image->resolution.x == 0.0 ? DefaultResolution : image->resolution.x)+0.5); height=(size_t) (y_resolution*image->rows/(image->resolution.y == 0.0 ? DefaultResolution : image->resolution.y)+0.5); resample_image=ResizeImage(image,width,height,filter,exception); if (resample_image != (Image *) NULL) { resample_image->resolution.x=x_resolution; resample_image->resolution.y=y_resolution; } return(resample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeImage() scales an image to the desired dimensions, using the given % filter (see AcquireFilterInfo()). % % If an undefined filter is given the filter defaults to Mitchell for a % colormapped image, a image with a matte channel, or if the image is % enlarged. Otherwise the filter defaults to a Lanczos. % % ResizeImage() was inspired by Paul Heckbert's "zoom" program. % % The format of the ResizeImage method is: % % Image *ResizeImage(Image *image,const size_t columns,const size_t rows, % const FilterType filter,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ typedef struct _ContributionInfo { double weight; ssize_t pixel; } ContributionInfo; static ContributionInfo **DestroyContributionThreadSet( ContributionInfo **contribution) { ssize_t i; assert(contribution != (ContributionInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (contribution[i] != (ContributionInfo *) NULL) contribution[i]=(ContributionInfo *) RelinquishAlignedMemory( contribution[i]); contribution=(ContributionInfo **) RelinquishMagickMemory(contribution); return(contribution); } static ContributionInfo **AcquireContributionThreadSet(const size_t count) { ssize_t i; ContributionInfo **contribution; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads, sizeof(*contribution)); if (contribution == (ContributionInfo **) NULL) return((ContributionInfo **) NULL); (void) memset(contribution,0,number_threads*sizeof(*contribution)); for (i=0; i < (ssize_t) number_threads; i++) { contribution[i]=(ContributionInfo *) MagickAssumeAligned( AcquireAlignedMemory(count,sizeof(**contribution))); if (contribution[i] == (ContributionInfo *) NULL) return(DestroyContributionThreadSet(contribution)); } return(contribution); } static MagickBooleanType HorizontalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double x_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { #define ResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; MagickBooleanType status; double scale, support; ssize_t x; /* Apply filter to resize horizontally from image to resize image. */ scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->columns,1) #endif for (x=0; x < (ssize_t) resize_image->columns; x++) { const int id = GetOpenMPThreadId(); double bisect, density; const Quantum *magick_restrict p; ContributionInfo *magick_restrict contribution; Quantum *magick_restrict q; ssize_t y; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (x+0.5)/x_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->columns); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception); q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (y=0; y < (ssize_t) resize_image->rows; y++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j-start].pixel-contribution[0].pixel); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } /* Alpha blending. */ gamma=0.0; for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight*QuantumScale* GetPixelAlpha(image,p+k*GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_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,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } static MagickBooleanType VerticalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double y_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; double scale, support; MagickBooleanType status; ssize_t y; /* Apply filter to resize vertically from image to resize image. */ scale=MagickMax(1.0/y_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { const int id = GetOpenMPThreadId(); double bisect, density; const Quantum *magick_restrict p; ContributionInfo *magick_restrict contribution; Quantum *magick_restrict q; ssize_t x; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (y+0.5)/y_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->rows); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,0,contribution[0].pixel, image->columns,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1), exception); q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) resize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=(ssize_t) ((contribution[j-start].pixel-contribution[0].pixel)* image->columns+x); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } gamma=0.0; for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight*QuantumScale*GetPixelAlpha(image,p+k* GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_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,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } MagickExport Image *ResizeImage(const Image *image,const size_t columns, const size_t rows,const FilterType filter,ExceptionInfo *exception) { double x_factor, y_factor; FilterType filter_type; Image *filter_image, *resize_image; MagickOffsetType offset; MagickSizeType span; MagickStatusType status; ResizeFilter *resize_filter; /* Acquire resize 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); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows) && (filter == UndefinedFilter)) return(CloneImage(image,0,0,MagickTrue,exception)); /* Acquire resize filter. */ x_factor=(double) columns/(double) image->columns; y_factor=(double) rows/(double) image->rows; filter_type=LanczosFilter; if (filter != UndefinedFilter) filter_type=filter; else if ((x_factor == 1.0) && (y_factor == 1.0)) filter_type=PointFilter; else if ((image->storage_class == PseudoClass) || (image->alpha_trait != UndefinedPixelTrait) || ((x_factor*y_factor) > 1.0)) filter_type=MitchellFilter; resize_filter=AcquireResizeFilter(image,filter_type,MagickFalse,exception); #if defined(MAGICKCORE_OPENCL_SUPPORT) resize_image=AccelerateResizeImage(image,columns,rows,resize_filter, exception); if (resize_image != (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } #endif resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } if (x_factor > y_factor) filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception); else filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception); if (filter_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(DestroyImage(resize_image)); } /* Resize image. */ offset=0; if (x_factor > y_factor) { span=(MagickSizeType) (filter_image->columns+rows); status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span, &offset,exception); status&=VerticalFilter(resize_filter,filter_image,resize_image,y_factor, span,&offset,exception); } else { span=(MagickSizeType) (filter_image->rows+columns); status=VerticalFilter(resize_filter,image,filter_image,y_factor,span, &offset,exception); status&=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor, span,&offset,exception); } /* Free resources. */ filter_image=DestroyImage(filter_image); resize_filter=DestroyResizeFilter(resize_filter); if (status == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } resize_image->type=image->type; return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SampleImage() scales an image to the desired dimensions with pixel % sampling. Unlike other scaling methods, this method does not introduce % any additional color into the scaled image. % % The format of the SampleImage method is: % % Image *SampleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the sampled image. % % o rows: the number of rows in the sampled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SampleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleImageTag "Sample/Image" CacheView *image_view, *sample_view; Image *sample_image; MagickBooleanType status; MagickOffsetType progress; ssize_t x1; ssize_t *x_offset, y; PointInfo sample_offset; /* Initialize sampled 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 ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); sample_image=CloneImage(image,columns,rows,MagickTrue,exception); if (sample_image == (Image *) NULL) return((Image *) NULL); /* Set the sampling offset, default is in the mid-point of sample regions. */ sample_offset.x=sample_offset.y=0.5-MagickEpsilon; { const char *value; value=GetImageArtifact(image,"sample:offset"); if (value != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; (void) ParseGeometry(value,&geometry_info); flags=ParseGeometry(value,&geometry_info); sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon; if ((flags & SigmaValue) != 0) sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; } } /* Allocate scan line buffer and column offset buffers. */ x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, sizeof(*x_offset)); if (x_offset == (ssize_t *) NULL) { sample_image=DestroyImage(sample_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (x1=0; x1 < (ssize_t) sample_image->columns; x1++) x_offset[x1]=(ssize_t) ((((double) x1+sample_offset.x)*image->columns)/ sample_image->columns); /* Sample each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sample_view=AcquireAuthenticCacheView(sample_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,sample_image,sample_image->rows,1) #endif for (y=0; y < (ssize_t) sample_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; ssize_t y_offset; if (status == MagickFalse) continue; y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ sample_image->rows); p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, exception); q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } /* Sample each column. */ for (x=0; x < (ssize_t) sample_image->columns; x++) { ssize_t i; if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(sample_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) { PixelChannel channel; PixelTrait image_traits, traits; channel=GetPixelChannelChannel(sample_image,i); traits=GetPixelChannelTraits(sample_image,channel); image_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (image_traits == UndefinedPixelTrait)) continue; SetPixelChannel(sample_image,channel,p[x_offset[x]*GetPixelChannels( image)+i],q); } q+=GetPixelChannels(sample_image); } if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); sample_view=DestroyCacheView(sample_view); x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); sample_image->type=image->type; if (status == MagickFalse) sample_image=DestroyImage(sample_image); return(sample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleImage() changes the size of an image to the given dimensions. % % The format of the ScaleImage method is: % % Image *ScaleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ScaleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define ScaleImageTag "Scale/Image" CacheView *image_view, *scale_view; double alpha, pixel[CompositePixelChannel], *scale_scanline, *scanline, *x_vector, *y_vector; Image *scale_image; MagickBooleanType next_column, next_row, proceed, status; PixelTrait scale_traits; PointInfo scale, span; ssize_t i; ssize_t n, number_rows, y; /* Initialize scaled 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 ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); scale_image=CloneImage(image,columns,rows,MagickTrue,exception); if (scale_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(scale_image,DirectClass,exception) == MagickFalse) { scale_image=DestroyImage(scale_image); return((Image *) NULL); } /* Allocate memory. */ x_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*x_vector)); scanline=x_vector; if (image->rows != scale_image->rows) scanline=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*scanline)); scale_scanline=(double *) AcquireQuantumMemory((size_t) scale_image->columns, MaxPixelChannels*sizeof(*scale_scanline)); y_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*y_vector)); if ((scanline == (double *) NULL) || (scale_scanline == (double *) NULL) || (x_vector == (double *) NULL) || (y_vector == (double *) NULL)) { if ((image->rows != scale_image->rows) && (scanline != (double *) NULL)) scanline=(double *) RelinquishMagickMemory(scanline); if (scale_scanline != (double *) NULL) scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (x_vector != (double *) NULL) x_vector=(double *) RelinquishMagickMemory(x_vector); if (y_vector != (double *) NULL) y_vector=(double *) RelinquishMagickMemory(y_vector); scale_image=DestroyImage(scale_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Scale image. */ number_rows=0; next_row=MagickTrue; span.y=1.0; scale.y=(double) scale_image->rows/(double) image->rows; (void) memset(y_vector,0,(size_t) MaxPixelChannels*image->columns* sizeof(*y_vector)); n=0; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); scale_view=AcquireAuthenticCacheView(scale_image,exception); for (y=0; y < (ssize_t) scale_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) break; q=QueueCacheViewAuthenticPixels(scale_view,0,y,scale_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } alpha=1.0; if (scale_image->rows == image->rows) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } } else { /* Scale Y direction. */ while (scale.y < span.y) { if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; } for (x=0; x < (ssize_t) image->columns; x++) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) y_vector[x*GetPixelChannels(image)+i]+=scale.y* x_vector[x*GetPixelChannels(image)+i]; span.y-=scale.y; scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; next_row=MagickFalse; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { pixel[i]=y_vector[x*GetPixelChannels(image)+i]+span.y* x_vector[x*GetPixelChannels(image)+i]; scanline[x*GetPixelChannels(image)+i]=pixel[i]; y_vector[x*GetPixelChannels(image)+i]=0.0; } } scale.y-=span.y; if (scale.y <= 0) { scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } span.y=1.0; } if (scale_image->columns == image->columns) { /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha*scanline[ x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } else { ssize_t t; /* Scale X direction. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; span.x=1.0; t=0; for (x=0; x < (ssize_t) image->columns; x++) { scale.x=(double) scale_image->columns/(double) image->columns; while (scale.x >= span.x) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; pixel[i]+=span.x*scanline[x*GetPixelChannels(image)+i]; scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; } scale.x-=span.x; span.x=1.0; next_column=MagickTrue; } if (scale.x > 0) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=scale.x*scanline[x*GetPixelChannels(image)+i]; span.x-=scale.x; } } if (span.x > 0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=span.x*scanline[(x-1)*GetPixelChannels(image)+i]; } if ((next_column == MagickFalse) && (t < (ssize_t) scale_image->columns)) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scale_scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scale_scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha* scale_scanline[x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } if (SyncCacheViewAuthenticPixels(scale_view,exception) == MagickFalse) { status=MagickFalse; break; } proceed=SetImageProgress(image,ScaleImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) { status=MagickFalse; break; } } scale_view=DestroyCacheView(scale_view); image_view=DestroyCacheView(image_view); /* Free allocated memory. */ y_vector=(double *) RelinquishMagickMemory(y_vector); scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (scale_image->rows != image->rows) scanline=(double *) RelinquishMagickMemory(scanline); x_vector=(double *) RelinquishMagickMemory(x_vector); scale_image->type=image->type; if (status == MagickFalse) scale_image=DestroyImage(scale_image); return(scale_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h u m b n a i l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThumbnailImage() changes the size of an image to the given dimensions and % removes any associated profiles. The goal is to produce small low cost % thumbnail images suited for display on the Web. % % The format of the ThumbnailImage method is: % % Image *ThumbnailImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ThumbnailImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleFactor 5 char filename[MagickPathExtent], value[MagickPathExtent]; const char *name; Image *clone_image, *thumbnail_image; ssize_t x_factor, y_factor; struct stat 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); x_factor=(ssize_t) image->columns/columns; y_factor=(ssize_t) image->rows/rows; clone_image=CloneImage(image,0,0,MagickTrue,exception); if ((x_factor > 4) && (y_factor > 4)) { thumbnail_image=SampleImage(clone_image,4*columns,4*rows,exception); if (thumbnail_image != (Image *) NULL) { clone_image=DestroyImage(clone_image); clone_image=thumbnail_image; } } if ((x_factor > 2) && (y_factor > 2)) { thumbnail_image=ResizeImage(clone_image,2*columns,2*rows,BoxFilter, exception); if (thumbnail_image != (Image *) NULL) { clone_image=DestroyImage(clone_image); clone_image=thumbnail_image; } } thumbnail_image=ResizeImage(clone_image,columns,rows,image->filter == UndefinedFilter ? LanczosSharpFilter : image->filter,exception); if (thumbnail_image == (Image *) NULL) return(thumbnail_image); (void) ParseAbsoluteGeometry("0x0+0+0",&thumbnail_image->page); if (thumbnail_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(thumbnail_image,OpaqueAlphaChannel,exception); thumbnail_image->depth=8; thumbnail_image->interlace=NoInterlace; /* Strip all profiles except color profiles. */ ResetImageProfileIterator(thumbnail_image); for (name=GetNextImageProfile(thumbnail_image); name != (const char *) NULL; ) { if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) { (void) DeleteImageProfile(thumbnail_image,name); ResetImageProfileIterator(thumbnail_image); } name=GetNextImageProfile(thumbnail_image); } (void) DeleteImageProperty(thumbnail_image,"comment"); (void) CopyMagickString(value,image->magick_filename,MagickPathExtent); if (strstr(image->magick_filename,"//") == (char *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"file://%s", image->magick_filename); (void) SetImageProperty(thumbnail_image,"Thumb::URI",value,exception); GetPathComponent(image->magick_filename,TailPath,filename); (void) CopyMagickString(value,filename,MagickPathExtent); if ( GetPathAttributes(image->filename,&attributes) != MagickFalse ) (void) FormatImageProperty(thumbnail_image,"Thumb::MTime","%.20g",(double) attributes.st_mtime); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) attributes.st_mtime); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",MagickPathExtent, value); (void) SetImageProperty(thumbnail_image,"Thumb::Size",value,exception); (void) FormatLocaleString(value,MagickPathExtent,"image/%s",image->magick); LocaleLower(value); (void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value,exception); (void) SetImageProperty(thumbnail_image,"software",MagickAuthoritativeURL, exception); (void) FormatImageProperty(thumbnail_image,"Thumb::Image::Width","%.20g", (double) image->magick_columns); (void) FormatImageProperty(thumbnail_image,"Thumb::Image::Height","%.20g", (double) image->magick_rows); (void) FormatImageProperty(thumbnail_image,"Thumb::Document::Pages","%.20g", (double) GetImageListLength(image)); return(thumbnail_image); }
exp3_omp_v0.c
#include <stdio.h> #include <omp.h> int main() { int ii; #pragma omp parallel { for(ii=0;ii<10;ii++) { printf("Iteration: %d\n",ii); } } printf("\n"); return 0; }
JointWMF.h
/***************************************************************/ /* * Distribution code Version 1.1 -- 09/21/2014 by Qi Zhang Copyright 2014, The Chinese University of Hong Kong. * * The Code is created based on the method described in the following paper * [1] "100+ Times Faster Weighted Median Filter", Qi Zhang, Li Xu, Jiaya Jia, IEEE Conference on * Computer Vision and Pattern Recognition (CVPR), 2014 * * Due to the adaption for supporting mask and different types of input, this code is * slightly slower than the one claimed in the original paper. Please use * our executable on our website for performance comparison. * * The code and the algorithm are for non-comercial use only. * /***************************************************************/ #ifndef JOINT_WMF_H #define JOINT_WMF_H /***************************************************************/ /* * Standard IO library is required. * STL String library is required. * /***************************************************************/ #include <cstdio> #include <string> /***************************************************************/ /* * OpenCV 2.4 is required. * The following code is already built on OpenCV 2.4.2. * /***************************************************************/ #include "opencv2/core/core.hpp" #include <time.h> #include <omp.h> //Use the namespace of CV and STD using namespace std; using namespace cv; class JointWMF{ public: /***************************************************************/ /* Function: filter * * Description: filter implementation of joint-histogram weighted median framework * including clustering of feature image, adaptive quantization of input image. * * Input arguments: * I: input image (any # of channels). Accept only CV_32F and CV_8U type. * feature: the feature image ("F" in the paper). Accept only CV_8UC1 and CV_8UC3 type (the # of channels should be 1 or 3). * r: radius of filtering kernel, should be a positive integer. * sigma: filter range standard deviation for the feature image. * nI: # of quantization level of input image. (only when the input image is CV_32F type) * nF: # of clusters of feature value. (only when the feature image is 3-channel) * iter: # of filtering times/iterations. (without changing the feature map) * weightType: the type of weight definition, including: * exp: exp(-|I1-I2|^2/(2*sigma^2)) * iv1: (|I1-I2|+sigma)^-1 * iv2: (|I1-I2|^2+sigma^2)^-1 * cos: dot(I1,I2)/(|I1|*|I2|) * jac: (min(r1,r2)+min(g1,g2)+min(b1,b2))/(max(r1,r2)+max(g1,g2)+max(b1,b2)) * off: unweighted * mask: a 0-1 mask that has the same size with I. This mask is used to ignore the effect of some pixels. If the pixel value on mask is 0, * the pixel will be ignored when maintaining the joint-histogram. This is useful for applications like optical flow occlusion handling. * * Note: * 1. When feature image clustering (when F is 3-channel) OR adaptive quantization (when I is floating point image) is * performed, the result is an approximation. To increase the accuracy, using a larger "nI" or "nF" will help. * */ /***************************************************************/ static Mat filter(Mat &I, Mat &feature, int r, float sigma=25.5, int nI=256, int nF=256, int iter=1, string weightType="exp", Mat mask=Mat()){ Mat F = feature.clone(); //check validation assert(I.depth() == CV_32F || I.depth() == CV_8U); assert(F.depth() == CV_8U && (F.channels()==1 || F.channels()==3)); //declaration Mat result; //Preprocess I //OUTPUT OF THIS STEP: Is, iMap //If I is floating point image, "adaptive quantization" is done in from32FTo32S. //The mapping of floating value to integer value is stored in iMap (for each channel). //"Is" stores each channel of "I". The channels are converted to CV_32S type after this step. vector<float *> iMap(I.channels()); vector<Mat> Is; { split(I,Is); for(int i=0;i<(int)Is.size();i++){ if(I.depth()==CV_32F){ iMap[i] = new float[nI]; from32FTo32S(Is[i],Is[i],nI,iMap[i]); } else if(I.depth()==CV_8U){ Is[i].convertTo(Is[i],CV_32S); } } } //Preprocess F //OUTPUT OF THIS STEP: F(new), wMap //If "F" is 3-channel image, "clustering feature image" is done in featureIndexing. //If "F" is 1-channel image, featureIndexing only does a type-casting on "F". //The output "F" is CV_32S type, containing indexes of feature values. //"wMap" is a 2D array that defines the distance between each pair of feature indexes. // wMap[i][j] is the weight between feature index "i" and "j". float **wMap; { featureIndexing(F, wMap, nF, sigma, weightType); } //Filtering - Joint-Histogram Framework { for(int i=0;i<(int)Is.size();i++){ for(int k=0;k<iter;k++){ {//Do filtering Is[i] = filterCore(Is[i], F, wMap, r, nF,nI,mask); } } } } float2D_release(wMap); //Postprocess F //Convert input image back to the original type. { for(int i=0;i<(int)Is.size();i++){ if(I.depth()==CV_32F){ from32STo32F(Is[i],Is[i],iMap[i]); delete []iMap[i]; } else if(I.depth()==CV_8U){ Is[i].convertTo(Is[i],CV_8U); } } } //merge the channels merge(Is,result); //end of the function return result; } /***************************************************************/ /* Function: filterCore * * Description: filter core implementation only containing joint-histogram weighted median framework * * input arguments: * I: input image. Only accept CV_32S type. * F: feature image. Only accept CV_32S type. * wMap: a 2D array that defines the distance between each pair of feature values. wMap[i][j] is the weight between feature value "i" and "j". * r: radius of filtering kernel, should be a positive integer. * nI: # of possible values in I, i.e., all values of I should in range [0, nI) * nF: # of possible values in F, i.e., all values of F should in range [0, nF) * mask: a 0-1 mask that has the same size with I, for ignoring the effect of some pixels, as introduced in function "filter" */ /***************************************************************/ static Mat filterCore(Mat &I, Mat &F, float **wMap, int r=20, int nF=256, int nI=256, Mat mask=Mat()){ // Check validation assert(I.depth() == CV_32S && I.channels()==1);//input image: 32SC1 assert(F.depth() == CV_32S && F.channels()==1);//feature image: 32SC1 // Configuration and declaration int rows = I.rows, cols = I.cols; int alls = rows * cols; int winSize = (2*r+1)*(2*r+1); Mat outImg = I.clone(); // Handle Mask if(mask.empty()){ mask = Mat(I.size(),CV_8U); mask = Scalar(1); } // Allocate memory for joint-histogram and BCB int **H = int2D(nI,nF); int *BCB = new int[nF]; // Allocate links for necklace table int **Hf = int2D(nI,nF);//forward link int **Hb = int2D(nI,nF);//backward link int *BCBf = new int[nF];//forward link int *BCBb = new int[nF];//backward link // Column Scanning for(int x=0;x<cols;x++){ // Reset histogram and BCB for each column memset(BCB, 0, sizeof(int)*nF); memset(H[0], 0, sizeof(int)*nF*nI); for(int i=0;i<nI;i++)Hf[i][0]=Hb[i][0]=0; BCBf[0]=BCBb[0]=0; // Reset cut-point int medianVal = -1; // Precompute "x" range and checks boundary int downX = max(0,x-r); int upX = min(cols-1,x+r); // Initialize joint-histogram and BCB for the first window { int upY = min(rows-1,r); for(int i=0;i<=upY;i++){ int *IPtr = I.ptr<int>(i); int *FPtr = F.ptr<int>(i); uchar *maskPtr = mask.ptr<uchar>(i); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; int fval = IPtr[j]; int *curHist = H[fval]; int gval = FPtr[j]; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=0,p2=curHf[0]; curHf[p1]=gval; curHf[gval]=p2; curHb[p2]=gval; curHb[gval]=p1; } curHist[gval]++; // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,-1); } } } for(int y=0;y<rows;y++){ // Find weighted median with help of BCB and joint-histogram { float balanceWeight = 0; int curIndex = F.ptr<int>(y,x)[0]; float *fPtr = wMap[curIndex]; int &curMedianVal = medianVal; // Compute current balance int i=0; do{ balanceWeight += BCB[i]*fPtr[i]; i=BCBf[i]; }while(i); // Move cut-point to the left if(balanceWeight >= 0){ for(;balanceWeight >= 0 && curMedianVal;curMedianVal--){ float curWeight = 0; int *nextHist = H[curMedianVal]; int *nextHf = Hf[curMedianVal]; // Compute weight change by shift cut-point int i=0; do{ curWeight += (nextHist[i]<<1)*fPtr[i]; // Update BCB and maintain the necklace table of BCB updateBCB(BCB[i],BCBf,BCBb,i,-(nextHist[i]<<1)); i=nextHf[i]; }while(i); balanceWeight -= curWeight; } } // Move cut-point to the right else if(balanceWeight < 0){ for(;balanceWeight < 0 && curMedianVal != nI-1; curMedianVal++){ float curWeight = 0; int *nextHist = H[curMedianVal+1]; int *nextHf = Hf[curMedianVal+1]; // Compute weight change by shift cut-point int i=0; do{ curWeight += (nextHist[i]<<1)*fPtr[i]; // Update BCB and maintain the necklace table of BCB updateBCB(BCB[i],BCBf,BCBb,i,nextHist[i]<<1); i=nextHf[i]; }while(i); balanceWeight += curWeight; } } // Weighted median is found and written to the output image if(balanceWeight<0)outImg.ptr<int>(y,x)[0] = curMedianVal+1; else outImg.ptr<int>(y,x)[0] = curMedianVal; } // Update joint-histogram and BCB when local window is shifted. { int fval,gval,*curHist; // Add entering pixels into joint-histogram and BCB { int rownum = y + r + 1; if(rownum < rows){ int *inputImgPtr = I.ptr<int>(rownum); int *guideImgPtr = F.ptr<int>(rownum); uchar *maskPtr = mask.ptr<uchar>(rownum); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; fval = inputImgPtr[j]; curHist = H[fval]; gval = guideImgPtr[j]; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=0,p2=curHf[0]; curHf[gval]=p2; curHb[gval]=p1; curHf[p1]=curHb[p2]=gval; } curHist[gval]++; // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,((fval <= medianVal)<<1)-1); } } } // Delete leaving pixels into joint-histogram and BCB { int rownum = y - r; if(rownum >= 0){ int *inputImgPtr = I.ptr<int>(rownum); int *guideImgPtr = F.ptr<int>(rownum); uchar *maskPtr = mask.ptr<uchar>(rownum); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; fval = inputImgPtr[j]; curHist = H[fval]; gval = guideImgPtr[j]; curHist[gval]--; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=curHb[gval],p2=curHf[gval]; curHf[p1]=p2; curHb[p2]=p1; } // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,-((fval <= medianVal)<<1)+1); } } } } } } // Deallocate the memory { delete []BCB; delete []BCBf; delete []BCBb; int2D_release(H); int2D_release(Hf); int2D_release(Hb); } // end of the function return outImg; } private: /***************************************************************/ /* Function: updateBCB * Description: maintain the necklace table of BCB /***************************************************************/ static inline void updateBCB(int &num,int *f,int *b,int i,int v){ static int p1,p2; if(i){ if(!num){ // cell is becoming non-empty p2=f[0]; f[0]=i; f[i]=p2; b[p2]=i; b[i]=0; } else if(!(num+v)){// cell is becoming empty p1=b[i],p2=f[i]; f[p1]=p2; b[p2]=p1; } } // update the cell count num += v; } /***************************************************************/ /* Function: float2D * Description: allocate a 2D float array with dimension "dim1 x dim2" /***************************************************************/ static float** float2D(int dim1, int dim2){ float **ret = new float*[dim1]; ret[0] = new float[dim1*dim2]; for(int i=1;i<dim1;i++)ret[i] = ret[i-1]+dim2; return ret; } /***************************************************************/ /* Function: float2D_release * Description: deallocate the 2D array created by float2D() /***************************************************************/ static void float2D_release(float **p){ delete []p[0]; delete []p; } /***************************************************************/ /* Function: int2D * Description: allocate a 2D integer array with dimension "dim1 x dim2" /***************************************************************/ static int** int2D(int dim1, int dim2){ int **ret = new int*[dim1]; ret[0] = new int[dim1*dim2]; for(int i=1;i<dim1;i++)ret[i] = ret[i-1]+dim2; return ret; } /***************************************************************/ /* Function: int2D_release * Description: deallocate the 2D array created by int2D() /***************************************************************/ static void int2D_release(int **p){ delete []p[0]; delete []p; } /***************************************************************/ /* Function: featureIndexing * Description: convert uchar feature image "F" to CV_32SC1 type. * If F is 3-channel, perform k-means clustering * If F is 1-channel, only perform type-casting /***************************************************************/ static void featureIndexing(Mat &F, float **&wMap, int &nF, float sigmaI, string weightType){ // Configuration and Declaration Mat FNew; int cols = F.cols, rows = F.rows; int alls = cols * rows; int KmeansAttempts=1; vector<string> ops; ops.push_back("exp"); ops.push_back("iv1"); ops.push_back("iv2"); ops.push_back("cos"); ops.push_back("jac"); ops.push_back("off"); // Get weight type number int numOfOps = (int)ops.size(); int op = 0; for(;op<numOfOps;op++)if(ops[op] == weightType)break; if(op>=numOfOps)op=0; /* For 1 channel feature image (uchar)*/ if(F.channels() == 1){ nF = 256; // Type-casting F.convertTo(FNew, CV_32S); // Computer weight map (weight between each pair of feature index) { wMap = float2D(nF,nF); float nSigmaI = sigmaI; float divider = (1.0f/(2*nSigmaI*nSigmaI)); for(int i=0;i<nF;i++){ for(int j=i;j<nF;j++){ float diff = fabs((float)(i-j)); if(op==0)wMap[i][j] = wMap[j][i] = exp(-(diff*diff)*divider); // EXP 2 else if(op==2)wMap[i][j] = wMap[j][i] = 1.0f / (diff*diff+nSigmaI*nSigmaI); // IV2 else if(op==1)wMap[i][j] = wMap[j][i] = 1.0f/(diff+nSigmaI);// IV1 else if(op==3)wMap[i][j] = wMap[j][i] = 1.0f; // COS else if(op==4)wMap[i][j] = wMap[j][i] = (float)(min(i,j)*1.0/max(i,j)); // Jacard else if(op==5)wMap[i][j] = wMap[j][i] = 1.0f; // Unweighted } } } } /* For 3 channel feature image (uchar)*/ else if(F.channels() == 3){ const int shift = 2; // 256(8-bit)->64(6-bit) const int LOW_NUM = 256>>shift; static int hash[LOW_NUM][LOW_NUM][LOW_NUM]={0}; memset(hash,0,sizeof(hash)); // throw pixels into a 2D histogram int candCnt = 0; { int lowR,lowG,lowB; uchar *FPtr = F.ptr<uchar>(); for(int i=0,i3=0;i<alls;i++,i3+=3){ lowB = FPtr[i3]>>shift; lowG = FPtr[i3+1]>>shift; lowR = FPtr[i3+2]>>shift; if(hash[lowB][lowG][lowR]==0){ candCnt++; hash[lowB][lowG][lowR]=1; } } } nF = min(nF, candCnt); Mat samples(candCnt,3,CV_32F); //prepare for K-means { int top=0; for(int i=0;i<LOW_NUM;i++)for(int j=0;j<LOW_NUM;j++)for(int k=0;k<LOW_NUM;k++){ if(hash[i][j][k]){ samples.ptr<float>(top)[0] = (float)i; samples.ptr<float>(top)[1] = (float)j; samples.ptr<float>(top)[2] = (float)k; top++; } } } //do K-means Mat labels; Mat centers; { kmeans(samples, nF, labels, TermCriteria(TermCriteria::MAX_ITER|TermCriteria::EPS, 0, 10000), KmeansAttempts, KMEANS_PP_CENTERS, centers ); } //make connection (i,j,k) <-> index { int top = 0; for(int i=0;i<LOW_NUM;i++)for(int j=0;j<LOW_NUM;j++)for(int k=0;k<LOW_NUM;k++){ if(hash[i][j][k]){ hash[i][j][k] = labels.ptr<int>(top)[0]; top++; } } } // generate index map { FNew = Mat(F.size(),CV_32SC1); int lowR,lowG,lowB; uchar *FPtr = F.ptr<uchar>(); for(int i=0,i3=0;i<alls;i++,i3+=3){ lowB = FPtr[i3]>>shift; lowG = FPtr[i3+1]>>shift; lowR = FPtr[i3+2]>>shift; FNew.ptr<int>()[i] = hash[lowB][lowG][lowR]; } } // Computer weight map (weight between each pair of feature index) { wMap = float2D(nF,nF); float nSigmaI = sigmaI/256.0f*LOW_NUM; float divider = (1.0f/(2*nSigmaI*nSigmaI)); float *length = new float[nF]; for(int i=0;i<nF;i++){ float a0 = centers.ptr<float>(i)[0]; float a1 = centers.ptr<float>(i)[1]; float a2 = centers.ptr<float>(i)[2]; length[i] = sqrt(a0*a0+a1*a1+a2*a2); } for(int i=0;i<nF;i++){ for(int j=i;j<nF;j++){ float a0 = centers.ptr<float>(i)[0], b0 = centers.ptr<float>(j)[0]; float a1 = centers.ptr<float>(i)[1], b1 = centers.ptr<float>(j)[1]; float a2 = centers.ptr<float>(i)[2], b2 = centers.ptr<float>(j)[2]; float diff0 = a0-b0; float diff1 = a1-b1; float diff2 = a2-b2; if(op==0)wMap[i][j] = wMap[j][i] = exp(-(diff0*diff0+diff1*diff1+diff2*diff2)*divider); // EXP 2 else if(op==2)wMap[i][j] = wMap[j][i] = 1.0f / (diff0*diff0+diff1*diff1+diff2*diff2+nSigmaI*nSigmaI); // IV2 else if(op==1)wMap[i][j] = wMap[j][i] = 1.0f/(fabs(diff0)+fabs(diff1)+fabs(diff2)+nSigmaI);// IV1 else if(op==3)wMap[i][j] = wMap[j][i] = (a0*b0+a1*b1+a2*b2)/(length[i]*length[j]); // COS else if(op==4)wMap[i][j] = wMap[j][i] = (min(a0,b0)+min(a1,b1)+min(a2,b2))/(max(a0,b0)+max(a1,b1)+max(a2,b2)); // Jacard else if(op==5)wMap[i][j] = wMap[j][i] = 1.0f; // Unweighted } } delete []length; } } //end of the function F = FNew; } /***************************************************************/ /* Function: from32FTo32S * Description: adaptive quantization for changing a floating-point 1D image to integer image. * The adaptive quantization strategy is based on binary search, which searches an * upper bound of quantization error. * The function also return a mapping between quantized value (32F) and quantized index (32S). * The mapping is used to convert integer image back to floating-point image after filtering. /***************************************************************/ static void from32FTo32S(Mat &img, Mat &outImg, int nI, float *mapping){ int rows = img.rows, cols = img.cols; int alls = rows * cols; float *imgPtr = img.ptr<float>(); typedef pair<float,int> pairFI; pairFI *data = (pairFI *)malloc(alls*sizeof(pairFI)); // Sort all pixels of the image by ascending order of pixel value { #pragma omp parallel for for(int i=0;i<alls;i++){ data[i].second = i; data[i].first = imgPtr[i]; } sort(data,data+alls); } // Find lower bound and upper bound of the pixel values double maxVal,minVal; minMaxLoc(img,&minVal,&maxVal); float maxRange = (float)(maxVal - minVal); float th = 1e-5f; float l = 0, r = maxRange*2.0f/nI; // Perform binary search on error bound while(r-l > th){ float m = (r+l)*0.5f; bool suc = true; float base = (float)minVal; int cnt=0; for(int i=0;i<alls;i++){ if(data[i].first>base+m){ cnt++; base = data[i].first; if(cnt==nI){ suc = false; break; } } } if(suc)r=m; else l=m; } Mat retImg(img.size(),CV_32SC1); int *retImgPtr = retImg.ptr<int>(); // In the sorted list, divide pixel values into clusters according to the minimum error bound // Quantize each value to the median of its cluster // Also record the mapping of quantized value and quantized index. float base = (float)minVal; int baseI = 0; int cnt = 0; for(int i=0;i<=alls;i++){ if(i==alls || data[i].first>base+r){ mapping[cnt] = data[(baseI+i-1)>>1].first; //median if(i==alls)break; cnt++; base = data[i].first; baseI = i; } retImgPtr[data[i].second] = cnt; } free(data); //end of the function outImg = retImg; } /***************************************************************/ /* Function: from32STo32F * Description: convert the quantization index image back to the floating-point image accroding to the mapping /***************************************************************/ static void from32STo32F(Mat &img, Mat &outImg, float *mapping){ Mat retImg(img.size(),CV_32F); int rows = img.rows, cols = img.cols, alls = rows*cols; float *retImgPtr = retImg.ptr<float>(); int *imgPtr = img.ptr<int>(); // convert 32S index to 32F real value #pragma omp parallel for for(int i=0;i<alls;i++){ retImgPtr[i] = mapping[imgPtr[i]]; } // end of the function outImg = retImg; } }; #endif
mp_omp.c
#include <stdio.h> #include <omp.h> #include "mpi.h" int main(int argc, char *argv[]) { int numprocs, rank, namelen; char processor_name[MPI_MAX_PROCESSOR_NAME]; int iam = 0, np = 1; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(processor_name, &namelen); #pragma omp parallel default(shared) private(iam, np) { np = omp_get_num_threads(); iam = omp_get_thread_num(); printf("Hello from thread %d out of %d threads spawned by process %d out of %d processes on %s\n", iam, np, rank, numprocs, processor_name); } MPI_Finalize(); }
app.c
/** * Christina Giannoula * cgiannoula: christina.giann@gmail.com */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <dpu.h> #include <dpu_log.h> #include <unistd.h> #include <getopt.h> #include <assert.h> #include <math.h> #include <omp.h> #include "../support/common.h" #include "../support/matrix.h" #include "../support/params.h" #include "../support/partition.h" #include "../support/timer.h" #include "../support/utils.h" // Define the DPU Binary path as DPU_BINARY here. #ifndef DPU_BINARY #define DPU_BINARY "./bin/spmv_dpu" #endif #define DPU_CAPACITY (64 << 20) // A DPU's capacity is 64 MB /* * Main Structures: * 1. Matrices * 2. Input vector * 3. Output vector * 4. Help structures for data partitioning */ static struct RBDBCSRMatrix* A; static struct RBDCSRMatrix* B; static struct COOMatrix* C; static val_dt* x; static val_dt* y; static val_dt* z; static struct partition_info_t *part_info; /** * @brief Specific information for each DPU */ struct dpu_info_t { uint32_t block_rows_per_dpu; uint32_t prev_block_rows_dpu; uint32_t cols_per_dpu; uint32_t block_start; uint32_t blocks; uint32_t blocks_pad; uint32_t prev_blocks_dpu; uint32_t ptr_offset; uint32_t merge; }; struct dpu_info_t *dpu_info; /** * @brief find the dpus_per_row_partition * @param factor n to create partitions * @param column_partitions to create vert_partitions * @param horz_partitions to return the 2D partitioning */ void find_partitions(uint32_t n, uint32_t *horz_partitions, uint32_t vert_partitions) { uint32_t dpus_per_vert_partition = n / vert_partitions; *horz_partitions = dpus_per_vert_partition; } /** * @brief initialize input vector * @param pointer to input vector and vector size */ void init_vector(val_dt* vec, uint32_t size) { for(unsigned int i = 0; i < size; ++i) { vec[i] = (val_dt) (i%4+1); } } /** * @brief compute output in the host CPU */ static void spmv_host(val_dt* y, struct RBDBCSRMatrix *A, val_dt* x) { uint64_t total_blocks = 0; for (uint32_t c = 0; c < A->vert_partitions; c++) { uint32_t ptr_offset = c * (A->num_block_rows + 1); uint32_t col_offset = c * A->tile_width; for(uint64_t n=0; n < A->num_block_rows; n++) { for(uint64_t i=A->browptr[ptr_offset + n]; i<A->browptr[ptr_offset + n+1]; i++){ uint64_t j = A->bcolind[total_blocks + i]; for(uint64_t blr=0; blr < A->row_block_size; blr++){ val_dt acc = 0; for(uint64_t blc=0; blc < A->col_block_size; blc++) { acc += A->bval[(total_blocks + i) * A->col_block_size * A->row_block_size + blr * A->col_block_size + blc] * x[col_offset + j * A->col_block_size + blc]; } y[n * A->row_block_size + blr] += acc; } } } total_blocks += A->blocks_per_vert_partition[c]; } } /** * @brief main of the host application */ int main(int argc, char **argv) { struct Params p = input_params(argc, argv); struct dpu_set_t dpu_set, dpu; uint32_t nr_of_dpus; uint32_t nr_of_ranks; // Allocate DPUs and load binary DPU_ASSERT(dpu_alloc(NR_DPUS, NULL, &dpu_set)); DPU_ASSERT(dpu_load(dpu_set, DPU_BINARY, NULL)); DPU_ASSERT(dpu_get_nr_dpus(dpu_set, &nr_of_dpus)); DPU_ASSERT(dpu_get_nr_ranks(dpu_set, &nr_of_ranks)); printf("[INFO] Allocated %d DPU(s)\n", nr_of_dpus); printf("[INFO] Allocated %d Rank(s)\n", nr_of_ranks); printf("[INFO] Allocated %d TASKLET(s) per DPU\n", NR_TASKLETS); unsigned int i; // Initialize input data C = readCOOMatrix(p.fileName); sortCOOMatrix(C); uint32_t horz_partitions = 0; uint32_t vert_partitions = p.vert_partitions; find_partitions(nr_of_dpus, &horz_partitions, p.vert_partitions); printf("[INFO] %dx%d Matrix Partitioning\n\n", horz_partitions, vert_partitions); B = coo2rbdcsr(C, horz_partitions, vert_partitions); freeCOOMatrix(C); A = rbdcsr2rbdbcsr(B, p.row_blsize, p.col_blsize); countNNZperBlockRBDBCSRMatrix(A); freeRBDCSRMatrix(B); // Initialize partition data part_info = partition_init(A, nr_of_dpus, p.max_nranks, NR_TASKLETS); #if FG_TRANS struct dpu_set_t rank; uint32_t each_rank; DPU_RANK_FOREACH(dpu_set, rank, each_rank){ uint32_t nr_dpus_in_rank; DPU_ASSERT(dpu_get_nr_dpus(rank, &nr_dpus_in_rank)); part_info->active_dpus_per_rank[each_rank+1] = nr_dpus_in_rank; } int sum = 0; for(int i=0; i < p.max_nranks+1; i++) { part_info->accum_dpus_ranks[i] = part_info->active_dpus_per_rank[i] + sum; sum += part_info->active_dpus_per_rank[i]; } #endif // Initialize help data - Padding needed uint32_t ncols_pad = A->ncols + A->tile_width + A->col_block_size; uint32_t tile_width_pad = A->num_block_cols * A->col_block_size; uint32_t nrows_pad = A->nrows + A->row_block_size; if (ncols_pad % (8 / byte_dt) != 0) ncols_pad = ncols_pad + ((8 / byte_dt) - (ncols_pad % (8 / byte_dt))); if (tile_width_pad % (8 / byte_dt) != 0) tile_width_pad = tile_width_pad + ((8 / byte_dt) - (tile_width_pad % (8 / byte_dt))); #if INT8 if (tile_width_pad % 2 != 0) tile_width_pad++; #endif if (nrows_pad % (8 / byte_dt) != 0) nrows_pad = nrows_pad + ((8 / byte_dt) - (nrows_pad % (8 / byte_dt))); // Allocate input vector x = (val_dt *) malloc(ncols_pad * sizeof(val_dt)); // Allocate output vector z = (val_dt *) calloc(nrows_pad, sizeof(val_dt)); // Initialize input vector with arbitrary data init_vector(x, ncols_pad); // Load-balance blocks (at block-row granularity) across DPUs of the same vertical partition partition_by_block(A, part_info); // Initialize help data dpu_info = (struct dpu_info_t *) malloc(nr_of_dpus * sizeof(struct dpu_info_t)); dpu_arguments_t *input_args = (dpu_arguments_t *) malloc(nr_of_dpus * sizeof(dpu_arguments_t)); // Max limits for parallel transfers uint64_t max_block_rows_per_dpu = 0; uint64_t max_blocks_per_dpu = 0; // Timer for measurements Timer timer; i = 0; uint32_t acc_blocks = 0; uint32_t total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { // Find padding for block rows and non-zero elements needed for CPU-DPU transfers uint32_t tile_horz_indx = i % A->horz_partitions; uint32_t tile_vert_indx = i / A->horz_partitions; uint32_t block_rows_per_dpu = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx + 1] - part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx]; uint32_t block_rows_per_dpu_pad = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx + 1] - part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx] + 1; uint32_t prev_block_rows_dpu = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx]; if (block_rows_per_dpu_pad > max_block_rows_per_dpu) max_block_rows_per_dpu = block_rows_per_dpu_pad; unsigned int blocks, blocks_pad; blocks = A->browptr[tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu + block_rows_per_dpu] - A->browptr[tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu]; assert(blocks == part_info->blocks_dpu[i]); if (blocks % 2 != 0) // bcolind blocks_pad = blocks + 1; else blocks_pad = blocks; if (blocks_pad > max_blocks_per_dpu) max_blocks_per_dpu = blocks_pad; // Keep information per DPU dpu_info[i].block_rows_per_dpu = block_rows_per_dpu; dpu_info[i].prev_block_rows_dpu = prev_block_rows_dpu; dpu_info[i].cols_per_dpu = A->tile_width; dpu_info[i].blocks = blocks; dpu_info[i].blocks_pad = blocks_pad; dpu_info[i].prev_blocks_dpu = total_blocks; dpu_info[i].ptr_offset = tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu; // Find input arguments per DPU input_args[i].block_rows = block_rows_per_dpu; input_args[i].tcols = tile_width_pad; input_args[i].row_block_size = A->row_block_size; input_args[i].col_block_size = A->col_block_size; #if BLNC_TSKLT_BLOCK // Load-balance blocks across tasklets partition_tsklt_by_block(A, part_info, i, NR_TASKLETS, nr_of_dpus, acc_blocks, prev_block_rows_dpu, block_rows_per_dpu, tile_vert_indx); #else // Load-balance nnzs across tasklets partition_tsklt_by_nnz(A, part_info, i, NR_TASKLETS, nr_of_dpus, acc_blocks, prev_block_rows_dpu, block_rows_per_dpu, tile_vert_indx); #endif uint32_t t; for (t = 0; t < NR_TASKLETS; t++) { // Find input arguments per tasklet input_args[i].start_block_row[t] = part_info->brow_split_tasklet[i * (NR_TASKLETS+2) + t]; input_args[i].end_block_row[t] = part_info->brow_split_tasklet[i * (NR_TASKLETS+2) + (t+1)]; } if (tile_horz_indx == (A->horz_partitions - 1)) acc_blocks += A->blocks_per_vert_partition[tile_vert_indx]; total_blocks += part_info->blocks_dpu[i]; } #if FG_TRANS // Find max number of block rows (subset of elements of the output vector) among DPUs of each rank DPU_RANK_FOREACH(dpu_set, rank, each_rank){ uint32_t max_block_rows_cur_rank = 0; uint32_t nr_dpus_in_rank; DPU_ASSERT(dpu_get_nr_dpus(rank, &nr_dpus_in_rank)); uint32_t start_dpu = part_info->accum_dpus_ranks[each_rank]; for (uint32_t k = 0; k < nr_dpus_in_rank; k++) { if (start_dpu + k >= nr_of_dpus) break; if (dpu_info[start_dpu + k].block_rows_per_dpu > max_block_rows_cur_rank) max_block_rows_cur_rank = dpu_info[start_dpu + k].block_rows_per_dpu; } if (max_block_rows_cur_rank % 2 != 0) max_block_rows_cur_rank++; part_info->max_block_rows_per_rank[each_rank] = (uint32_t) max_block_rows_cur_rank; } #endif // Initializations for parallel transfers with padding needed if (max_block_rows_per_dpu % 2 != 0) max_block_rows_per_dpu++; if (max_blocks_per_dpu % 2 != 0) max_blocks_per_dpu++; // Re-allocations for padding needed A->browptr = (uint32_t *) realloc(A->browptr, (max_block_rows_per_dpu * nr_of_dpus * sizeof(uint32_t))); A->bcolind = (uint32_t *) realloc(A->bcolind, (max_blocks_per_dpu * nr_of_dpus * sizeof(uint32_t))); A->bval = (val_dt *) realloc(A->bval, (max_blocks_per_dpu * A->row_block_size * A->col_block_size * nr_of_dpus * sizeof(val_dt))); y = (val_dt *) calloc((uint64_t) ((uint64_t) nr_of_dpus * (uint64_t) max_block_rows_per_dpu * A->row_block_size), sizeof(val_dt)); // Count total number of bytes to be transfered in MRAM of DPU unsigned long int total_bytes; total_bytes = ((max_block_rows_per_dpu) * sizeof(uint32_t)) + (max_blocks_per_dpu * sizeof(uint32_t)) + (max_blocks_per_dpu * A->row_block_size * A->col_block_size * sizeof(val_dt)) + (tile_width_pad * sizeof(val_dt)) + (max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt)); assert(total_bytes <= DPU_CAPACITY && "Bytes needed exceeded MRAM size"); // Copy input arguments to DPUs i = 0; DPU_FOREACH(dpu_set, dpu, i) { input_args[i].max_block_rows = max_block_rows_per_dpu; input_args[i].max_blocks = max_blocks_per_dpu; DPU_ASSERT(dpu_prepare_xfer(dpu, input_args + i)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, "DPU_INPUT_ARGUMENTS", 0, sizeof(dpu_arguments_t), DPU_XFER_DEFAULT)); // Copy input matrix to DPUs startTimer(&timer, 0); // Copy Browptr i = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->browptr + dpu_info[i].ptr_offset)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, (max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt)), max_block_rows_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT)); // Copy Bcolind i = 0; total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->bcolind + total_blocks)); total_blocks += part_info->blocks_dpu[i]; } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_block_rows_per_dpu * sizeof(uint32_t), max_blocks_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT)); // Copy Bvalues i = 0; total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->bval + ((uint64_t) total_blocks * A->row_block_size * A->col_block_size))); total_blocks += part_info->blocks_dpu[i]; } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_block_rows_per_dpu * sizeof(uint32_t) + max_blocks_per_dpu * sizeof(uint32_t), max_blocks_per_dpu * A->row_block_size * A->col_block_size * sizeof(val_dt), DPU_XFER_DEFAULT)); stopTimer(&timer, 0); // Copy input vector to DPUs startTimer(&timer, 1); i = 0; DPU_FOREACH(dpu_set, dpu, i) { uint32_t tile_vert_indx = i / A->horz_partitions; DPU_ASSERT(dpu_prepare_xfer(dpu, x + tile_vert_indx * A->tile_width)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt), tile_width_pad * sizeof(val_dt), DPU_XFER_DEFAULT)); stopTimer(&timer, 1); // Run kernel on DPUs startTimer(&timer, 2); DPU_ASSERT(dpu_launch(dpu_set, DPU_SYNCHRONOUS)); stopTimer(&timer, 2); #if LOG // Display DPU Log (default: disabled) DPU_FOREACH(dpu_set, dpu) { DPU_ASSERT(dpulog_read_for_dpu(dpu.dpu, stdout)); } #endif // Retrieve results for output vector from DPUs startTimer(&timer, 3); #if CG_TRANS // Coarse-grained data transfers in the output vector i = 0; uint32_t block_rows_footprint = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, y + (i * max_block_rows_per_dpu * A->row_block_size))); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_FROM_DPU, DPU_MRAM_HEAP_POINTER_NAME, 0, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt), DPU_XFER_DEFAULT)); #endif #if FG_TRANS // Fine-grained data transfers in the output vector at rank granularity i = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, y + (i * max_block_rows_per_dpu * A->row_block_size))); } i = 0; //struct dpu_set_t rank; DPU_RANK_FOREACH(dpu_set, rank) { DPU_ASSERT(dpu_push_xfer(rank, DPU_XFER_FROM_DPU, DPU_MRAM_HEAP_POINTER_NAME, 0, part_info->max_block_rows_per_rank[i] * A->row_block_size * sizeof(val_dt), DPU_XFER_ASYNC)); i++; } DPU_ASSERT(dpu_sync(dpu_set)); #endif stopTimer(&timer, 3); // Merge partial results to the host CPU startTimer(&timer, 4); uint32_t r, c, t, b; for (c = 0; c < A->vert_partitions; c++) { for (r = 0; r < A->horz_partitions; r++) { #pragma omp parallel for num_threads(p.nthreads) shared(A, z, y, max_block_rows_per_dpu, r, c) private(t, b) for (t = 0; t < part_info->brow_split[c * (A->horz_partitions + 1) + r+1] - part_info->brow_split[c * (A->horz_partitions + 1) + r]; t++) { for (b = 0; b < A->row_block_size; b++) { z[(part_info->brow_split[c * (A->horz_partitions + 1) + r] + t) * A->row_block_size + b] += y[(c * A->horz_partitions + r) * max_block_rows_per_dpu * A->row_block_size + t * A->row_block_size + b]; } } } } stopTimer(&timer, 4); // Print timing results printf("\n"); printf("Load Matrix "); printTimer(&timer, 0); printf("Load Input Vector "); printTimer(&timer, 1); printf("Kernel "); printTimer(&timer, 2); printf("Retrieve Output Vector "); printTimer(&timer, 3); printf("Merge Partial Results "); printTimer(&timer, 4); printf("\n\n"); #if CHECK_CORR // Check output startTimer(&timer, 4); val_dt *y_host = (val_dt *) calloc(nrows_pad, sizeof(val_dt)); spmv_host(y_host, A, x); bool status = true; i = 0; for (i = 0; i < A->nrows; i++) { if(y_host[i] != z[i]) { status = false; } } if (status) { printf("[" ANSI_COLOR_GREEN "OK" ANSI_COLOR_RESET "] Outputs are equal\n"); } else { printf("[" ANSI_COLOR_RED "ERROR" ANSI_COLOR_RESET "] Outputs differ!\n"); } free(y_host); #endif // Deallocation freeRBDBCSRMatrix(A); free(x); free(y); free(z); partition_free(part_info); DPU_ASSERT(dpu_free(dpu_set)); return 0; }
merge_tasks_unnested.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <omp.h> /* OpenMP Parallel Mergesort - STasking * * @author: ANDREW VAILLANCOURT * 2019 */ void merge(int a[], int size, int temp[]); void insertion_sort(int a[], int size); void mergesort_serial(int a[], int size, int temp[], int thresh); void mergesort_parallel_omp(int a[], int size, int temp[], int threads, int thresh); void run_omp(int a[], int size, int temp[], int threads, int thresh); void par_mergesort (int a[], int size, int temp[], int threads, int thresh); int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: %s array_size threshold num_threads\n", argv[0]); return 1; } int size = atoi(argv[1]); // Array size int thresh = atoi(argv[2]); // point at which sort switches to insertion int threads = atoi(argv[3]); // Requested number of threads double start, end; // Check nested parallelism availability omp_set_nested(1); if (omp_get_nested() != 1) { puts("Warning: Nested parallelism desired but unavailable"); } // Check processors and threads int processors = omp_get_num_procs(); // Available processors if (threads > processors) { printf("Warning: %d threads requested, will run_omp on %d processors available\n",threads, processors); omp_set_num_threads(threads); } int max_threads = omp_get_max_threads(); // Max available threads if (threads > max_threads) // Requested threads are more than max available { printf("Error: Cannot use %d threads, only %d threads available\n", threads, max_threads); return 1; } // Array allocation int *a = malloc(sizeof(int) * size); int *temp = malloc(sizeof(int) * size); if (a == NULL || temp == NULL) { printf("Error: Could not allocate array of size %d\n", size); return 1; } // array initialization int i; srand(314159); for (i = 0; i < size; i++) { a[i] = rand() % size; } // run sort and get time start = omp_get_wtime(); run_omp(a, size, temp, threads, thresh); end = omp_get_wtime(); printf("%.4f\n", end - start); // check sorted for (i = 1; i < size; i++) { if (!(a[i - 1] <= a[i])) { printf("Error: final array not sorted => a[%d]=%d > a[%d]=%d\n", i - 1, a[i - 1], i, a[i]); return 1; } } return 0; } void run_omp(int a[], int size, int temp[], int threads, int thresh) { //omp_set_nested(1); // Enable nested parallelism, if available par_mergesort(a, size, temp, threads, thresh); } // OpenMP merge sort with given number of threads void mergesort_parallel_omp(int a[], int size, int temp[], int threads, int thresh) { if (threads == 1) { mergesort_serial(a, size, temp, thresh); } else if (threads > 1) { #pragma omp task { mergesort_parallel_omp(a, size / 2, temp, threads / 2, thresh); } #pragma omp task { mergesort_parallel_omp(a + size / 2, size - size / 2, temp + size / 2, threads - threads / 2, thresh); } #pragma omp taskwait { merge(a, size, temp); } } else { printf("Error: %d threads\n", threads); return; } } void par_mergesort (int a[], int size, int temp[], int threads, int thresh) { #pragma omp parallel { #pragma omp single nowait mergesort_parallel_omp (a, size, temp, threads, thresh); } } // only called if num_threads = 1 void mergesort_serial(int a[], int size, int temp[], int thresh) { // Switch to insertion sort for small arrays if (size <= thresh) { insertion_sort(a, size); return; } mergesort_serial(a, size / 2, temp, thresh); mergesort_serial(a + size / 2, size - size / 2, temp, thresh); merge(a, size, temp); } void merge(int a[], int size, int temp[]) { int i1 = 0; int i2 = size / 2; int tempi = 0; while (i1 < size / 2 && i2 < size) { if (a[i1] < a[i2]) { temp[tempi] = a[i1]; i1++; } else { temp[tempi] = a[i2]; i2++; } tempi++; } while (i1 < size / 2) { temp[tempi] = a[i1]; i1++; tempi++; } while (i2 < size) { temp[tempi] = a[i2]; i2++; tempi++; } // Copy sorted temp array into main array, a memcpy(a, temp, size * sizeof(int)); } void insertion_sort(int a[], int size) { int i; for (i = 0; i < size; i++) { int j, v = a[i]; for (j = i - 1; j >= 0; j--) { if (a[j] <= v) break; a[j + 1] = a[j]; } a[j + 1] = v; } }
convolution_3x3_pack8_int8.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_winograd42_transform_kernel_pack8_int8_neon(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch) { // winograd42 transform kernel Mat kernel_tm(6 * 6, inch, outch, 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 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 = 8b-8a-inch/8a-36-outch/8b kernel_tm_pack8.create(inch / 8, 36, outch / 8, (size_t)2u * 64, 64); int q = 0; for (; q + 7 < outch; q += 8) { 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); const Mat k4 = kernel_tm.channel(q + 4); const Mat k5 = kernel_tm.channel(q + 5); const Mat k6 = kernel_tm.channel(q + 6); const Mat k7 = kernel_tm.channel(q + 7); Mat g0 = kernel_tm_pack8.channel(q / 8); for (int k = 0; k < 36; k++) { short* g00 = g0.row<short>(k); for (int p = 0; p + 7 < inch; p += 8) { 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); const short* k40 = k4.row<const short>(p + i); const short* k50 = k5.row<const short>(p + i); const short* k60 = k6.row<const short>(p + i); const short* k70 = k7.row<const short>(p + i); 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; } } } } } static void conv3x3s1_winograd42_pack8_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; // size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_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++) { int8x8_t _r00 = vld1_s8(r0); int8x8_t _r01 = vld1_s8(r0 + 8); int8x8_t _r02 = vld1_s8(r0 + 16); int8x8_t _r03 = vld1_s8(r0 + 24); int8x8_t _r04 = vld1_s8(r0 + 32); int8x8_t _r05 = vld1_s8(r0 + 40); int8x8_t _v4s8 = vdup_n_s8(4); int8x8_t _v5s8 = vdup_n_s8(5); int16x8_t _v2 = vdupq_n_s16(2); int16x8_t _v4 = vdupq_n_s16(4); // int16x8_t _tmp0m = vfmsq_n_f16(vfmaq_n_f16(_r04, _r00, 4.f), _r02, 5.f); int16x8_t _tmp0m = vsubq_s16(vaddw_s8(vmull_s8(_r00, _v4s8), _r04), vmull_s8(_r02, _v5s8)); // int16x8_t _tmp1m = vfmsq_n_f16(vaddq_f16(_r04, _r03), vaddq_f16(_r01, _r02), 4.f); int16x8_t _tmp1m = vmlsq_s16(vaddl_s8(_r04, _r03), vaddl_s8(_r01, _r02), _v4); // int16x8_t _tmp2m = vfmaq_n_f16(vsubq_f16(_r04, _r03), vsubq_f16(_r01, _r02), 4.f); int16x8_t _tmp2m = vmlaq_s16(vsubl_s8(_r04, _r03), vsubl_s8(_r01, _r02), _v4); // int16x8_t _tmp3m = vfmsq_n_f16(vsubq_f16(_r04, _r02), vsubq_f16(_r01, _r03), 2.f); int16x8_t _tmp3m = vmlsq_s16(vsubl_s8(_r04, _r02), vsubl_s8(_r01, _r03), _v2); // int16x8_t _tmp4m = vfmaq_n_f16(vsubq_f16(_r04, _r02), vsubq_f16(_r01, _r03), 2.f); int16x8_t _tmp4m = vmlaq_s16(vsubl_s8(_r04, _r02), vsubl_s8(_r01, _r03), _v2); // int16x8_t _tmp5m = vfmsq_n_f16(vfmaq_n_f16(_r05, _r01, 4.f), _r03, 5.f); int16x8_t _tmp5m = vsubq_s16(vaddw_s8(vmull_s8(_r01, _v4s8), _r05), vmull_s8(_r03, _v5s8)); vst1q_s16(tmp[0][m], _tmp0m); vst1q_s16(tmp[1][m], _tmp1m); vst1q_s16(tmp[2][m], _tmp2m); vst1q_s16(tmp[3][m], _tmp3m); vst1q_s16(tmp[4][m], _tmp4m); vst1q_s16(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++) { int16x8_t _tmp00 = vld1q_s16(tmp[m][0]); int16x8_t _tmp01 = vld1q_s16(tmp[m][1]); int16x8_t _tmp02 = vld1q_s16(tmp[m][2]); int16x8_t _tmp03 = vld1q_s16(tmp[m][3]); int16x8_t _tmp04 = vld1q_s16(tmp[m][4]); int16x8_t _tmp05 = vld1q_s16(tmp[m][5]); int16x8_t _v2 = vdupq_n_s16(2); int16x8_t _v4 = vdupq_n_s16(4); int16x8_t _v5 = vdupq_n_s16(5); int16x8_t _r0tm0 = vmlsq_s16(vmlaq_s16(_tmp04, _tmp00, _v4), _tmp02, _v5); int16x8_t _r0tm1 = vmlsq_s16(vaddq_s16(_tmp04, _tmp03), vaddq_s16(_tmp01, _tmp02), _v4); int16x8_t _r0tm2 = vmlaq_s16(vsubq_s16(_tmp04, _tmp03), vsubq_s16(_tmp01, _tmp02), _v4); int16x8_t _r0tm3 = vmlsq_s16(vsubq_s16(_tmp04, _tmp02), vsubq_s16(_tmp01, _tmp03), _v2); int16x8_t _r0tm4 = vmlaq_s16(vsubq_s16(_tmp04, _tmp02), vsubq_s16(_tmp01, _tmp03), _v2); int16x8_t _r0tm5 = vmlsq_s16(vmlaq_s16(_tmp05, _tmp01, _v4), _tmp03, _v5); vst1q_s16(r0_tm_0, _r0tm0); vst1q_s16(r0_tm_1, _r0tm1); vst1q_s16(r0_tm_2, _r0tm2); vst1q_s16(r0_tm_3, _r0tm3); vst1q_s16(r0_tm_4, _r0tm4); vst1q_s16(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 __aarch64__ if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else 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 >= 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); #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 __aarch64__ for (; i + 11 < tiles; i += 12) { short* tm2p = tm2.row<short>(i / 12); const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { // transpose 12x8 asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n" "ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0], #64 \n" "ld4 {v16.8h, v17.8h, v18.8h, v19.8h}, [%0] \n" "sub %0, %0, #128 \n" "uzp1 v20.8h, v0.8h, v4.8h \n" // 0 "uzp1 v21.8h, v16.8h, v1.8h \n" // 1 "uzp1 v22.8h, v5.8h, v17.8h \n" // 2 "uzp1 v23.8h, v2.8h, v6.8h \n" // 3 "uzp1 v24.8h, v18.8h, v3.8h \n" // 4 "uzp1 v25.8h, v7.8h, v19.8h \n" // 5 "uzp2 v26.8h, v0.8h, v4.8h \n" // 6 "uzp2 v27.8h, v16.8h, v1.8h \n" // 7 "uzp2 v28.8h, v5.8h, v17.8h \n" // 8 "uzp2 v29.8h, v2.8h, v6.8h \n" // 9 "uzp2 v30.8h, v18.8h, v3.8h \n" // 10 "uzp2 v31.8h, v7.8h, v19.8h \n" // 11 "st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n" "st1 {v24.8h, v25.8h, v26.8h, v27.8h}, [%1], #64 \n" "st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); r0 += bottom_blob_tm.cstep * 8; } } for (; i + 7 < tiles; i += 8) { short* tmpptr = tm2.row<short>(i / 12 + (i % 12) / 8); const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { // transpose 8x8 asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n" "ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0] \n" "sub %0, %0, #64 \n" "uzp1 v16.8h, v0.8h, v4.8h \n" "uzp2 v20.8h, v0.8h, v4.8h \n" "uzp1 v17.8h, v1.8h, v5.8h \n" "uzp2 v21.8h, v1.8h, v5.8h \n" "uzp1 v18.8h, v2.8h, v6.8h \n" "uzp2 v22.8h, v2.8h, v6.8h \n" "uzp1 v19.8h, v3.8h, v7.8h \n" "uzp2 v23.8h, v3.8h, v7.8h \n" "st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n" "st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); r0 += bottom_blob_tm.cstep * 8; } } #endif // __aarch64__ for (; i + 3 < tiles; i += 4) { #if __aarch64__ short* tmpptr = tm2.row<short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else short* tmpptr = tm2.row<short>(i / 4); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n" "st1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "v0", "v1", "v2", "v3"); #else asm volatile( "pld [%0, #512] \n" "vldm %0, {d0-d7} \n" "vstm %1!, {d0-d7} \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "q0", "q1", "q2", "q3"); #endif r0 += bottom_blob_tm.cstep * 8; } } for (; i + 1 < tiles; i += 2) { #if __aarch64__ short* tmpptr = tm2.row<short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v0.8h, v1.8h}, [%0] \n" "st1 {v0.8h, v1.8h}, [%1], #32 \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "v0", "v1"); #else asm volatile( "pld [%0, #256] \n" "vld1.s16 {d0-d3}, [%0 :128] \n" "vst1.s16 {d0-d3}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "q0", "q1"); #endif r0 += bottom_blob_tm.cstep * 8; } } for (; i < tiles; i++) { #if __aarch64__ short* tmpptr = tm2.row<short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2 + i % 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.8h}, [%0] \n" "st1 {v0.8h}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "v0"); #else asm volatile( "pld [%0, #128] \n" "vld1.s16 {d0-d1}, [%0 :128] \n" "vst1.s16 {d0-d1}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tmpptr) // %1 : "0"(r0), "1"(tmpptr) : "memory", "q0"); #endif r0 += bottom_blob_tm.cstep * 8; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { 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 __aarch64__ for (; i + 11 < tiles; i += 12) { const short* r0 = bb2.row<const short>(i / 12); const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 asm volatile( "ld1 {v0.8h, v1.8h}, [%2], #32 \n" // r01 "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "ld1 {v4.8h, v5.8h}, [%3], #32 \n" // w01 "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "prfm pldl1keep, [%2, #256] \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "prfm pldl1keep, [%3, #256] \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "smlal v8.4s, v4.4h, v0.h[0] \n" "smlal2 v9.4s, v4.8h, v0.h[0] \n" "smlal v10.4s, v4.4h, v0.h[1] \n" "smlal2 v11.4s, v4.8h, v0.h[1] \n" "smlal v12.4s, v4.4h, v0.h[2] \n" "smlal2 v13.4s, v4.8h, v0.h[2] \n" "smlal v14.4s, v4.4h, v0.h[3] \n" "smlal2 v15.4s, v4.8h, v0.h[3] \n" "smlal v16.4s, v4.4h, v0.h[4] \n" "smlal2 v17.4s, v4.8h, v0.h[4] \n" "smlal v18.4s, v4.4h, v0.h[5] \n" "smlal2 v19.4s, v4.8h, v0.h[5] \n" "smlal v20.4s, v4.4h, v0.h[6] \n" "smlal2 v21.4s, v4.8h, v0.h[6] \n" "smlal v22.4s, v4.4h, v0.h[7] \n" "smlal2 v23.4s, v4.8h, v0.h[7] \n" "ld1 {v2.8h, v3.8h}, [%2], #32 \n" // r23 "smlal v24.4s, v4.4h, v1.h[0] \n" "smlal2 v25.4s, v4.8h, v1.h[0] \n" "smlal v26.4s, v4.4h, v1.h[1] \n" "smlal2 v27.4s, v4.8h, v1.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v28.4s, v4.4h, v1.h[2] \n" "smlal2 v29.4s, v4.8h, v1.h[2] \n" "smlal v30.4s, v4.4h, v1.h[3] \n" "smlal2 v31.4s, v4.8h, v1.h[3] \n" "ld1 {v6.8h, v7.8h}, [%3], #32 \n" // w23 "smlal v8.4s, v5.4h, v1.h[4] \n" "smlal2 v9.4s, v5.8h, v1.h[4] \n" "smlal v10.4s, v5.4h, v1.h[5] \n" "smlal2 v11.4s, v5.8h, v1.h[5] \n" "prfm pldl1keep, [%3, #256] \n" "smlal v12.4s, v5.4h, v1.h[6] \n" "smlal2 v13.4s, v5.8h, v1.h[6] \n" "smlal v14.4s, v5.4h, v1.h[7] \n" "smlal2 v15.4s, v5.8h, v1.h[7] \n" "smlal v16.4s, v5.4h, v2.h[0] \n" "smlal2 v17.4s, v5.8h, v2.h[0] \n" "smlal v18.4s, v5.4h, v2.h[1] \n" "smlal2 v19.4s, v5.8h, v2.h[1] \n" "smlal v20.4s, v5.4h, v2.h[2] \n" "smlal2 v21.4s, v5.8h, v2.h[2] \n" "smlal v22.4s, v5.4h, v2.h[3] \n" "smlal2 v23.4s, v5.8h, v2.h[3] \n" "smlal v24.4s, v5.4h, v2.h[4] \n" "smlal2 v25.4s, v5.8h, v2.h[4] \n" "smlal v26.4s, v5.4h, v2.h[5] \n" "smlal2 v27.4s, v5.8h, v2.h[5] \n" "smlal v28.4s, v5.4h, v2.h[6] \n" "smlal2 v29.4s, v5.8h, v2.h[6] \n" "smlal v30.4s, v5.4h, v2.h[7] \n" "smlal2 v31.4s, v5.8h, v2.h[7] \n" "ld1 {v0.8h, v1.8h}, [%2], #32 \n" // r45 "smlal v8.4s, v6.4h, v3.h[0] \n" "smlal2 v9.4s, v6.8h, v3.h[0] \n" "smlal v10.4s, v6.4h, v3.h[1] \n" "smlal2 v11.4s, v6.8h, v3.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v12.4s, v6.4h, v3.h[2] \n" "smlal2 v13.4s, v6.8h, v3.h[2] \n" "smlal v14.4s, v6.4h, v3.h[3] \n" "smlal2 v15.4s, v6.8h, v3.h[3] \n" "smlal v16.4s, v6.4h, v3.h[4] \n" "smlal2 v17.4s, v6.8h, v3.h[4] \n" "smlal v18.4s, v6.4h, v3.h[5] \n" "smlal2 v19.4s, v6.8h, v3.h[5] \n" "smlal v20.4s, v6.4h, v3.h[6] \n" "smlal2 v21.4s, v6.8h, v3.h[6] \n" "smlal v22.4s, v6.4h, v3.h[7] \n" "smlal2 v23.4s, v6.8h, v3.h[7] \n" "smlal v24.4s, v6.4h, v0.h[0] \n" "smlal2 v25.4s, v6.8h, v0.h[0] \n" "smlal v26.4s, v6.4h, v0.h[1] \n" "smlal2 v27.4s, v6.8h, v0.h[1] \n" "smlal v28.4s, v6.4h, v0.h[2] \n" "smlal2 v29.4s, v6.8h, v0.h[2] \n" "smlal v30.4s, v6.4h, v0.h[3] \n" "smlal2 v31.4s, v6.8h, v0.h[3] \n" "ld1 {v4.8h, v5.8h}, [%3], #32 \n" // w45 "smlal v8.4s, v7.4h, v0.h[4] \n" "smlal2 v9.4s, v7.8h, v0.h[4] \n" "smlal v10.4s, v7.4h, v0.h[5] \n" "smlal2 v11.4s, v7.8h, v0.h[5] \n" "prfm pldl1keep, [%3, #256] \n" "smlal v12.4s, v7.4h, v0.h[6] \n" "smlal2 v13.4s, v7.8h, v0.h[6] \n" "smlal v14.4s, v7.4h, v0.h[7] \n" "smlal2 v15.4s, v7.8h, v0.h[7] \n" "ld1 {v2.8h, v3.8h}, [%2], #32 \n" // r67 "smlal v16.4s, v7.4h, v1.h[0] \n" "smlal2 v17.4s, v7.8h, v1.h[0] \n" "smlal v18.4s, v7.4h, v1.h[1] \n" "smlal2 v19.4s, v7.8h, v1.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v20.4s, v7.4h, v1.h[2] \n" "smlal2 v21.4s, v7.8h, v1.h[2] \n" "smlal v22.4s, v7.4h, v1.h[3] \n" "smlal2 v23.4s, v7.8h, v1.h[3] \n" "smlal v24.4s, v7.4h, v1.h[4] \n" "smlal2 v25.4s, v7.8h, v1.h[4] \n" "smlal v26.4s, v7.4h, v1.h[5] \n" "smlal2 v27.4s, v7.8h, v1.h[5] \n" "smlal v28.4s, v7.4h, v1.h[6] \n" "smlal2 v29.4s, v7.8h, v1.h[6] \n" "smlal v30.4s, v7.4h, v1.h[7] \n" "smlal2 v31.4s, v7.8h, v1.h[7] \n" "smlal v8.4s, v4.4h, v2.h[0] \n" "smlal2 v9.4s, v4.8h, v2.h[0] \n" "smlal v10.4s, v4.4h, v2.h[1] \n" "smlal2 v11.4s, v4.8h, v2.h[1] \n" "smlal v12.4s, v4.4h, v2.h[2] \n" "smlal2 v13.4s, v4.8h, v2.h[2] \n" "smlal v14.4s, v4.4h, v2.h[3] \n" "smlal2 v15.4s, v4.8h, v2.h[3] \n" "smlal v16.4s, v4.4h, v2.h[4] \n" "smlal2 v17.4s, v4.8h, v2.h[4] \n" "smlal v18.4s, v4.4h, v2.h[5] \n" "smlal2 v19.4s, v4.8h, v2.h[5] \n" "smlal v20.4s, v4.4h, v2.h[6] \n" "smlal2 v21.4s, v4.8h, v2.h[6] \n" "smlal v22.4s, v4.4h, v2.h[7] \n" "smlal2 v23.4s, v4.8h, v2.h[7] \n" "ld1 {v0.8h, v1.8h}, [%2], #32 \n" // r89 "smlal v24.4s, v4.4h, v3.h[0] \n" "smlal2 v25.4s, v4.8h, v3.h[0] \n" "smlal v26.4s, v4.4h, v3.h[1] \n" "smlal2 v27.4s, v4.8h, v3.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v28.4s, v4.4h, v3.h[2] \n" "smlal2 v29.4s, v4.8h, v3.h[2] \n" "smlal v30.4s, v4.4h, v3.h[3] \n" "smlal2 v31.4s, v4.8h, v3.h[3] \n" "ld1 {v6.8h, v7.8h}, [%3], #32 \n" // w67 "smlal v8.4s, v5.4h, v3.h[4] \n" "smlal2 v9.4s, v5.8h, v3.h[4] \n" "smlal v10.4s, v5.4h, v3.h[5] \n" "smlal2 v11.4s, v5.8h, v3.h[5] \n" "prfm pldl1keep, [%3, #256] \n" "smlal v12.4s, v5.4h, v3.h[6] \n" "smlal2 v13.4s, v5.8h, v3.h[6] \n" "smlal v14.4s, v5.4h, v3.h[7] \n" "smlal2 v15.4s, v5.8h, v3.h[7] \n" "smlal v16.4s, v5.4h, v0.h[0] \n" "smlal2 v17.4s, v5.8h, v0.h[0] \n" "smlal v18.4s, v5.4h, v0.h[1] \n" "smlal2 v19.4s, v5.8h, v0.h[1] \n" "smlal v20.4s, v5.4h, v0.h[2] \n" "smlal2 v21.4s, v5.8h, v0.h[2] \n" "smlal v22.4s, v5.4h, v0.h[3] \n" "smlal2 v23.4s, v5.8h, v0.h[3] \n" "smlal v24.4s, v5.4h, v0.h[4] \n" "smlal2 v25.4s, v5.8h, v0.h[4] \n" "smlal v26.4s, v5.4h, v0.h[5] \n" "smlal2 v27.4s, v5.8h, v0.h[5] \n" "smlal v28.4s, v5.4h, v0.h[6] \n" "smlal2 v29.4s, v5.8h, v0.h[6] \n" "smlal v30.4s, v5.4h, v0.h[7] \n" "smlal2 v31.4s, v5.8h, v0.h[7] \n" "ld1 {v2.8h, v3.8h}, [%2], #32 \n" // r1011 "smlal v8.4s, v6.4h, v1.h[0] \n" "smlal2 v9.4s, v6.8h, v1.h[0] \n" "smlal v10.4s, v6.4h, v1.h[1] \n" "smlal2 v11.4s, v6.8h, v1.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v12.4s, v6.4h, v1.h[2] \n" "smlal2 v13.4s, v6.8h, v1.h[2] \n" "smlal v14.4s, v6.4h, v1.h[3] \n" "smlal2 v15.4s, v6.8h, v1.h[3] \n" "smlal v16.4s, v6.4h, v1.h[4] \n" "smlal2 v17.4s, v6.8h, v1.h[4] \n" "smlal v18.4s, v6.4h, v1.h[5] \n" "smlal2 v19.4s, v6.8h, v1.h[5] \n" "smlal v20.4s, v6.4h, v1.h[6] \n" "smlal2 v21.4s, v6.8h, v1.h[6] \n" "smlal v22.4s, v6.4h, v1.h[7] \n" "smlal2 v23.4s, v6.8h, v1.h[7] \n" "smlal v24.4s, v6.4h, v2.h[0] \n" "smlal2 v25.4s, v6.8h, v2.h[0] \n" "smlal v26.4s, v6.4h, v2.h[1] \n" "smlal2 v27.4s, v6.8h, v2.h[1] \n" "smlal v28.4s, v6.4h, v2.h[2] \n" "smlal2 v29.4s, v6.8h, v2.h[2] \n" "smlal v30.4s, v6.4h, v2.h[3] \n" "smlal2 v31.4s, v6.8h, v2.h[3] \n" "ld1 {v4.8h, v5.8h}, [%3], #32 \n" // w01 "smlal v8.4s, v7.4h, v2.h[4] \n" "smlal2 v9.4s, v7.8h, v2.h[4] \n" "smlal v10.4s, v7.4h, v2.h[5] \n" "smlal2 v11.4s, v7.8h, v2.h[5] \n" "prfm pldl1keep, [%3, #256] \n" "smlal v12.4s, v7.4h, v2.h[6] \n" "smlal2 v13.4s, v7.8h, v2.h[6] \n" "smlal v14.4s, v7.4h, v2.h[7] \n" "smlal2 v15.4s, v7.8h, v2.h[7] \n" "ld1 {v0.8h, v1.8h}, [%2], #32 \n" // r01 "smlal v16.4s, v7.4h, v3.h[0] \n" "smlal2 v17.4s, v7.8h, v3.h[0] \n" "smlal v18.4s, v7.4h, v3.h[1] \n" "smlal2 v19.4s, v7.8h, v3.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "smlal v20.4s, v7.4h, v3.h[2] \n" "smlal2 v21.4s, v7.8h, v3.h[2] \n" "smlal v22.4s, v7.4h, v3.h[3] \n" "smlal2 v23.4s, v7.8h, v3.h[3] \n" "smlal v24.4s, v7.4h, v3.h[4] \n" "smlal2 v25.4s, v7.8h, v3.h[4] \n" "smlal v26.4s, v7.4h, v3.h[5] \n" "smlal2 v27.4s, v7.8h, v3.h[5] \n" "subs %w0, %w0, #1 \n" "smlal v28.4s, v7.4h, v3.h[6] \n" "smlal2 v29.4s, v7.8h, v3.h[6] \n" "smlal v30.4s, v7.4h, v3.h[7] \n" "smlal2 v31.4s, v7.8h, v3.h[7] \n" "bne 0b \n" "sub %2, %2, #32 \n" "sub %3, %3, #32 \n" "st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" "st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n" "st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%1], #64 \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 7 < tiles; i += 8) { const short* r0 = bb2.row<const short>(i / 12 + (i % 12) / 8); const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); int32x4_t _sum2 = vdupq_n_s32(0); int32x4_t _sum3 = vdupq_n_s32(0); int32x4_t _sum4 = vdupq_n_s32(0); int32x4_t _sum5 = vdupq_n_s32(0); int32x4_t _sum6 = vdupq_n_s32(0); int32x4_t _sum7 = vdupq_n_s32(0); int32x4_t _sum8 = vdupq_n_s32(0); int32x4_t _sum9 = vdupq_n_s32(0); int32x4_t _suma = vdupq_n_s32(0); int32x4_t _sumb = vdupq_n_s32(0); int32x4_t _sumc = vdupq_n_s32(0); int32x4_t _sumd = vdupq_n_s32(0); int32x4_t _sume = vdupq_n_s32(0); int32x4_t _sumf = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _val1 = vld1q_s16(r0 + 8); int16x8_t _val2 = vld1q_s16(r0 + 16); int16x8_t _val3 = vld1q_s16(r0 + 24); int16x8_t _val4 = vld1q_s16(r0 + 32); int16x8_t _val5 = vld1q_s16(r0 + 40); int16x8_t _val6 = vld1q_s16(r0 + 48); int16x8_t _val7 = vld1q_s16(r0 + 56); int16x8_t _w0 = vld1q_s16(k0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w0), vget_low_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w0), vget_low_s16(_val0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w0), vget_low_s16(_val0), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w0), vget_low_s16(_val0), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w0), vget_low_s16(_val0), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w0), vget_low_s16(_val0), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w0), vget_low_s16(_val0), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w0), vget_low_s16(_val0), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w0), vget_high_s16(_val0), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w0), vget_high_s16(_val0), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w0), vget_high_s16(_val0), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w0), vget_high_s16(_val0), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w0), vget_high_s16(_val0), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w0), vget_high_s16(_val0), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w0), vget_high_s16(_val0), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w0), vget_high_s16(_val0), 3); int16x8_t _w1 = vld1q_s16(k0 + 8); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w1), vget_low_s16(_val1), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w1), vget_low_s16(_val1), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w1), vget_low_s16(_val1), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w1), vget_low_s16(_val1), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w1), vget_low_s16(_val1), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w1), vget_low_s16(_val1), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w1), vget_low_s16(_val1), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w1), vget_low_s16(_val1), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w1), vget_high_s16(_val1), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w1), vget_high_s16(_val1), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w1), vget_high_s16(_val1), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w1), vget_high_s16(_val1), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w1), vget_high_s16(_val1), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w1), vget_high_s16(_val1), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w1), vget_high_s16(_val1), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w1), vget_high_s16(_val1), 3); int16x8_t _w2 = vld1q_s16(k0 + 16); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w2), vget_low_s16(_val2), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w2), vget_low_s16(_val2), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w2), vget_low_s16(_val2), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w2), vget_low_s16(_val2), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w2), vget_low_s16(_val2), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w2), vget_low_s16(_val2), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w2), vget_low_s16(_val2), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w2), vget_low_s16(_val2), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w2), vget_high_s16(_val2), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w2), vget_high_s16(_val2), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w2), vget_high_s16(_val2), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w2), vget_high_s16(_val2), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w2), vget_high_s16(_val2), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w2), vget_high_s16(_val2), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w2), vget_high_s16(_val2), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w2), vget_high_s16(_val2), 3); int16x8_t _w3 = vld1q_s16(k0 + 24); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w3), vget_low_s16(_val3), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w3), vget_low_s16(_val3), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w3), vget_low_s16(_val3), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w3), vget_low_s16(_val3), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w3), vget_low_s16(_val3), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w3), vget_low_s16(_val3), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w3), vget_low_s16(_val3), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w3), vget_low_s16(_val3), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w3), vget_high_s16(_val3), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w3), vget_high_s16(_val3), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w3), vget_high_s16(_val3), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w3), vget_high_s16(_val3), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w3), vget_high_s16(_val3), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w3), vget_high_s16(_val3), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w3), vget_high_s16(_val3), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w3), vget_high_s16(_val3), 3); int16x8_t _w4 = vld1q_s16(k0 + 32); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w4), vget_low_s16(_val4), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w4), vget_low_s16(_val4), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w4), vget_low_s16(_val4), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w4), vget_low_s16(_val4), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w4), vget_low_s16(_val4), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w4), vget_low_s16(_val4), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w4), vget_low_s16(_val4), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w4), vget_low_s16(_val4), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w4), vget_high_s16(_val4), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w4), vget_high_s16(_val4), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w4), vget_high_s16(_val4), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w4), vget_high_s16(_val4), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w4), vget_high_s16(_val4), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w4), vget_high_s16(_val4), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w4), vget_high_s16(_val4), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w4), vget_high_s16(_val4), 3); int16x8_t _w5 = vld1q_s16(k0 + 40); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w5), vget_low_s16(_val5), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w5), vget_low_s16(_val5), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w5), vget_low_s16(_val5), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w5), vget_low_s16(_val5), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w5), vget_low_s16(_val5), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w5), vget_low_s16(_val5), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w5), vget_low_s16(_val5), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w5), vget_low_s16(_val5), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w5), vget_high_s16(_val5), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w5), vget_high_s16(_val5), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w5), vget_high_s16(_val5), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w5), vget_high_s16(_val5), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w5), vget_high_s16(_val5), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w5), vget_high_s16(_val5), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w5), vget_high_s16(_val5), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w5), vget_high_s16(_val5), 3); int16x8_t _w6 = vld1q_s16(k0 + 48); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w6), vget_low_s16(_val6), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w6), vget_low_s16(_val6), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w6), vget_low_s16(_val6), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w6), vget_low_s16(_val6), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w6), vget_low_s16(_val6), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w6), vget_low_s16(_val6), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w6), vget_low_s16(_val6), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w6), vget_low_s16(_val6), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w6), vget_high_s16(_val6), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w6), vget_high_s16(_val6), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w6), vget_high_s16(_val6), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w6), vget_high_s16(_val6), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w6), vget_high_s16(_val6), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w6), vget_high_s16(_val6), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w6), vget_high_s16(_val6), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w6), vget_high_s16(_val6), 3); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w7), vget_low_s16(_val7), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w7), vget_low_s16(_val7), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w7), vget_low_s16(_val7), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w7), vget_low_s16(_val7), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w7), vget_low_s16(_val7), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w7), vget_low_s16(_val7), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w7), vget_low_s16(_val7), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w7), vget_low_s16(_val7), 3); _sum8 = vmlal_lane_s16(_sum8, vget_low_s16(_w7), vget_high_s16(_val7), 0); _sum9 = vmlal_lane_s16(_sum9, vget_high_s16(_w7), vget_high_s16(_val7), 0); _suma = vmlal_lane_s16(_suma, vget_low_s16(_w7), vget_high_s16(_val7), 1); _sumb = vmlal_lane_s16(_sumb, vget_high_s16(_w7), vget_high_s16(_val7), 1); _sumc = vmlal_lane_s16(_sumc, vget_low_s16(_w7), vget_high_s16(_val7), 2); _sumd = vmlal_lane_s16(_sumd, vget_high_s16(_w7), vget_high_s16(_val7), 2); _sume = vmlal_lane_s16(_sume, vget_low_s16(_w7), vget_high_s16(_val7), 3); _sumf = vmlal_lane_s16(_sumf, vget_high_s16(_w7), vget_high_s16(_val7), 3); r0 += 64; k0 += 64; } vst1q_s32(output0_tm, _sum0); vst1q_s32(output0_tm + 4, _sum1); vst1q_s32(output0_tm + 8, _sum2); vst1q_s32(output0_tm + 12, _sum3); vst1q_s32(output0_tm + 16, _sum4); vst1q_s32(output0_tm + 20, _sum5); vst1q_s32(output0_tm + 24, _sum6); vst1q_s32(output0_tm + 28, _sum7); vst1q_s32(output0_tm + 32, _sum8); vst1q_s32(output0_tm + 36, _sum9); vst1q_s32(output0_tm + 40, _suma); vst1q_s32(output0_tm + 44, _sumb); vst1q_s32(output0_tm + 48, _sumc); vst1q_s32(output0_tm + 52, _sumd); vst1q_s32(output0_tm + 56, _sume); vst1q_s32(output0_tm + 60, _sumf); output0_tm += 64; } #endif // __aarch64__ for (; i + 3 < tiles; i += 4) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else const short* r0 = bb2.row<const short>(i / 4); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 #if __aarch64__ int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); int32x4_t _sum2 = vdupq_n_s32(0); int32x4_t _sum3 = vdupq_n_s32(0); int32x4_t _sum4 = vdupq_n_s32(0); int32x4_t _sum5 = vdupq_n_s32(0); int32x4_t _sum6 = vdupq_n_s32(0); int32x4_t _sum7 = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _val1 = vld1q_s16(r0 + 8); int16x8_t _val2 = vld1q_s16(r0 + 16); int16x8_t _val3 = vld1q_s16(r0 + 24); int16x8_t _w0 = vld1q_s16(k0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w0), vget_low_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w0), vget_low_s16(_val0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w0), vget_low_s16(_val1), 0); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w0), vget_low_s16(_val1), 0); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w0), vget_low_s16(_val2), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w0), vget_low_s16(_val2), 0); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w0), vget_low_s16(_val3), 0); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w0), vget_low_s16(_val3), 0); int16x8_t _w1 = vld1q_s16(k0 + 8); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w1), vget_low_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w1), vget_low_s16(_val0), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w1), vget_low_s16(_val1), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w1), vget_low_s16(_val1), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w1), vget_low_s16(_val2), 1); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w1), vget_low_s16(_val2), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w1), vget_low_s16(_val3), 1); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w1), vget_low_s16(_val3), 1); int16x8_t _w2 = vld1q_s16(k0 + 16); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w2), vget_low_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w2), vget_low_s16(_val0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w2), vget_low_s16(_val1), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w2), vget_low_s16(_val1), 2); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w2), vget_low_s16(_val2), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w2), vget_low_s16(_val2), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w2), vget_low_s16(_val3), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w2), vget_low_s16(_val3), 2); int16x8_t _w3 = vld1q_s16(k0 + 24); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w3), vget_low_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w3), vget_low_s16(_val0), 3); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w3), vget_low_s16(_val1), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w3), vget_low_s16(_val1), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w3), vget_low_s16(_val2), 3); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w3), vget_low_s16(_val2), 3); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w3), vget_low_s16(_val3), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w3), vget_low_s16(_val3), 3); int16x8_t _w4 = vld1q_s16(k0 + 32); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w4), vget_high_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w4), vget_high_s16(_val0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w4), vget_high_s16(_val1), 0); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w4), vget_high_s16(_val1), 0); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w4), vget_high_s16(_val2), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w4), vget_high_s16(_val2), 0); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w4), vget_high_s16(_val3), 0); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w4), vget_high_s16(_val3), 0); int16x8_t _w5 = vld1q_s16(k0 + 40); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w5), vget_high_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w5), vget_high_s16(_val0), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w5), vget_high_s16(_val1), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w5), vget_high_s16(_val1), 1); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w5), vget_high_s16(_val2), 1); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w5), vget_high_s16(_val2), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w5), vget_high_s16(_val3), 1); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w5), vget_high_s16(_val3), 1); int16x8_t _w6 = vld1q_s16(k0 + 48); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w6), vget_high_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w6), vget_high_s16(_val0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w6), vget_high_s16(_val1), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w6), vget_high_s16(_val1), 2); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w6), vget_high_s16(_val2), 2); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w6), vget_high_s16(_val2), 2); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w6), vget_high_s16(_val3), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w6), vget_high_s16(_val3), 2); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w7), vget_high_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w7), vget_high_s16(_val0), 3); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w7), vget_high_s16(_val1), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w7), vget_high_s16(_val1), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_w7), vget_high_s16(_val2), 3); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_w7), vget_high_s16(_val2), 3); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_w7), vget_high_s16(_val3), 3); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_w7), vget_high_s16(_val3), 3); r0 += 32; k0 += 64; } vst1q_s32(output0_tm, _sum0); vst1q_s32(output0_tm + 4, _sum1); vst1q_s32(output0_tm + 8, _sum2); vst1q_s32(output0_tm + 12, _sum3); vst1q_s32(output0_tm + 16, _sum4); vst1q_s32(output0_tm + 20, _sum5); vst1q_s32(output0_tm + 24, _sum6); vst1q_s32(output0_tm + 28, _sum7); output0_tm += 32; #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "veor q12, q12 \n" "veor q13, q13 \n" "veor q14, q14 \n" "veor q15, q15 \n" "0: \n" "pld [%1, #256] \n" "pld [%1, #512] \n" "vldm %1!, {d0-d7} \n" "pld [%2, #256] \n" "vld1.s16 {d8-d11}, [%2 :128]! \n" "vmlal.s16 q8, d8, d0[0] \n" "vmlal.s16 q9, d9, d0[0] \n" "vmlal.s16 q10, d8, d2[0] \n" "vmlal.s16 q11, d9, d2[0] \n" "vmlal.s16 q12, d8, d4[0] \n" "vmlal.s16 q13, d9, d4[0] \n" "vmlal.s16 q14, d8, d6[0] \n" "vmlal.s16 q15, d9, d6[0] \n" "pld [%2, #128] \n" "vld1.s16 {d8-d9}, [%2 :128]! \n" "vmlal.s16 q8, d10, d0[1] \n" "vmlal.s16 q9, d11, d0[1] \n" "vmlal.s16 q10, d10, d2[1] \n" "vmlal.s16 q11, d11, d2[1] \n" "vmlal.s16 q12, d10, d4[1] \n" "vmlal.s16 q13, d11, d4[1] \n" "vmlal.s16 q14, d10, d6[1] \n" "vmlal.s16 q15, d11, d6[1] \n" "pld [%2, #128] \n" "vld1.s16 {d10-d11}, [%2 :128]! \n" "vmlal.s16 q8, d8, d0[2] \n" "vmlal.s16 q9, d9, d0[2] \n" "vmlal.s16 q10, d8, d2[2] \n" "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d4[2] \n" "vmlal.s16 q13, d9, d4[2] \n" "vmlal.s16 q14, d8, d6[2] \n" "vmlal.s16 q15, d9, d6[2] \n" "pld [%2, #128] \n" "vld1.s16 {d8-d9}, [%2 :128]! \n" "vmlal.s16 q8, d10, d0[3] \n" "vmlal.s16 q9, d11, d0[3] \n" "vmlal.s16 q10, d10, d2[3] \n" "vmlal.s16 q11, d11, d2[3] \n" "vmlal.s16 q12, d10, d4[3] \n" "vmlal.s16 q13, d11, d4[3] \n" "vmlal.s16 q14, d10, d6[3] \n" "vmlal.s16 q15, d11, d6[3] \n" "pld [%2, #128] \n" "vld1.s16 {d10-d11}, [%2 :128]! \n" "vmlal.s16 q8, d8, d1[0] \n" "vmlal.s16 q9, d9, d1[0] \n" "vmlal.s16 q10, d8, d3[0] \n" "vmlal.s16 q11, d9, d3[0] \n" "vmlal.s16 q12, d8, d5[0] \n" "vmlal.s16 q13, d9, d5[0] \n" "vmlal.s16 q14, d8, d7[0] \n" "vmlal.s16 q15, d9, d7[0] \n" "pld [%2, #128] \n" "vld1.s16 {d8-d9}, [%2 :128]! \n" "vmlal.s16 q8, d10, d1[1] \n" "vmlal.s16 q9, d11, d1[1] \n" "vmlal.s16 q10, d10, d3[1] \n" "vmlal.s16 q11, d11, d3[1] \n" "vmlal.s16 q12, d10, d5[1] \n" "vmlal.s16 q13, d11, d5[1] \n" "vmlal.s16 q14, d10, d7[1] \n" "vmlal.s16 q15, d11, d7[1] \n" "pld [%2, #128] \n" "vld1.s16 {d10-d11}, [%2 :128]! \n" "vmlal.s16 q8, d8, d1[2] \n" "vmlal.s16 q9, d9, d1[2] \n" "vmlal.s16 q10, d8, d3[2] \n" "vmlal.s16 q11, d9, d3[2] \n" "vmlal.s16 q12, d8, d5[2] \n" "vmlal.s16 q13, d9, d5[2] \n" "vmlal.s16 q14, d8, d7[2] \n" "vmlal.s16 q15, d9, d7[2] \n" "subs %3, %3, #1 \n" "vmlal.s16 q8, d10, d1[3] \n" "vmlal.s16 q9, d11, d1[3] \n" "vmlal.s16 q10, d10, d3[3] \n" "vmlal.s16 q11, d11, d3[3] \n" "vmlal.s16 q12, d10, d5[3] \n" "vmlal.s16 q13, d11, d5[3] \n" "vmlal.s16 q14, d10, d7[3] \n" "vmlal.s16 q15, d11, d7[3] \n" "bne 0b \n" "1: \n" "vstm %0!, {d16-d23} \n" "vstm %0!, {d24-d31} \n" : "=r"(output0_tm), "=r"(r0), "=r"(k0), "=r"(nn) : "0"(output0_tm), "1"(r0), "2"(k0), "3"(nn) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif } for (; i + 1 < tiles; i += 2) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); int32x4_t _sum2 = vdupq_n_s32(0); int32x4_t _sum3 = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _val1 = vld1q_s16(r0 + 8); int16x8_t _w0 = vld1q_s16(k0); int16x8_t _w1 = vld1q_s16(k0 + 8); int16x8_t _w2 = vld1q_s16(k0 + 16); int16x8_t _w3 = vld1q_s16(k0 + 24); int16x8_t _w4 = vld1q_s16(k0 + 32); int16x8_t _w5 = vld1q_s16(k0 + 40); int16x8_t _w6 = vld1q_s16(k0 + 48); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w0), vget_low_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w0), vget_low_s16(_val0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w0), vget_low_s16(_val1), 0); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w0), vget_low_s16(_val1), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w1), vget_low_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w1), vget_low_s16(_val0), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w1), vget_low_s16(_val1), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w1), vget_low_s16(_val1), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w2), vget_low_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w2), vget_low_s16(_val0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w2), vget_low_s16(_val1), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w2), vget_low_s16(_val1), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w3), vget_low_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w3), vget_low_s16(_val0), 3); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w3), vget_low_s16(_val1), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w3), vget_low_s16(_val1), 3); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w4), vget_high_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w4), vget_high_s16(_val0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w4), vget_high_s16(_val1), 0); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w4), vget_high_s16(_val1), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w5), vget_high_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w5), vget_high_s16(_val0), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w5), vget_high_s16(_val1), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w5), vget_high_s16(_val1), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w6), vget_high_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w6), vget_high_s16(_val0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w6), vget_high_s16(_val1), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w6), vget_high_s16(_val1), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w7), vget_high_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w7), vget_high_s16(_val0), 3); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_w7), vget_high_s16(_val1), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_w7), vget_high_s16(_val1), 3); r0 += 16; k0 += 64; } vst1q_s32(output0_tm, _sum0); vst1q_s32(output0_tm + 4, _sum1); vst1q_s32(output0_tm + 8, _sum2); vst1q_s32(output0_tm + 12, _sum3); output0_tm += 16; } for (; i < tiles; i++) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _w0 = vld1q_s16(k0); int16x8_t _w1 = vld1q_s16(k0 + 8); int16x8_t _w2 = vld1q_s16(k0 + 16); int16x8_t _w3 = vld1q_s16(k0 + 24); int16x8_t _w4 = vld1q_s16(k0 + 32); int16x8_t _w5 = vld1q_s16(k0 + 40); int16x8_t _w6 = vld1q_s16(k0 + 48); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w0), vget_low_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w0), vget_low_s16(_val0), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w1), vget_low_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w1), vget_low_s16(_val0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w2), vget_low_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w2), vget_low_s16(_val0), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w3), vget_low_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w3), vget_low_s16(_val0), 3); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w4), vget_high_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w4), vget_high_s16(_val0), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w5), vget_high_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w5), vget_high_s16(_val0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w6), vget_high_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w6), vget_high_s16(_val0), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w7), vget_high_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w7), vget_high_s16(_val0), 3); r0 += 8; k0 += 64; } vst1q_s32(output0_tm, _sum0); vst1q_s32(output0_tm + 4, _sum1); output0_tm += 8; } } } } 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 * elempack, elempack, 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][8]; // 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) * 8; const int* output0_tm_1 = output0_tm_0 + tiles * 8; const int* output0_tm_2 = output0_tm_0 + tiles * 16; const int* output0_tm_3 = output0_tm_0 + tiles * 24; const int* output0_tm_4 = output0_tm_0 + tiles * 32; const int* output0_tm_5 = output0_tm_0 + tiles * 40; int* output0 = out0.row<int>(i * 4) + (j * 4) * 8; // TODO neon optimize for (int m = 0; m < 5; m++) { int32x4_t _out0tm0_low = vld1q_s32(output0_tm_0); int32x4_t _out0tm0_high = vld1q_s32(output0_tm_0 + 4); int32x4_t _out0tm1_low = vld1q_s32(output0_tm_1); int32x4_t _out0tm1_high = vld1q_s32(output0_tm_1 + 4); int32x4_t _out0tm2_low = vld1q_s32(output0_tm_2); int32x4_t _out0tm2_high = vld1q_s32(output0_tm_2 + 4); int32x4_t _out0tm3_low = vld1q_s32(output0_tm_3); int32x4_t _out0tm3_high = vld1q_s32(output0_tm_3 + 4); int32x4_t _out0tm4_low = vld1q_s32(output0_tm_4); int32x4_t _out0tm4_high = vld1q_s32(output0_tm_4 + 4); int32x4_t _out0tm5_low = vld1q_s32(output0_tm_5); int32x4_t _out0tm5_high = vld1q_s32(output0_tm_5 + 4); int32x4_t _tmp02a_low = vaddq_s32(_out0tm1_low, _out0tm2_low); int32x4_t _tmp02a_high = vaddq_s32(_out0tm1_high, _out0tm2_high); int32x4_t _tmp13a_low = vsubq_s32(_out0tm1_low, _out0tm2_low); int32x4_t _tmp13a_high = vsubq_s32(_out0tm1_high, _out0tm2_high); int32x4_t _tmp02b_low = vaddq_s32(_out0tm3_low, _out0tm4_low); int32x4_t _tmp02b_high = vaddq_s32(_out0tm3_high, _out0tm4_high); int32x4_t _tmp13b_low = vsubq_s32(_out0tm3_low, _out0tm4_low); int32x4_t _tmp13b_high = vsubq_s32(_out0tm3_high, _out0tm4_high); int32x4_t _v2 = vdupq_n_s32(2); int32x4_t _v4 = vdupq_n_s32(4); int32x4_t _v8 = vdupq_n_s32(8); int32x4_t _tmp0m_low = vaddq_s32(vaddq_s32(_out0tm0_low, _tmp02a_low), _tmp02b_low); int32x4_t _tmp0m_high = vaddq_s32(vaddq_s32(_out0tm0_high, _tmp02a_high), _tmp02b_high); int32x4_t _tmp1m_low = vmlaq_s32(_tmp13a_low, _tmp13b_low, _v2); int32x4_t _tmp1m_high = vmlaq_s32(_tmp13a_high, _tmp13b_high, _v2); int32x4_t _tmp2m_low = vmlaq_s32(_tmp02a_low, _tmp02b_low, _v4); int32x4_t _tmp2m_high = vmlaq_s32(_tmp02a_high, _tmp02b_high, _v4); int32x4_t _tmp3m_low = vmlaq_s32(vmlaq_s32(_tmp13a_low, _out0tm5_low, _v4), _tmp13b_low, _v8); int32x4_t _tmp3m_high = vmlaq_s32(vmlaq_s32(_tmp13a_high, _out0tm5_high, _v4), _tmp13b_high, _v8); vst1q_s32(tmp[0][m], _tmp0m_low); vst1q_s32(tmp[0][m] + 4, _tmp0m_high); vst1q_s32(tmp[1][m], _tmp1m_low); vst1q_s32(tmp[1][m] + 4, _tmp1m_high); vst1q_s32(tmp[2][m], _tmp2m_low); vst1q_s32(tmp[2][m] + 4, _tmp2m_high); vst1q_s32(tmp[3][m], _tmp3m_low); vst1q_s32(tmp[3][m] + 4, _tmp3m_high); output0_tm_0 += tiles * 48; output0_tm_1 += tiles * 48; output0_tm_2 += tiles * 48; output0_tm_3 += tiles * 48; output0_tm_4 += tiles * 48; output0_tm_5 += tiles * 48; } for (int m = 5; m < 6; m++) { int32x4_t _out0tm0_low = vld1q_s32(output0_tm_0); int32x4_t _out0tm0_high = vld1q_s32(output0_tm_0 + 4); int32x4_t _out0tm1_low = vld1q_s32(output0_tm_1); int32x4_t _out0tm1_high = vld1q_s32(output0_tm_1 + 4); int32x4_t _out0tm2_low = vld1q_s32(output0_tm_2); int32x4_t _out0tm2_high = vld1q_s32(output0_tm_2 + 4); int32x4_t _out0tm3_low = vld1q_s32(output0_tm_3); int32x4_t _out0tm3_high = vld1q_s32(output0_tm_3 + 4); int32x4_t _out0tm4_low = vld1q_s32(output0_tm_4); int32x4_t _out0tm4_high = vld1q_s32(output0_tm_4 + 4); int32x4_t _out0tm5_low = vld1q_s32(output0_tm_5); int32x4_t _out0tm5_high = vld1q_s32(output0_tm_5 + 4); int32x4_t _tmp02a_low = vaddq_s32(_out0tm1_low, _out0tm2_low); int32x4_t _tmp02a_high = vaddq_s32(_out0tm1_high, _out0tm2_high); int32x4_t _tmp13a_low = vsubq_s32(_out0tm1_low, _out0tm2_low); int32x4_t _tmp13a_high = vsubq_s32(_out0tm1_high, _out0tm2_high); int32x4_t _tmp02b_low = vaddq_s32(_out0tm3_low, _out0tm4_low); int32x4_t _tmp02b_high = vaddq_s32(_out0tm3_high, _out0tm4_high); int32x4_t _tmp13b_low = vsubq_s32(_out0tm3_low, _out0tm4_low); int32x4_t _tmp13b_high = vsubq_s32(_out0tm3_high, _out0tm4_high); int32x4_t _v2 = vdupq_n_s32(2); int32x4_t _v4 = vdupq_n_s32(4); int32x4_t _v8 = vdupq_n_s32(8); int32x4_t _tmp0m_low = vaddq_s32(vaddq_s32(_out0tm0_low, _tmp02a_low), _tmp02b_low); int32x4_t _tmp0m_high = vaddq_s32(vaddq_s32(_out0tm0_high, _tmp02a_high), _tmp02b_high); int32x4_t _tmp1m_low = vmlaq_s32(_tmp13a_low, _tmp13b_low, _v2); int32x4_t _tmp1m_high = vmlaq_s32(_tmp13a_high, _tmp13b_high, _v2); int32x4_t _tmp2m_low = vmlaq_s32(_tmp02a_low, _tmp02b_low, _v4); int32x4_t _tmp2m_high = vmlaq_s32(_tmp02a_high, _tmp02b_high, _v4); int32x4_t _tmp3m_low = vmlaq_s32(vmlaq_s32(_tmp13a_low, _out0tm5_low, _v4), _tmp13b_low, _v8); int32x4_t _tmp3m_high = vmlaq_s32(vmlaq_s32(_tmp13a_high, _out0tm5_high, _v4), _tmp13b_high, _v8); _tmp0m_low = vmulq_s32(_tmp0m_low, _v4); _tmp0m_high = vmulq_s32(_tmp0m_high, _v4); _tmp1m_low = vmulq_s32(_tmp1m_low, _v4); _tmp1m_high = vmulq_s32(_tmp1m_high, _v4); _tmp2m_low = vmulq_s32(_tmp2m_low, _v4); _tmp2m_high = vmulq_s32(_tmp2m_high, _v4); _tmp3m_low = vmulq_s32(_tmp3m_low, _v4); _tmp3m_high = vmulq_s32(_tmp3m_high, _v4); vst1q_s32(tmp[0][m], _tmp0m_low); vst1q_s32(tmp[0][m] + 4, _tmp0m_high); vst1q_s32(tmp[1][m], _tmp1m_low); vst1q_s32(tmp[1][m] + 4, _tmp1m_high); vst1q_s32(tmp[2][m], _tmp2m_low); vst1q_s32(tmp[2][m] + 4, _tmp2m_high); vst1q_s32(tmp[3][m], _tmp3m_low); vst1q_s32(tmp[3][m] + 4, _tmp3m_high); output0_tm_0 += tiles * 48; output0_tm_1 += tiles * 48; output0_tm_2 += tiles * 48; output0_tm_3 += tiles * 48; output0_tm_4 += tiles * 48; output0_tm_5 += tiles * 48; } for (int m = 0; m < 4; m++) { int32x4_t _tmp00_low = vld1q_s32(tmp[m][0]); int32x4_t _tmp00_high = vld1q_s32(tmp[m][0] + 4); int32x4_t _tmp01_low = vld1q_s32(tmp[m][1]); int32x4_t _tmp01_high = vld1q_s32(tmp[m][1] + 4); int32x4_t _tmp02_low = vld1q_s32(tmp[m][2]); int32x4_t _tmp02_high = vld1q_s32(tmp[m][2] + 4); int32x4_t _tmp03_low = vld1q_s32(tmp[m][3]); int32x4_t _tmp03_high = vld1q_s32(tmp[m][3] + 4); int32x4_t _tmp04_low = vld1q_s32(tmp[m][4]); int32x4_t _tmp04_high = vld1q_s32(tmp[m][4] + 4); int32x4_t _tmp05_low = vld1q_s32(tmp[m][5]); int32x4_t _tmp05_high = vld1q_s32(tmp[m][5] + 4); int32x4_t _tmp02a_low = vaddq_s32(_tmp01_low, _tmp02_low); int32x4_t _tmp02a_high = vaddq_s32(_tmp01_high, _tmp02_high); int32x4_t _tmp13a_low = vsubq_s32(_tmp01_low, _tmp02_low); int32x4_t _tmp13a_high = vsubq_s32(_tmp01_high, _tmp02_high); int32x4_t _tmp02b_low = vaddq_s32(_tmp03_low, _tmp04_low); int32x4_t _tmp02b_high = vaddq_s32(_tmp03_high, _tmp04_high); int32x4_t _tmp13b_low = vsubq_s32(_tmp03_low, _tmp04_low); int32x4_t _tmp13b_high = vsubq_s32(_tmp03_high, _tmp04_high); int32x4_t _v2 = vdupq_n_s32(2); int32x4_t _v4 = vdupq_n_s32(4); int32x4_t _v8 = vdupq_n_s32(8); int32x4_t _out00_low = vaddq_s32(vaddq_s32(_tmp00_low, _tmp02a_low), _tmp02b_low); int32x4_t _out00_high = vaddq_s32(vaddq_s32(_tmp00_high, _tmp02a_high), _tmp02b_high); int32x4_t _out01_low = vmlaq_s32(_tmp13a_low, _tmp13b_low, _v2); int32x4_t _out01_high = vmlaq_s32(_tmp13a_high, _tmp13b_high, _v2); int32x4_t _out02_low = vmlaq_s32(_tmp02a_low, _tmp02b_low, _v4); int32x4_t _out02_high = vmlaq_s32(_tmp02a_high, _tmp02b_high, _v4); int32x4_t _out03_low = vmlaq_s32(vaddq_s32(_tmp05_low, _tmp13a_low), _tmp13b_low, _v8); int32x4_t _out03_high = vmlaq_s32(vaddq_s32(_tmp05_high, _tmp13a_high), _tmp13b_high, _v8); // TODO use integer trick for division by 576 float32x4_t _v576 = vdupq_n_f32(1.0 / 576); _out00_low = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out00_low), _v576)); _out00_high = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out00_high), _v576)); _out01_low = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out01_low), _v576)); _out01_high = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out01_high), _v576)); _out02_low = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out02_low), _v576)); _out02_high = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out02_high), _v576)); _out03_low = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out03_low), _v576)); _out03_high = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(_out03_high), _v576)); vst1q_s32(output0, _out00_low); vst1q_s32(output0 + 4, _out00_high); vst1q_s32(output0 + 8, _out01_low); vst1q_s32(output0 + 12, _out01_high); vst1q_s32(output0 + 16, _out02_low); vst1q_s32(output0 + 20, _out02_high); vst1q_s32(output0 + 24, _out03_low); vst1q_s32(output0 + 28, _out03_high); output0 += outw * 8; } } } } } // 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); }
fc_kernel_arm.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: haoluo@openailab.com */ #include <stdint.h> #include <stdlib.h> #include <math.h> #include <arm_neon.h> #include "fc_kernel_arm.h" #include <sys/time.h> #ifdef __aarch64__ void sgemv_1x8_a72(float* biases, float* input, float* kernel, long kernel_size, float* output); void sgemv_1x2_a72(float* biases, float* input, float* kernel, long kernel_size, float* output); #else void sgemv_1x8_a17(float* biases, float* input, float* kernel, int kernel_size, float* output); void sgemv_1x2_a17(float* biases, float* input, float* kernel, int kernel_size, float* output); #endif typedef void (*kernel_t)(float* biases, float* input, float* kernel, int kernel_size, float* output); static void sgemv1x8(float* input, float* output, float* kernel, float* bias, int kernel_size, int start_ch, int end_ch, int num_thread, kernel_t kernel_1x8) { #pragma omp parallel for num_threads(num_thread) for (int ch = start_ch; ch < end_ch; ch += 8) { float* cur_kernel = kernel + ch * kernel_size; float* cur_output = output + ch; float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; float* cur_bias = bias ? bias + ch : zeros; kernel_1x8(cur_bias, input, cur_kernel, kernel_size, cur_output); } } static void sgemv1x2(float* input, float* output, float* kernel, float* bias, int kernel_size, int start_ch, int end_ch, int num_thread, kernel_t kernel_1x2) { int ch = 0; int end_ch2 = end_ch & -2; #pragma omp parallel for num_threads(num_thread) for (ch = start_ch; ch < end_ch2; ch += 2) { float* cur_kernel = kernel + ch * kernel_size; float* cur_output = output + ch; float zeros[2] = {0.f, 0.f}; float* cur_bias = bias ? bias + ch : zeros; kernel_1x2(cur_bias, input, cur_kernel, kernel_size, cur_output); } if (end_ch & 0x1) { float* cur_kernel = kernel + end_ch2 * kernel_size; float* cur_output = output + end_ch2; float sum = bias ? bias[ch] : 0.f; for (int i = 0; i < kernel_size; i++) sum += input[i] * cur_kernel[i]; *cur_output = sum; } } static void interleave_kernel(const float* kernel, float* kernel_interleaved, int out_chan, int kernel_size) { int i, j, k; float* cur_kernel[8]; float* cur_kernel_interleaved; // interleave 8 kernel for (i = 0; i < (out_chan & -8); i += 8) { for (j = 0; j < 8; j++) cur_kernel[j] = ( float* )kernel + kernel_size * (i + j); cur_kernel_interleaved = ( float* )kernel_interleaved + kernel_size * i; for (k = 0; k < kernel_size; k++) for (j = 0; j < 8; j++) cur_kernel_interleaved[8 * k + j] = *(cur_kernel[j] + k); } // interleave 2 kernel for (; i < (out_chan & -2); i += 2) { for (j = 0; j < 2; j++) cur_kernel[j] = ( float* )kernel + kernel_size * (i + j); cur_kernel_interleaved = ( float* )kernel_interleaved + kernel_size * i; for (k = 0; k < kernel_size; k++) for (j = 0; j < 2; j++) cur_kernel_interleaved[2 * k + j] = *(cur_kernel[j] + k); } // copy last kernel if (out_chan & 0x1) { cur_kernel[0] = ( float* )kernel + kernel_size * i; cur_kernel_interleaved = ( float* )kernel_interleaved + kernel_size * i; for (k = 0; k < kernel_size; k++) cur_kernel_interleaved[k] = *(cur_kernel[0] + k); } } int fc_kernel_prerun(struct ir_tensor* input_tensor, struct ir_tensor* filter_tensor, struct ir_tensor* output_tensor, struct fc_priv_info* priv_info, struct fc_param* param) { int num_output = param->num_output; int kernel_size = filter_tensor->dims[1]; if (!priv_info->interleave_buffer) { int mem_size = sizeof(float) * num_output * kernel_size; void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } float* filter_data = ( float* )filter_tensor->data; interleave_kernel(filter_data, ( float* )priv_info->interleave_buffer, num_output, kernel_size); return 0; } int fc_kernel_postrun(struct fc_priv_info* priv_info) { if (priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; priv_info->interleave_buffer_size = 0; } if (priv_info->input_buffer != NULL) { sys_free(priv_info->input_buffer); priv_info->input_buffer = NULL; priv_info->input_buffer_size = 0; } return 0; } int fc_kernel_run(struct ir_tensor* input_tensor, struct ir_tensor* filter_tensor, struct ir_tensor* bias_tensor, struct ir_tensor* output_tensor, struct fc_priv_info* priv_info, struct fc_param* param, int num_thread, int cpu_affinity) { int out_num = param->num_output; int kernel_size = filter_tensor->dims[1]; float* input = input_tensor->data; float* output = output_tensor->data; float* biases = NULL; if (bias_tensor) biases = bias_tensor->data; float* weight = priv_info->interleave_buffer; int remain_out_start = (out_num >> 3) << 3; /* set cpu affinity sgemv kernel */ kernel_t kernel_1x8; kernel_t kernel_1x2; #ifdef __aarch64__ kernel_1x8 = (kernel_t)sgemv_1x8_a72; kernel_1x2 = (kernel_t)sgemv_1x2_a72; #else kernel_1x8 = (kernel_t)sgemv_1x8_a17; kernel_1x2 = (kernel_t)sgemv_1x2_a17; #endif /* process */ for (int i = 0; i < input_tensor->dims[0]; i++) { float* cur_input = input + i * kernel_size; float* cur_output = output + i * out_num; sgemv1x8(cur_input, cur_output, weight, biases, kernel_size, 0, remain_out_start, num_thread, kernel_1x8); if (out_num & 0x7) sgemv1x2(cur_input, cur_output, weight, biases, kernel_size, remain_out_start, out_num, num_thread, kernel_1x2); } return 0; }
DRB026-targetparallelfor-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Race condition due to anti-dependence within a loop offloaded to accelerators. Data race pair: a[i]@64:5 vs. a[i+1]@64:10 */ int main(int argc, char* argv[]) { int i; int len = 1000; int a[1000]; #pragma omp parallel for for (i=0; i<len; i++) a[i]= i; for (i=0;i< len -1 ;i++) a[i]=a[i+1]+1; for (i=0; i<len; i++) printf("%d\n",a[i]); return 0; }
test.c
#include <omp.h> #include <stdio.h> int main() { int Success = 0; #pragma omp target map(from:Success) { Success = 1; } if (Success) printf("### Success ### \n"); else printf("### Error ###\n"); return 0; }
GB_unaryop__abs_fp64_uint64.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_fp64_uint64 // op(A') function: GB_tran__abs_fp64_uint64 // C type: double // A type: uint64_t // cast: double cij = (double) aij // unaryop: cij = fabs (aij) #define GB_ATYPE \ uint64_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = fabs (x) ; // casting #define GB_CASTING(z, x) \ double z = (double) 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_FP64 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_fp64_uint64 ( double *restrict Cx, const uint64_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_fp64_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
copy.c
#include "copy.h" void copy_ref(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { b[i] = a[i]; } } void copy_mov(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { double t; //t = a[i]; asm ("mov %1, %0" : "=r" (t) : "m" (a[i])); //b[i] = t; asm ("mov %1, %0" : "=m" (b[i]) : "r" (t)); } } void copy_rep_movsq(size_t n, const double * RESTRICT a, double * RESTRICT b) { /* It might make more sense to do rep-movsq a page at a time * and make the alignment nicer... */ #ifdef _OPENMP #pragma omp parallel { int me = omp_get_thread_num(); int nt = omp_get_num_threads(); size_t chunk = 1+(n-1)/nt; size_t start = me*chunk; size_t end = (me+1)*chunk; if (end>n) end = n; size_t tn = (end>start) ? end-start : 0; //const double * RESTRICT ta = &( a[start] ); // double * RESTRICT tb = &( b[start] ); const double * RESTRICT ta = a+start; double * RESTRICT tb = b+start; //printf("zzz %d: chunk=%zu\n", me, chunk); fflush(stdout); //printf("zzz %d: start=%zu\n", me, start); fflush(stdout); //printf("zzz %d: xend=%zu\n", me, end); fflush(stdout); //printf("zzz %d: count=%zd\n", me, tn); fflush(stdout); #ifdef __INTEL_COMPILER asm("rep movsq" : "=D" (tb), "=S" (ta), "=c" (tn) : "0" (tb), "1" (ta), "2" (tn) : "memory"); #else tn *= sizeof(double); memcpy(tb,ta,tn); #endif } #else { #ifdef __INTEL_COMPILER asm("rep movsq" : "=D" (b), "=S" (a), "=c" (n) : "0" (b), "1" (a), "2" (n) : "memory"); #else tn *= sizeof(double); memcpy(b,a,n*sizeof(double)); #endif } #endif } #ifdef __SSE__ #if 0 /* BROKEN */ void copy_movntq(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { double t; //t = a[i]; asm ("mov %1, %0" : "=r" (t) : "m" (a[i])); //b[i] = t; // movntq does not work here... asm ("movntq %1, %0" : "=m" (b[i]) : "r" (t)); } asm ("sfence" ::: "memory"); } #endif #ifdef __INTEL_COMPILER void copy_movntq64(size_t n, const double * RESTRICT a, double * RESTRICT b) { //_mm_empty(); OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { __m64 t = _m_from_int64( *(__int64*)&(a[i]) ); _mm_stream_pi( (__m64*)&(b[i]), (__m64)t); } _mm_sfence(); } #endif /* ICC */ #endif /* SSE */ #ifdef __SSE2__ void copy_movnti(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { double t; //t = a[i]; asm ("mov %1, %0" : "=r" (t) : "m" (a[i])); //b[i] = t; asm ("movnti %1, %0" : "=m" (b[i]) : "r" (t)); } asm ("sfence" ::: "memory"); } #ifdef __INTEL_COMPILER void copy_movnti64(size_t n, const double * RESTRICT a, double * RESTRICT b) { //_mm_empty(); OMP_PARALLEL_FOR for (size_t i=0; i<n; i++) { __m64 t = _m_from_int64( *(__int64*)&(a[i]) ); _mm_stream_si64( (__int64*)&(b[i]), *(__int64*)&t); } _mm_sfence(); } #endif /* ICC */ void copy_movapd128(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=2) { __m128d t = _mm_load_pd( &(a[i]) ); _mm_store_pd( &(b[i]), t); } } void copy_movntpd128(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=2) { __m128d t = _mm_load_pd( &(a[i]) ); _mm_stream_pd( &(b[i]), t); } _mm_sfence(); } #endif /* SSE2 */ #ifdef __SSE4_1__ void copy_movntdqa128(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=2) { __m128i t = _mm_stream_load_si128( (__m128i*)&(a[i]) ); _mm_stream_si128 ( (__m128i*)&(b[i]), t); } _mm_sfence(); } #endif /* SSE4.1 */ #ifdef __AVX__ void copy_vmovapd256(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256d t = _mm256_load_pd( &(a[i]) ); _mm256_store_pd( &(b[i]), t); } } void copy_vmovntpd256(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256d t = _mm256_load_pd( &(a[i]) ); _mm256_stream_pd( &(b[i]), t); } _mm_sfence(); } #endif /* AVX */ #ifdef __AVX2__ void copy_vmovntdqa256(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256i t = _mm256_stream_load_si256( (__m256i*)&(a[i]) ); _mm256_stream_si256 ( (__m256i*)&(b[i]), t); } _mm_sfence(); } void copy_vgatherdpd128(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m128i vindex = _mm_set_epi32(-1,-1,1,0); // start from the right... OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=2) { __m128d t = _mm_i32gather_pd( &(a[i]), vindex, 8 /* scale */ ); _mm_storel_pd( &(b[i ]), t); _mm_storeh_pd( &(b[i+1]), t); } } void copy_vgatherqpd128(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m128i vindex = _mm_set_epi64x(1,0); // works OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=2) { __m128d t = _mm_i64gather_pd( &(a[i]), vindex, 8 /* scale */ ); _mm_storel_pd( &(b[i ]), t); _mm_storeh_pd( &(b[i+1]), t); } } void copy_vgatherdpd256(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m128i vindex = _mm_set_epi32(3,2,1,0); // start from the right... OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256d t = _mm256_i32gather_pd( &(a[i]), vindex, 8 /* scale */ ); __m128d l = _mm256_extractf128_pd(t,0); __m128d u = _mm256_extractf128_pd(t,1); _mm_storel_pd( &(b[i ]), l); _mm_storeh_pd( &(b[i+1]), l); _mm_storel_pd( &(b[i+2]), u); _mm_storeh_pd( &(b[i+3]), u); } } void copy_vgatherqpd256(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m256i vindex = _mm256_set_epi64x(3,2,1,0); // works OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256d t = _mm256_i64gather_pd( &(a[i]), vindex, 8 /* scale */ ); __m128d l = _mm256_extractf128_pd(t,0); __m128d u = _mm256_extractf128_pd(t,1); _mm_storel_pd( &(b[i ]), l); _mm_storeh_pd( &(b[i+1]), l); _mm_storel_pd( &(b[i+2]), u); _mm_storeh_pd( &(b[i+3]), u); } } void copy_mvgatherqpd256(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m256i vindex = _mm256_set_epi64x(3,2,1,0); // works // O in OQ means ordered, i.e. AND. unordered is OR. Q means quiet i.e. non-signaling. __m256d src = _mm256_cmp_pd(_mm256_setzero_pd(),_mm256_setzero_pd(),_CMP_EQ_OQ); // sets all bits to 1 __m256d mask = src; OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=4) { __m256d t = _mm256_mask_i64gather_pd( src, &(a[i]), vindex, mask, 8 /* scale */ ); __m128d l = _mm256_extractf128_pd(t,0); __m128d u = _mm256_extractf128_pd(t,1); _mm_storel_pd( &(b[i ]), l); _mm_storeh_pd( &(b[i+1]), l); _mm_storel_pd( &(b[i+2]), u); _mm_storeh_pd( &(b[i+3]), u); } } #endif /* AVX2 */ #ifdef __AVX512F__ void copy_vmovapd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_load_pd( &(a[i]) ); _mm512_store_pd( &(b[i]), t); } } void copy_vmovupd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_loadu_pd( &(a[i]) ); _mm512_storeu_pd( &(b[i]), t); } } void copy_mvmovapd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { __m512d src = {0}; __mmask8 k = 255; OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_mask_load_pd( src, k, &(a[i]) ); _mm512_mask_store_pd( &(b[i]), k, t); } } void copy_mvmovupd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { __m512d src = {0}; __mmask8 k = 255; OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_mask_loadu_pd( src, k, &(a[i]) ); _mm512_mask_storeu_pd( &(b[i]), k, t); } } void copy_vmovntpd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_load_pd( &(a[i]) ); _mm512_stream_pd( &(b[i]), t); } _mm_sfence(); } void copy_vmovntdqa512(size_t n, const double * RESTRICT a, double * RESTRICT b) { OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512i t = _mm512_stream_load_si512( (__m512i*)&(a[i]) ); _mm512_stream_si512 ( (__m512i*)&(b[i]), t); } _mm_sfence(); } void copy_vGSdpd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m256i vindex = _mm256_set_epi32(7,6,5,4,3,2,1,0); // start from the right... OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_i32gather_pd(vindex, &(a[i]), 8 /* scale */ ); _mm512_i32scatter_pd( &(b[i]), vindex, t, 8 /* scale */ ); } } void copy_mvGSdpd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { __m512d src = {0}; __mmask8 k = 255; const __m256i vindex = _mm256_set_epi32(7,6,5,4,3,2,1,0); // start from the right... OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_mask_i32gather_pd(src, k, vindex, &(a[i]), 8 /* scale */ ); _mm512_mask_i32scatter_pd( &(b[i]), k, vindex, t, 8 /* scale */ ); } } void copy_vGSqpd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { const __m512i vindex = _mm512_set_epi64(7,6,5,4,3,2,1,0); OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_i64gather_pd(vindex, &(a[i]), 8 /* scale */ ); _mm512_i64scatter_pd( &(b[i]), vindex, t, 8 /* scale */ ); } } void copy_mvGSqpd512(size_t n, const double * RESTRICT a, double * RESTRICT b) { __m512d src = {0}; __mmask8 k = 255; const __m512i vindex = _mm512_set_epi64(7,6,5,4,3,2,1,0); OMP_PARALLEL_FOR for (size_t i=0; i<n; i+=8) { __m512d t = _mm512_mask_i64gather_pd(src, k, vindex, &(a[i]), 8 /* scale */ ); _mm512_mask_i64scatter_pd( &(b[i]), k, vindex, t, 8 /* scale */ ); } } #endif /* AVX-512F */