source
stringlengths
3
92
c
stringlengths
26
2.25M
ParallelVertexFilter.h
/** * @file * This file is part of PUMGen * * For conditions of distribution and use, please see the copyright * notice in the file 'COPYING' at the root directory of this package * and the copyright notice at https://github.com/SeisSol/PUMGen * * @copyright 2017 Technical University of Munich * @author Sebastian Rettenberger <sebastian.rettenberger@tum.de> * * @remark This class is taken from XdmfWriter (https://github.com/TUM-I5/XdmfWriter) */ #ifndef PARALLEL_VERTEX_FILTER_H #define PARALLEL_VERTEX_FILTER_H #include <mpi.h> #include <algorithm> #include <cassert> #include <cstring> #include <cstdint> #include <vector> #include "utils/logger.h" /** * Filters duplicate vertices in parallel */ class ParallelVertexFilter { private: /** * Compares 3D-vertex indices according to the vertices */ class IndexedVertexComparator { private: const double *m_vertices; public: IndexedVertexComparator(const double *vertices) : m_vertices(vertices) { } bool operator() (unsigned int i, unsigned int j) { i *= 3; j *= 3; return (m_vertices[i] < m_vertices[j]) || (m_vertices[i] == m_vertices[j] && m_vertices[i+1] < m_vertices[j+1]) || (m_vertices[i] == m_vertices[j] && m_vertices[i+1] == m_vertices[j+1] && m_vertices[i+2] < m_vertices[j+2]); } }; private: /** The communicator we use */ MPI_Comm m_comm; /** Our rank */ int m_rank; /** #Processes */ int m_numProcs; /** Global id after filtering */ unsigned long *m_globalIds; /** Number of local vertices after filtering */ unsigned int m_numLocalVertices; /** Local vertices after filtering */ double *m_localVertices; public: ParallelVertexFilter(MPI_Comm comm = MPI_COMM_WORLD) : m_comm(comm), m_globalIds(0L), m_numLocalVertices(0), m_localVertices(0L) { MPI_Comm_rank(comm, &m_rank); MPI_Comm_size(comm, &m_numProcs); if (vertexType == MPI_DATATYPE_NULL) { MPI_Type_contiguous(3, MPI_DOUBLE, &vertexType); MPI_Type_commit(&vertexType); } } virtual ~ParallelVertexFilter() { delete [] m_globalIds; delete [] m_localVertices; } /** * @param vertices Vertices that should be filtered, must have the size <code>numVertices * 3</code> */ void filter(unsigned int numVertices, const double *vertices) { // Chop the last 4 bits to avoid numerical errors double *roundVertices = new double[numVertices*3]; removeRoundError(vertices, numVertices*3, roundVertices); // Create indices and sort them locally unsigned int *sortIndices = new unsigned int[numVertices]; createSortedIndices(roundVertices, numVertices, sortIndices); // Select BUCKETS_PER_RANK-1 splitter elements double localSplitters[BUCKETS_PER_RANK-1]; #if 0 // Use omp only if we create a larger amount of buckets #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif #endif for (int i = 0; i < BUCKETS_PER_RANK-1; i++) { unsigned long vrtxIndex = static_cast<unsigned long>(i) * static_cast<unsigned long>(numVertices) / static_cast<unsigned long>(BUCKETS_PER_RANK-1); assert(vrtxIndex < numVertices); localSplitters[i] = roundVertices[sortIndices[vrtxIndex]*3]; } // Collect all splitter elements on rank 0 double *allSplitters = 0L; if (m_rank == 0) allSplitters = new double[m_numProcs * (BUCKETS_PER_RANK-1)]; MPI_Gather(localSplitters, BUCKETS_PER_RANK-1, MPI_DOUBLE, allSplitters, BUCKETS_PER_RANK-1, MPI_DOUBLE, 0, m_comm); // Sort splitter elements if (m_rank == 0) std::sort(allSplitters, allSplitters + (m_numProcs * (BUCKETS_PER_RANK-1))); // Distribute splitter to all processes double *splitters = new double[m_numProcs-1]; if (m_rank == 0) { #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (int i = 0; i < m_numProcs-1; i++) { unsigned long spltIndex = (i+1) * (BUCKETS_PER_RANK-1); assert(spltIndex < static_cast<unsigned int>(m_numProcs * (BUCKETS_PER_RANK-1))); splitters[i] = allSplitters[spltIndex]; } } MPI_Bcast(splitters, m_numProcs-1, MPI_DOUBLE, 0, m_comm); delete [] allSplitters; // Determine the bucket for each vertex unsigned int *bucket = new unsigned int[numVertices]; #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < numVertices; i++) { double* ub = std::upper_bound(splitters, splitters+m_numProcs-1, roundVertices[i*3]); bucket[i] = ub-splitters; } delete [] roundVertices; delete [] splitters; // Determine the (local and total) bucket size int *bucketSize = new int[m_numProcs]; memset(bucketSize, 0, sizeof(int)*m_numProcs); for (unsigned int i = 0; i < numVertices; i++) bucketSize[bucket[i]]++; delete [] bucket; // Tell all processes what we are going to send them int *recvSize = new int[m_numProcs]; MPI_Alltoall(bucketSize, 1, MPI_INT, recvSize, 1, MPI_INT, m_comm); unsigned int numSortVertices = 0; #ifdef _OPENMP #pragma omp parallel for schedule(static) reduction(+: numSortVertices) #endif for (int i = 0; i < m_numProcs; i++) numSortVertices += recvSize[i]; // Create sorted send buffer double *sendVertices = new double[3 * numVertices]; #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < numVertices; i++) { memcpy(&sendVertices[i*3], &vertices[sortIndices[i]*3], sizeof(double)*3); } // Allocate buffer for the vertices and exchange them double *sortVertices = new double[3 * numSortVertices]; int *sDispls = new int[m_numProcs]; int *rDispls = new int[m_numProcs]; sDispls[0] = 0; rDispls[0] = 0; for (int i = 1; i < m_numProcs; i++) { sDispls[i] = sDispls[i-1] + bucketSize[i-1]; rDispls[i] = rDispls[i-1] + recvSize[i-1]; } MPI_Alltoallv(sendVertices, bucketSize, sDispls, vertexType, sortVertices, recvSize, rDispls, vertexType, m_comm); delete [] sendVertices; // Chop the last 4 bits to avoid numerical errors roundVertices = new double[numSortVertices*3]; removeRoundError(sortVertices, numSortVertices*3, roundVertices); // Create indices and sort them (such that the vertices are sorted) unsigned int *sortSortIndices = new unsigned int[numSortVertices]; createSortedIndices(roundVertices, numSortVertices, sortSortIndices); delete [] roundVertices; // Initialize the global ids we send back to the other processors unsigned long *gids = new unsigned long[numSortVertices]; if (numSortVertices > 0) { gids[sortSortIndices[0]] = 0; for (unsigned int i = 1; i < numSortVertices; i++) { if (equals(&sortVertices[sortSortIndices[i-1]*3], &sortVertices[sortSortIndices[i]*3])) gids[sortSortIndices[i]] = gids[sortSortIndices[i-1]]; else gids[sortSortIndices[i]] = gids[sortSortIndices[i-1]] + 1; } } // Create the local vertices list if (numSortVertices > 0) m_numLocalVertices = gids[sortSortIndices[numSortVertices-1]] + 1; else m_numLocalVertices = 0; delete [] m_localVertices; m_localVertices = new double[m_numLocalVertices * 3]; for (unsigned int i = 0; i < numSortVertices; i++) memcpy(&m_localVertices[gids[i]*3], &sortVertices[i*3], sizeof(double)*3); delete [] sortVertices; // Get the vertices offset unsigned int offset = m_numLocalVertices; MPI_Scan(MPI_IN_PLACE, &offset, 1, MPI_UNSIGNED, MPI_SUM, m_comm); offset -= m_numLocalVertices; // Add offset to the global ids #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < numSortVertices; i++) gids[i] += offset; // Send result back unsigned long *globalIds = new unsigned long[numVertices]; MPI_Alltoallv(gids, recvSize, rDispls, MPI_UNSIGNED_LONG, globalIds, bucketSize, sDispls, MPI_UNSIGNED_LONG, m_comm); delete [] bucketSize; delete [] recvSize; delete [] sDispls; delete [] rDispls; delete [] gids; // Assign the global ids to the correct vertices delete [] m_globalIds; m_globalIds = new unsigned long[numVertices]; #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < numVertices; i++) m_globalIds[sortIndices[i]] = globalIds[i]; delete [] sortIndices; delete [] globalIds; } /** * @return The list of the global identifiers after filtering */ const unsigned long* globalIds() const { return m_globalIds; } /** * @return Number of vertices this process is responsible for after filtering */ unsigned int numLocalVertices() const { return m_numLocalVertices; } /** * @return The list of vertices this process is responsible for after filtering */ const double* localVertices() const { return m_localVertices; } private: /** * Removes round errors of double values by setting the last 4 bits * (of the significand) to zero. * * @warning Only works if <code>value</code> ist not nan or infinity * @todo This should work for arbitrary precision */ static double removeRoundError(double value) { static const uint64_t mask = ~0xF; union FloatUnion { double f; uint64_t bits; }; FloatUnion result; result.f = value; result.bits &= mask; return result.f; } /** * Removes the round errors using {@link removeRoundError(double)} * * @param values The list of floating point values * @param count Number of values * @param[out] roundValues The list of rounded values * (the caller is responsible for allocating the memory) */ static void removeRoundError(const double *values, unsigned int count, double* roundValues) { #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < count; i++) roundValues[i] = removeRoundError(values[i]); } /** * Creates the list of sorted indices for the vertices. * The caller is responsible for allocating the memory. */ static void createSortedIndices(const double *vertices, unsigned int numVertices, unsigned int *sortedIndices) { #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (unsigned int i = 0; i < numVertices; i++) sortedIndices[i] = i; IndexedVertexComparator comparator(vertices); std::sort(sortedIndices, sortedIndices+numVertices, comparator); } /** * Compares to vertices for equality * Assumes that the rounding errors are removed. */ static bool equals(const double* vertexA, const double* vertexB) { return vertexA[0] == vertexB[0] && vertexA[1] == vertexB[1] && vertexA[2] == vertexB[2]; } /** MPI data type consisting of three doubles */ static MPI_Datatype vertexType; /** The total buckets we create is <code>BUCKETS_PER_RANK * numProcs</code> */ const static int BUCKETS_PER_RANK = 8; }; #endif // PARALLEL_VERTEX_FILTER_H
dart.h
#ifndef DART__DART_H_ #define DART__DART_H_ /** * \file dart.h * * \defgroup DartInterface DART - The DASH Runtime Interface * * Common C interface of the underlying communication back-end. * * * DASH/DART Terminology * ===================== * * DASH is a realization of the PGAS (partitioned global address space) * programming model. Below is an attempt to define some of the * terminology used in the project. DART is the name of the DASH * runtime. * * DASH Units, Teams, and Groups * ----------------------------- * * The individual participants in a DASH program are called units. One * can think of a DASH unit like an MPI process or UPC thread. The * generic term 'unit' is used to have the conceptual freedom to later * map a dash unit to a OS process, thread, or any other concept that * might fit (for example, in the context of GPUs and accelerators). * * Teams are ordered sets of units, identified by an integer ID. Each * unit has a non-negative, zero-based integer ID in a given team, which * always remains unchanged throughout the lifetime of the team. In * each application there exists a default team that contains all the * units that comprise the program denoted by DART_TEAM_ALL. * * Groups are also sets of units. The difference between groups and * teams is that groups have local meaning only, while teams are * coherent across several units. In effect, group related operations * are local, while operations to manipulate teams are collective and * will require communication and can thus be costly. * * Local/Global/Private/Shared * --------------------------- * * ### 1) Local and Global: ##### * The terms local and global are adjectives to describe the address * spaces in a DASH program. The local address space of a dash unit is * managed by the regular OS mechanisms (malloc, free), and data items * in the local address space are addressed by regular pointers. The * global address space in a DASH program is a virtual abstraction. Each * DASH unit contributes a part of it's memory to make up it's partition * of the global address space. Data items in the global memory are * addressed by global pointers provided by the DART runtime. * * ### 2) Private and Shared: ### * The adjectives private and shared describe the accessibility of data * items in DASH. A shared datum is one that can be accessed by more * than one unit (by means of the DART runtime). A private datum is one * that is not shared. * * ### 3) Partitions, Affinity, Ownership ### * ... to be written... * idea: we might use the term affinity to express hierarchical locality * * ### 4) Team-Alignment and Symmetricity: ### * Team-aligned and symmetric are terms describing memory allocations. * A memory allocation is symmetric (with respect to a team), if the * same amount of memory (in bytes) is allocated by each member of the * team. The memory allocation is said to be team-aligned (with respect * to a specific team), if the same segment-id can be used in a global * pointer to refer to any member's portion of the allocated memory. * (See section on global pointers below on segment IDs). * * A team-aligned and symmetric allocation has the nice property that * any member of the team is able to locally compute a global pointer to * any location in the allocated memory. * * * A note on thread safety: * ------------------------ * * In this release, most of DART's functionality cannot be called from within * multiple threads in parallel. This is especially true for * \ref DartGroupTeam "group and team management" and \ref DartGlobMem "global * memory management" functionality as well as \ref DartCommunication * "communication operations". * All exceptions from this rule have been marked accordingly in the * documentation. Improvements to thread-safety of DART are scheduled for the * next release. * * Note that this also affects global operations in DASH as they rely on DART * functionality. However, all operations on local data can be considered * thread-safe, e.g., `Container.local` or `Container.lbegin`. * The local access operators adhere to the C++ STL thread-safety * rules (see http://en.cppreference.com/w/cpp/container for details). * Thus, the following code is valid: * * \code{.cc} dash::Array<int> arr(...); #pragma omp parallel for // OK to parallelize since we're working on .local for( auto i=0; i<arr.local.size(); i++ ) [ arr.local[i]=foo(i); } * \endcode * * * Logging * ------- * * DART can be configured to produce log output with different log levels, a * feature that is mainly meant for debugging purposes. To enable general * logging output, the parameter \c -DENABLE_DART_LOGGING=ON should be * passed to CMake when building DART/DASH. Alternatively, the pre-compiler * macro \c DART_ENABLE_LOGGING can be defined manually. Please note that the * additional log output may cause notable performance overhead and should * not be enabled for production runs. * * The verbosity of the log output can be controlled at runtime through * the environment variable DART_LOG_LEVEL, whose value (if set) controls * the maximum log level. Possible values are: * - \c DART_LOGLEVEL_ERROR: Emit only messages on errors that are fatal * (similar to having logging disabled). * - \c DART_LOGLEVEL_WARN: Emit error messages and non-fatal warnings. * - \c DART_LOGLEVEL_INFO: In addition to errors and warnings, emit * additional information on the execution * of the DART library. * - \c DART_LOGLEVEL_DEBUG: Issue detailed debugging output on (mostly) * all DART methods executed. * - \c DART_LOGLEVEL_TRACE: In addition to the above, also output * information on the internal state of DART. * */ #ifdef __cplusplus extern "C" { #endif /* --- DART version and build date --- */ /** \cond DART_HIDDEN_SYMBOLS */ #define DART_VERSION_STR "3.2.0" #define DART_BUILD_STR (__DATE__ " " __TIME__) /** \endcond */ /* --- DART types and return values */ #include "dart_types.h" /* --- DART build- and environment configuration */ #include "dart_config.h" /* --- DART init/finalization */ #include "dart_initialization.h" /* --- DART group and team management --- */ #include "dart_team_group.h" /* --- DART global pointer and memory management --- */ #include "dart_globmem.h" /* --- DART collective communication --- --- DART onesided communication --- */ #include "dart_communication.h" /* --- DART synchronization --- */ #include "dart_synchronization.h" #ifdef __cplusplus } // extern "C" #endif #endif /* DART_DART_H_ */
gemm_symm_int8.h
// chgemm is pleased to support the open source community by supporting ncnn available. // // author:tpoisonooo (https://github.com/tpoisonooo/chgemm) implement symmetric int8 GEMM on aarch64. // // Copyright (C) 2019 tpoisonooo. 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. #pragma once #if __aarch64__ #define DECOMPOSE_K \ int ktmp = k; \ int k8 = k >> 3; \ int k8_even = (k8 % 2 == 0) ? 0 : 1; \ k -= (k8 << 3); \ int k4 = k >> 2; \ k -= (k4 << 2); \ int k2 = k >> 1; \ k -= (k2 << 1); \ int k1 = k; \ k = ktmp; #define DECOMPOSE_N \ int ntmp = n; \ int n4 = n >> 2; \ n -= (n4 << 2); \ int n2 = n >> 1; \ n -= (n2 << 1); \ int n1 = n; \ n = ntmp; #define PRINT_MATRIX 0 #if PRINT_MATRIX static void print_int8_matrix(char* name, const int8_t* a, int m, int k, int ldx) { fprintf(stdout, "------------- %s \n", name); for (int i = 0; i < m; ++i) { for (int j = 0; j < k; ++j) { fprintf(stdout, "%d \t", a[i * ldx + j]); } fprintf(stdout, "\n\n"); } } static void print_int32_matrix(char* name, const int32_t* a, int m, int k, int ldx) { fprintf(stdout, "------------- %s \n", name); for (int i = 0; i < m; ++i) { for (int j = 0; j < k; ++j) { fprintf(stdout, "%d \t", a[i * ldx + j]); } fprintf(stdout, "\n\n"); } } static void print_fp32_vec(char* name, const float* a, int len) { fprintf(stdout, "------------- %s \n", name); for (int i = 0; i < len; ++i) { fprintf(stdout, "%f \t", a[i]); } fprintf(stdout, "\n\n"); } #endif static void reorder_b(const int8_t* b, int8_t* sb, const int k, const int n, const int ldx) { #if PRINT_MATRIX print_int8_matrix("b", b, k, n, ldx); int8_t* origin = sb; #endif int i = 0; for (; i + 3 < n; i += 4) { const int8_t* p0 = b + i; const int8_t* p1 = b + 1 * ldx + i; const int8_t* p2 = b + 2 * ldx + i; const int8_t* p3 = b + 3 * ldx + i; const int8_t* p4 = b + 4 * ldx + i; const int8_t* p5 = b + 5 * ldx + i; const int8_t* p6 = b + 6 * ldx + i; const int8_t* p7 = b + 7 * ldx + i; int j = 0; for (; j + 7 < k; j += 8) { sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb[4] = p4[0]; sb[5] = p5[0]; sb[6] = p6[0]; sb[7] = p7[0]; sb[8] = p0[1]; sb[9] = p1[1]; sb[10] = p2[1]; sb[11] = p3[1]; sb[12] = p4[1]; sb[13] = p5[1]; sb[14] = p6[1]; sb[15] = p7[1]; sb[16] = p0[2]; sb[17] = p1[2]; sb[18] = p2[2]; sb[19] = p3[2]; sb[20] = p4[2]; sb[21] = p5[2]; sb[22] = p6[2]; sb[23] = p7[2]; sb[24] = p0[3]; sb[25] = p1[3]; sb[26] = p2[3]; sb[27] = p3[3]; sb[28] = p4[3]; sb[29] = p5[3]; sb[30] = p6[3]; sb[31] = p7[3]; sb += 32; p0 += 8 * ldx; p1 += 8 * ldx; p2 += 8 * ldx; p3 += 8 * ldx; p4 += 8 * ldx; p5 += 8 * ldx; p6 += 8 * ldx; p7 += 8 * ldx; } if (j + 3 < k) { j += 4; sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb[4] = p0[1]; sb[5] = p1[1]; sb[6] = p2[1]; sb[7] = p3[1]; sb[8] = p0[2]; sb[9] = p1[2]; sb[10] = p2[2]; sb[11] = p3[2]; sb[12] = p0[3]; sb[13] = p1[3]; sb[14] = p2[3]; sb[15] = p3[3]; sb += 16; p0 += 4 * ldx; p1 += 4 * ldx; p2 += 4 * ldx; p3 += 4 * ldx; } if (j + 1 < k) { j += 2; sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p0[1]; sb[3] = p1[1]; sb[4] = p0[2]; sb[5] = p1[2]; sb[6] = p0[3]; sb[7] = p1[3]; sb += 8; p0 += 2 * ldx; p1 += 2 * ldx; } if (j < k) { sb[0] = p0[0]; sb[1] = p0[1]; sb[2] = p0[2]; sb[3] = p0[3]; sb += 4; p0 += ldx; } } if (i + 1 < n) { const int8_t* p0 = b + i; const int8_t* p1 = b + 1 * ldx + i; const int8_t* p2 = b + 2 * ldx + i; const int8_t* p3 = b + 3 * ldx + i; const int8_t* p4 = b + 4 * ldx + i; const int8_t* p5 = b + 5 * ldx + i; const int8_t* p6 = b + 6 * ldx + i; const int8_t* p7 = b + 7 * ldx + i; int j = 0; for (; j + 7 < k; j += 8) { sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb[4] = p4[0]; sb[5] = p5[0]; sb[6] = p6[0]; sb[7] = p7[0]; sb[8] = p0[1]; sb[9] = p1[1]; sb[10] = p2[1]; sb[11] = p3[1]; sb[12] = p4[1]; sb[13] = p5[1]; sb[14] = p6[1]; sb[15] = p7[1]; sb += 16; p0 += 8 * ldx; p1 += 8 * ldx; p2 += 8 * ldx; p3 += 8 * ldx; p4 += 8 * ldx; p5 += 8 * ldx; p6 += 8 * ldx; p7 += 8 * ldx; } if (j + 3 < k) { j += 4; sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb[4] = p0[1]; sb[5] = p1[1]; sb[6] = p2[1]; sb[7] = p3[1]; sb += 8; p0 += 4 * ldx; p1 += 4 * ldx; p2 += 4 * ldx; p3 += 4 * ldx; } if (j + 1 < k) { j += 2; sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p0[1]; sb[3] = p1[1]; sb += 4; p0 += 2 * ldx; p1 += 2 * ldx; } if (j < k) { sb[0] = p0[0]; sb[1] = p0[1]; sb += 2; p0 += ldx; } i += 2; } if (i < n) { const int8_t* p0 = b + i; const int8_t* p1 = b + 1 * ldx + i; const int8_t* p2 = b + 2 * ldx + i; const int8_t* p3 = b + 3 * ldx + i; const int8_t* p4 = b + 4 * ldx + i; const int8_t* p5 = b + 5 * ldx + i; const int8_t* p6 = b + 6 * ldx + i; const int8_t* p7 = b + 7 * ldx + i; int j = 0; for (; j + 7 < k; j += 8) { sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb[4] = p4[0]; sb[5] = p5[0]; sb[6] = p6[0]; sb[7] = p7[0]; sb += 8; p0 += 8 * ldx; p1 += 8 * ldx; p2 += 8 * ldx; p3 += 8 * ldx; p4 += 8 * ldx; p5 += 8 * ldx; p6 += 8 * ldx; p7 += 8 * ldx; } if (j + 3 < k) { j += 4; sb[0] = p0[0]; sb[1] = p1[0]; sb[2] = p2[0]; sb[3] = p3[0]; sb += 4; p0 += 4 * ldx; p1 += 4 * ldx; p2 += 4 * ldx; p3 += 4 * ldx; } if (j + 1 < k) { j += 2; sb[0] = p0[0]; sb[1] = p1[0]; sb += 2; p0 += 2 * ldx; p1 += 2 * ldx; } if (j < k) { sb[0] = p0[0]; sb += 1; p0 += ldx; } } #if PRINT_MATRIX print_int8_matrix("sb", origin, k, n, n); #endif } static void reorder_a(int8_t* a, int8_t* sa, int m, const int k, const int ldx) { #if PRINT_MATRIX print_int8_matrix("a", a, m, k, ldx); int8_t* origin = sa; #endif int i = 0; for (; i + 3 < m; i += 4) { int8_t* p0 = a; int8_t* p1 = a + ldx; int8_t* p2 = a + 2 * ldx; int8_t* p3 = a + 3 * ldx; int j = 0; for (; j + 7 < k; j += 8) { asm volatile( "ld1 {v0.8b}, [%0], #8 \n" "ld1 {v1.8b}, [%1], #8 \n" "ld1 {v2.8b}, [%2], #8 \n" "ld1 {v3.8b}, [%3], #8 \n" "st1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%4], #32\n" : "=r"(p0), "=r"(p1), "=r"(p2), "=r"(p3), "=r"(sa) : "0"(p0), "1"(p1), "2"(p2), "3"(p3), "4"(sa) : "cc", "memory", "v0", "v1", "v2", "v3"); } if (j + 3 < k) { j += 4; asm volatile( "ld1 {v0.8b}, [%0] \n" "add %0, %0, #4 \n" "ld1 {v1.8b}, [%1] \n" "add %1, %1, #4 \n" "ld1 {v2.8b}, [%2] \n" "add %2, %2, #4 \n" "ld1 {v3.8b}, [%3] \n" "add %3, %3, #4 \n" "trn1 v0.2s, v0.2s, v1.2s \n" "st1 {v0.8b}, [%4], #8 \n" "trn1 v2.2s, v2.2s, v3.2s \n" "st1 {v2.8b}, [%4], #8 \n" : "=r"(p0), "=r"(p1), "=r"(p2), "=r"(p3), "=r"(sa) : "0"(p0), "1"(p1), "2"(p2), "3"(p3), "4"(sa) : "cc", "memory", "v0", "v1", "v2", "v3"); } if (j + 1 < k) { j += 2; asm volatile( "ld1 {v0.8b}, [%0] \n" "add %0, %0, #2 \n" "ld1 {v1.8b}, [%1] \n" "add %1, %1, #2 \n" "ld1 {v2.8b}, [%2] \n" "add %2, %2, #2 \n" "ld1 {v3.8b}, [%3] \n" "add %3, %3, #2 \n" "trn1 v0.4h, v0.4h, v1.4h \n" "trn1 v2.4h, v2.4h, v3.4h \n" "trn1 v0.2s, v0.2s, v2.2s \n" "st1 {v0.8b}, [%4], #8 \n" : "=r"(p0), "=r"(p1), "=r"(p2), "=r"(p3), "=r"(sa) : "0"(p0), "1"(p1), "2"(p2), "3"(p3), "4"(sa) : "cc", "memory", "v0", "v1", "v2", "v3"); } if (j < k) { *sa++ = *p0; *sa++ = *p1; *sa++ = *p2; *sa++ = *p3; } a += 4 * ldx; } if (i + 1 < m) { i += 2; int8_t* p0 = a; int8_t* p1 = a + ldx; int j = 0; for (; j + 7 < k; j += 8) { asm volatile( "ld1 {v0.8b}, [%0], #8 \n" "ld1 {v1.8b}, [%1], #8 \n" "st1 {v0.8b, v1.8b}, [%2], #16\n" : "=r"(p0), "=r"(p1), "=r"(sa) : "0"(p0), "1"(p1), "2"(sa) : "cc", "memory", "v0", "v1"); } if (j + 3 < k) { j += 4; asm volatile( "ld1 {v0.8b}, [%0] \n" "add %0, %0, #4 \n" "ld1 {v1.8b}, [%1] \n" "add %1, %1, #4 \n" "trn1 v0.2s, v0.2s, v1.2s \n" "st1 {v0.8b}, [%2], #8 \n" : "=r"(p0), "=r"(p1), "=r"(sa) : "0"(p0), "1"(p1), "2"(sa) : "cc", "memory", "v0", "v1"); } if (j + 1 < k) { j += 2; sa[0] = p0[0]; sa[1] = p0[1]; sa[2] = p1[0]; sa[3] = p1[1]; sa += 4; p0 += 2; p1 += 2; } if (j < k) { sa[0] = p0[0]; sa[1] = p1[0]; sa += 2; } a += 2 * ldx; } if (i < m) { memcpy(sa, a, sizeof(int8_t) * ldx); } #if PRINT_MATRIX print_int8_matrix("sa", origin, m, k, k); #endif } static void int8kernel_m1(void* dst, int8_t* sa, int8_t* sb, int, int k, int n, int, float* scales, float* bias) { void* pc = dst; int8_t* pa = sa; int8_t* pb = sb; DECOMPOSE_K DECOMPOSE_N if (n4 > 0) { asm volatile( "9: \n" " eor v8.16b, v8.16b, v8.16b \n" " eor v9.16b, v9.16b, v9.16b \n" " eor v10.16b, v10.16b, v10.16b\n" " eor v11.16b, v11.16b, v11.16b\n" " mov x8, %0 // PanelA\n" " cmp %w4, #0 \n" " beq 1f \n" " mov w19, %w4 \n" " cmp %w3, #0 \n" " beq 2f// loop number is even \n" " // start loopm1_kd8_nd4\n" " subs w19, w19, #1 \n" " ld1 {v4.8b, v5.8b, v6.8b, v7.8b}, [%1], #32 // load four lines of B\n" " ld1 {v2.8b}, [%0], #8 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " saddlp v8.4s, v0.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " saddlp v9.4s, v0.8h \n" " smull v0.8h, v6.8b, v2.8b \n" " saddlp v10.4s, v0.8h \n" " smull v0.8h, v7.8b, v2.8b \n" " saddlp v11.4s, v0.8h \n" " cmp w19, #0 \n" " beq 3f \n" " 2: \n" " ld1 {v4.8b, v5.8b, v6.8b, v7.8b}, [%1], #32 \n" " ld1 {v12.8b, v13.8b, v14.8b, v15.8b}, [%1], #32\n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v2.8b, v4.8b \n" " smlal v0.8h, v3.8b, v12.8b \n" " sadalp v8.4s, v0.8h \n" " smull v1.8h, v2.8b, v5.8b \n" " smlal v1.8h, v3.8b, v13.8b \n" " sadalp v9.4s, v1.8h \n" " smull v0.8h, v2.8b, v6.8b \n" " smlal v0.8h, v3.8b, v14.8b \n" " sadalp v10.4s, v0.8h \n" " smull v1.8h, v2.8b, v7.8b \n" " smlal v1.8h, v3.8b, v15.8b \n" " sadalp v11.4s, v1.8h \n" " subs w19, w19, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v10.4s, v10.4s, v11.4s\n" " addp v8.4s, v8.4s, v10.4s \n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w5, #0 \n" " beq 4f \n" " // start subkernel_m1n4k4 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load B4x4\n" " sxtl v4.8h, v4.8b \n" " sxtl v5.8h, v5.8b \n" " mov v6.d[0], v4.d[1] \n" " mov v7.d[0], v5.d[1] \n" " ld1 {v2.8b}, [%0] // load A1x4\n" " add %0, %0, #4 \n" " sxtl v2.8h, v2.8b \n" " smull v12.4s, v2.4h, v4.4h \n" " smull v13.4s, v2.4h, v6.4h \n" " smull v14.4s, v2.4h, v5.4h \n" " smull v15.4s, v2.4h, v7.4h \n" " addp v12.4s, v12.4s, v13.4s\n" " addp v14.4s, v14.4s, v15.4s\n" " addp v12.4s, v12.4s, v14.4s\n" " add v8.4s, v8.4s, v12.4s \n" " 4: \n" " cmp %w6, #0 \n" " beq 5f \n" " // start subkernel_m1n4k2\n" " ld1 {v4.8b}, [%0] // load A1x2 \n" " add %0, %0, #2 \n" " ld1 {v0.8b}, [%1], #8 // load B2x4 \n" " mov v4.h[1], v4.h[0] \n" " mov v4.s[1], v4.s[0] \n" " smull v0.8h, v0.8b, v4.8b \n" " sadalp v8.4s, v0.8h \n" " 5: \n" " cmp %w7, #0 \n" " beq 6f \n" " // start subkernel_m1n4k1 \n" " ld1 {v4.8b}, [%1] // load B1x4\n" " add %1, %1, #4 \n" " ld1 {v2.8b}, [%0] // load A1x1\n" " add %0, %0, #1 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0]\n" " 6: \n" " cmp %9, #0 \n" " beq 7f \n" " ldr w24, [%9] \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " // fp32 *= scale_tm \n" " mov v12.s[0], w24 \n" " fmul v8.4s, v8.4s, v12.s[0]\n" " cmp %10, #0 \n" " beq 8f \n" " // fp32 += bias_tm \n" " ldr w24, [%10] \n" " dup v15.4s, w24 \n" " fadd v8.4s, v8.4s, v15.4s \n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s\n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.s}[0], [%2]\n" " add %2, %2, #4 \n" " b 10f\n" " 7: \n" " st1 {v8.4s}, [%2], #16 \n" " 10: \n" " subs %w8, %w8, #1 \n" " mov %0, x8 \n" " bne 9b \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc), // %2 "=r"(k8_even), // %3 "=r"(k8), // %4 "=r"(k4), // %5 "=r"(k2), // %6 "=r"(k1), // %7 "=r"(n4), // %8 "=r"(scales), // %9 "=r"(bias) // %10 : "0"(pa), "1"(pb), "2"(pc), "3"(k8_even), "4"(k8), "5"(k4), "6"(k2), "7"(k1), "8"(n4), "9"(scales), "10"(bias) : "cc", "memory", "x8", "w19", "w24", "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"); } if (n2 > 0) { asm volatile( "9: \n" " eor v8.16b, v8.16b, v8.16b \n" " eor v9.16b, v9.16b, v9.16b \n" " eor v10.16b, v10.16b, v10.16b\n" " eor v11.16b, v11.16b, v11.16b\n" " mov x8, %0 // PanelA\n" " cmp %w4, #0 \n" " beq 1f // k <= 7\n" " mov w19, %w4\n" " cmp %w3, #0 \n" " beq 2f // loop number is even \n" " // start loopmd1_kd8_nd2 \n" " subs w19, w19, #1 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load two lines of B\n" " ld1 {v2.8b}, [%0], #8 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " saddlp v8.4s, v0.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " saddlp v9.4s, v0.8h \n" " cmp w19, #0 \n" " beq 3f \n" " 2: \n" " ld1 {v4.8b, v5.8b, v6.8b, v7.8b}, [%1], #32\n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v2.8b, v4.8b \n" " smlal v0.8h, v3.8b, v6.8b \n" " sadalp v8.4s, v0.8h \n" " smull v1.8h, v2.8b, v5.8b \n" " smlal v1.8h, v3.8b, v7.8b \n" " sadalp v9.4s, v1.8h \n" " subs w19, w19, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v8.4s, v8.4s, v8.4s \n" " // start process kd4 kd2 kd1 cases \n" " 1: \n" " cmp %w5, 0 \n" " beq 4f \n" " // start subkernel_m1n2k4 \n" " ld1 {v4.8b}, [%1], #8 // load B4x2\n" " sxtl v4.8h, v4.8b \n" " mov v6.d[0], v4.d[1] \n" " ld1 {v2.8b}, [%0] // load A1x4\n" " add %0, %0, #4 \n" " sxtl v2.8h, v2.8b \n" " smull v9.4s, v2.4h, v4.4h \n" " smull v10.4s, v2.4h, v6.4h \n" " addp v9.4s, v9.4s, v10.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " 4: \n" " cmp %w6, 0 \n" " beq 5f \n" " // start subkernel_m1n2k2 \n" " ld1 {v4.8b}, [%0] // load A1x2\n" " add %0, %0, #2 \n" " ld1 {v0.8b}, [%1] // load B2x2\n" " add %1, %1, #4 \n" " mov v4.h[1], v4.h[0] \n" " smull v0.8h, v4.8b, v0.8b \n" " saddlp v0.4s, v0.8h \n" " add v8.4s, v8.4s, v0.4s \n" " 5: \n" " cmp %w7, 0 \n" " beq 6f \n" " // start subkernel_m1n2k1 \n" " ld1 {v4.8b}, [%1] // load B1x2\n" " add %1, %1, #2 \n" " ld1 {v2.8b}, [%0] // load A1x1\n" " add %0, %0, #2 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0]\n" " 6: \n" " cmp %9, #0 \n" " beq 7f \n" " // v12: s0 s1 \n" " ldr w24, [%9] \n" " mov v12.s[0], w24 \n" " mov v12.s[1], v12.s[0] \n" " // int32 => fp32 \n" " scvtf v8.2s, v8.2s \n" " // fp32 *= scale_tm \n" " fmul v8.2s, v8.2s, v12.2s \n" " cmp %10, #0 \n" " beq 8f \n" " // fp32 += bias_tm \n" " ldr w24, [%10] \n" " mov v12.s[0], w24 \n" " mov v12.s[1], v12.s[0] \n" " fadd v8.2s, v8.2s, v12.2s \n" " 8:\n" " // fp32 -> int32 \n" " fcvtas v8.2s, v8.2s\n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.h}[0], [%2]\n" " add %2, %2, #2 \n" " b 10f\n" " 7: \n" " st1 {v8.2s}, [%2], #8 \n" " 10: \n" " mov %0, x8 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc), // %2 "=r"(k8_even), // %3 "=r"(k8), // %4 "=r"(k4), // %5 "=r"(k2), // %6 "=r"(k1), // %7 "=r"(n4), // %8 "=r"(scales), // %9 "=r"(bias) // %10 : "0"(pa), "1"(pb), "2"(pc), "3"(k8_even), "4"(k8), "5"(k4), "6"(k2), "7"(k1), "8"(n4), "9"(scales), "10"(bias) : "cc", "memory", "x8", "w19", "w24", "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"); } if (n1 > 0) { asm volatile( "9: \n" " eor v8.16b, v8.16b, v8.16b \n" " eor v9.16b, v9.16b, v9.16b \n" " eor v10.16b, v10.16b, v10.16b\n" " eor v11.16b, v11.16b, v11.16b\n" " cmp %w4, #0 \n" " beq 1f // k <= 7 \n" " mov w19, %w4\n" " cmp %w3, #0 \n" " beq 2f // loop number is even \n" " // start loopkd8_nd1 \n" " subs w19, w19, #1 \n" " ld1 {v4.8b}, [%1], #8 // load B line \n" " ld1 {v2.8b}, [%0], #8 // load A line \n" " smull v0.8h, v4.8b, v2.8b \n" " saddlp v8.4s, v0.8h \n" " cmp w19, #0 \n" " beq 3f \n" " 2: \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v24.8b, v25.8b}, [%0], #16\n" " smull v0.8h, v24.8b, v4.8b \n" " smlal v0.8h, v25.8b, v5.8b \n" " sadalp v8.4s, v0.8h \n" " subs w19, w19, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v8.4s \n" " addp v8.4s, v8.4s, v8.4s \n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w5, 0 \n" " beq 4f \n" " // start subkernel_m1n1k4 \n" " ld1 {v4.8b}, [%1] // load B4x1\n" " add %1, %1, #4 \n" " sxtl v4.8h, v4.8b // extend B4x1 to v4\n" " ld1 {v2.8b}, [%0] // load A1x4\n" " add %0, %0, #4 \n" " sxtl v2.8h, v2.8b \n" " smull v9.4s, v2.4h, v4.4h \n" " addp v9.4s, v9.4s, v9.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " 4: \n" " cmp %w6, 0 \n" " beq 5f \n" " // start subkernel_m1n1k2 \n" " ld1 {v4.8b}, [%0] // load A1x2\n" " add %0, %0, #2 \n" " ld1 {v0.8b}, [%1] // load B2x1\n" " add %1, %1, #2 \n" " smull v0.8h, v0.8b, v4.8b \n" " saddlp v0.4s, v0.8h \n" " add v8.4s, v8.4s, v0.4s \n" " 5: \n" " cmp %w7, 0 \n" " beq 6f \n" " // start subkernel_m1n1k1 \n" " ld1 {v0.8b}, [%1] // load B1x1 \n" " add %1, %1, #1 \n" " ld1 {v1.8b}, [%0] // load A1x1 \n" " add %0, %0, #1 \n" " sxtl v1.8h, v1.8b \n" " sxtl v0.8h, v0.8b \n" " smull v0.4s, v1.4h, v0.h[0] \n" " add v8.4s, v8.4s, v0.4s \n" " 6: \n" " cmp %9, #0 \n" " beq 7f \n" " // int32 => fp32 \n" " scvtf v8.2s, v8.2s \n" " // fp32 *= scale_tm\n" " ldr w24, [%9] \n" " mov v12.s[0], w24 \n" " fmul v8.2s, v8.2s, v12.2s \n" " cmp %10, #0 \n" " beq 8f \n" " // fp32 += bias_tm \n" " ldr w24, [%10] \n" " mov v12.s[0], w24 \n" " fadd v8.2s, v8.2s, v12.2s \n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.2s, v8.2s\n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.b}[0], [%2]\n" " b 10f \n" " 7: \n" " st1 {v8.s}[0], [%2] \n" " 10: \n" " mov x0, #0 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc), // %2 "=r"(k8_even), // %3 "=r"(k8), // %4 "=r"(k4), // %5 "=r"(k2), // %6 "=r"(k1), // %7 "=r"(n4), // %8 "=r"(scales), // %9 "=r"(bias) // %10 : "0"(pa), "1"(pb), "2"(pc), "3"(k8_even), "4"(k8), "5"(k4), "6"(k2), "7"(k1), "8"(n4), "9"(scales), "10"(bias) : "cc", "memory", "x0", "x8", "w19", "w24", "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"); } } static void int8kernel_m2(void* dst, int8_t* sa, int8_t* sb, int, int k, int n, int ldc, float* scales, float* bias) { void *pc0, *pc1; if (scales == 0) { pc0 = (int32_t*)dst; pc1 = ((int32_t*)pc0) + ldc; } else { pc0 = dst; pc1 = ((int8_t*)pc0) + ldc; } int8_t* pa = sa; int8_t* pb = sb; DECOMPOSE_K DECOMPOSE_N if (n4 > 0) { asm volatile( "9: \n" " eor v8.16b, v8.16b, v8.16b \n" " eor v9.16b, v9.16b, v9.16b \n" " eor v10.16b, v10.16b, v10.16b \n" " eor v11.16b, v11.16b, v11.16b \n" " eor v12.16b, v12.16b, v12.16b \n" " eor v13.16b, v13.16b, v13.16b \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" " mov x8, %0 // PanelA \n" " cmp %w5, #0 \n" " beq 1f \n" " mov w17, %w5 \n" " cmp %w4, #0 \n" " beq 2f // loop number is even \n" " // start loopm2_kd8_nd4\n" " subs w17, w17, #1 \n" " ld1 {v4.8b, v5.8b, v6.8b, v7.8b}, [%1], #32 // load four lines of B\n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load two lines of PanelA \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v9.4s, v0.8h \n" " saddlp v13.4s, v1.8h \n" " smull v0.8h, v6.8b, v2.8b \n" " smull v1.8h, v6.8b, v3.8b \n" " saddlp v10.4s, v0.8h \n" " saddlp v14.4s, v1.8h \n" " smull v0.8h, v7.8b, v2.8b \n" " smull v1.8h, v7.8b, v3.8b \n" " saddlp v11.4s, v0.8h \n" " saddlp v15.4s, v1.8h \n" " cmp w17, #0 \n" " beq 3f \n" " 2: \n" " add x12, %1, #32 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [x12], #16 \n" " ld1 {v24.8b, v25.8b}, [%0], #16\n" " smlal v0.8h, v6.8b, v24.8b \n" " smlal v1.8h, v7.8b, v24.8b \n" " sadalp v8.4s, v0.8h\n" " sadalp v9.4s, v1.8h\n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v12.4s, v0.8h\n" " sadalp v13.4s, v1.8h\n" " // start v10v11, v14v15, v18v19, v22v23, error here!\n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [x12], #16 \n" " smlal v0.8h, v6.8b, v24.8b \n" " smlal v1.8h, v7.8b, v24.8b \n" " sadalp v10.4s, v0.8h \n" " sadalp v11.4s, v1.8h \n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v14.4s, v0.8h \n" " sadalp v15.4s, v1.8h \n" " add %1, %1, #32 \n" " subs w17, w17, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v10.4s, v10.4s, v11.4s\n" " addp v12.4s, v12.4s, v13.4s\n" " addp v14.4s, v14.4s, v15.4s\n" " addp v8.4s, v8.4s, v10.4s \n" " addp v9.4s, v12.4s, v14.4s \n" " // start process kd4 kd2 kd1 cases \n" " 1: \n" " cmp %w6, #0 \n" " beq 4f \n" " // start subkernel_m2n4k4 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load B4x4\n" " sxtl v4.8h, v4.8b \n" " sxtl v5.8h, v5.8b \n" " mov v6.d[0], v4.d[1] \n" " mov v7.d[0], v5.d[1] \n" " ld1 {v2.8b}, [%0], #8 // load A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v12.4s, v2.4h, v4.4h \n" " smull v13.4s, v2.4h, v6.4h \n" " smull v14.4s, v2.4h, v5.4h \n" " smull v15.4s, v2.4h, v7.4h \n" " addp v12.4s, v12.4s, v13.4s\n" " addp v14.4s, v14.4s, v15.4s\n" " addp v12.4s, v12.4s, v14.4s\n" " add v8.4s, v8.4s, v12.4s \n" " smull v16.4s, v3.4h, v4.4h \n" " smull v17.4s, v3.4h, v6.4h \n" " smull v18.4s, v3.4h, v5.4h \n" " smull v19.4s, v3.4h, v7.4h \n" " addp v16.4s, v16.4s, v17.4s\n" " addp v18.4s, v18.4s, v19.4s\n" " addp v16.4s, v16.4s, v18.4s\n" " add v9.4s, v9.4s, v16.4s \n" " 4: \n" " cmp %w7, #0 \n" " beq 5f \n" " // start subkernel_m2n4k2 \n" " ld1 {v4.8b}, [%0] // load A2x2 \n" " add %0, %0, #4 \n" " ld1 {v0.8b}, [%1], #8 // load B2x4 \n" " // 00 11 22 33 \n" " rev32 v1.4h, v0.4h // 11 00 33 22 \n" " rev64 v2.2s, v0.2s // 22 33 00 11 \n" " rev64 v3.4h, v0.4h // 33 22 11 00 \n" " smull v12.8h, v4.8b, v0.8b \n" " smull v13.8h, v4.8b, v1.8b \n" " smull v14.8h, v4.8b, v2.8b \n" " smull v15.8h, v4.8b, v3.8b \n" " saddlp v12.4s, v12.8h \n" " saddlp v13.4s, v13.8h \n" " saddlp v14.4s, v14.8h \n" " saddlp v15.4s, v15.8h \n" " mov v16.s[0], v12.s[0] \n" " mov v16.s[1], v13.s[0] \n" " mov v16.s[2], v14.s[0] \n" " mov v16.s[3], v15.s[0] \n" " mov v17.s[0], v13.s[1] \n" " mov v17.s[1], v12.s[1] \n" " mov v17.s[2], v15.s[1] \n" " mov v17.s[3], v14.s[1] \n" " add v8.4s, v8.4s, v16.4s \n" " add v9.4s, v9.4s, v17.4s \n" " 5: \n" " cmp %w8, #0 \n" " beq 6f \n" " // start subkernel_m2n4k1 \n" " ld1 {v4.8b}, [%1] // load B1x4\n" " add %1, %1, #4 \n" " ld1 {v2.8b}, [%0] // load A2x1\n" " add %0, %0, #2 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0]\n" " smlal v9.4s, v4.4h, v2.h[1]\n" " 6: \n" " cmp %10, #0 \n" " beq 7f \n" " ld1 {v12.2s}, [%10] \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " scvtf v9.4s, v9.4s \n" " // fp32 *= scale_tm \n" " fmul v8.4s, v8.4s, v12.s[0]\n" " fmul v9.4s, v9.4s, v12.s[1]\n" " cmp %11, #0 \n" " beq 8f \n" " // fp32 += scales_tm \n" " ld1 {v14.2s}, [%11] \n" " dup v15.4s, v14.s[0] \n" " fadd v8.4s, v8.4s, v15.4s \n" " dup v15.4s, v14.s[1] \n" " fadd v9.4s, v9.4s, v15.4s \n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s\n" " fcvtas v9.4s, v9.4s\n" " // int32 -> int16 \n" " sqxtn v6.4h, v8.4s \n" " sqxtn2 v6.8h, v9.4s\n" " // int16 -> int8 \n" " sqxtn v8.8b, v6.8h \n" " // save \n" " st1 {v8.s}[0], [%2] \n" " add %2, %2, #4 \n" " st1 {v8.s}[1], [%3] \n" " add %3, %3, #4 \n" " b 10f \n" " 7: \n" " st1 {v8.4s}, [%2], #16 \n" " st1 {v9.4s}, [%3], #16 \n" " 10: \n" " subs %w9, %w9, #1 \n" " mov %0, x8 \n" " bne 9b \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(k8_even), // %4 "=r"(k8), // %5 "=r"(k4), // %6 "=r"(k2), // %7 "=r"(k1), // %8 "=r"(n4), // %9 "=r"(scales), // %10 "=r"(bias) // %11 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(k8_even), "5"(k8), "6"(k4), "7"(k2), "8"(k1), "9"(n4), "10"(scales), "11"(bias) : "cc", "memory", "x8", "w17", "x12", "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"); } if (n2 > 0) { asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \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" "9: \n" " mov x8, %0 // PanelA \n" " cmp %w5, #0 \n" " beq 1f \n" " mov w17, %w5 \n" " cmp %w4, #0 \n" " beq 2f // loop number is even \n" " // start loopmd2_kd8_nd2 \n" " subs w17, w17, #1 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load two lines of B\n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v9.4s, v0.8h \n" " saddlp v13.4s, v1.8h \n" " cmp w17, #0 \n" " beq 3f \n" " 2: \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [%1], #16 \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v24.8b, v25.8b}, [%0], #16\n" " smlal v0.8h, v6.8b, v24.8b \n" " smlal v1.8h, v7.8b, v24.8b \n" " sadalp v8.4s, v0.8h\n" " sadalp v9.4s, v1.8h\n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v12.4s, v0.8h \n" " sadalp v13.4s, v1.8h \n" " subs w17, w17, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v12.4s, v12.4s, v13.4s\n" " addp v8.4s, v8.4s, v8.4s \n" " addp v12.4s, v12.4s, v12.4s\n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w6, #0 \n" " beq 4f \n" " // start subkernel_m2n2k4 \n" " ld1 {v4.8b}, [%1], #8 // load B4x2\n" " sxtl v4.8h, v4.8b \n" " mov v6.d[0], v4.d[1] \n" " ld1 {v2.8b}, [%0], #8 // load first A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v9.4s, v2.4h, v4.4h \n" " smull v10.4s, v2.4h, v6.4h \n" " addp v9.4s, v9.4s, v10.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " smull v13.4s, v3.4h, v4.4h \n" " smull v14.4s, v3.4h, v6.4h \n" " addp v13.4s, v13.4s, v14.4s\n" " addp v13.4s, v13.4s, v13.4s\n" " add v12.4s, v12.4s, v13.4s \n" " 4: \n" " cmp %w7, 0 \n" " beq 5f \n" " // start subkernel_m2n2k2 \n" " ld1 {v4.8b}, [%0] // load A2x2\n" " add %0, %0, #4 \n" " ld1 {v0.8b}, [%1] // load B2x2\n" " add %1, %1, #4 \n" " // 00 11\n" " rev32 v1.4h, v0.4h // 11 00\n" " smull v21.8h, v4.8b, v0.8b \n" " smull v22.8h, v4.8b, v1.8b \n" " saddlp v21.4s, v21.8h \n" " saddlp v22.4s, v22.8h \n" " mov v9.s[0], v21.s[0] \n" " mov v9.s[1], v22.s[0] \n" " add v8.4s, v8.4s, v9.4s \n" " mov v13.s[0], v22.s[1] \n" " mov v13.s[1], v21.s[1] \n" " add v12.4s, v12.4s, v13.4s \n" " 5: \n" " cmp %w8, #0 \n" " beq 6f \n" " // start subkernel_m2n2k1 \n" " ld1 {v4.8b}, [%1] // load B1x2\n" " add %1, %1, #2 \n" " ld1 {v2.8b}, [%0] // load A4x1\n" " add %0, %0, #2 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0]\n" " smlal v12.4s, v4.4h, v2.h[1] \n" " 6: \n" " cmp %9, #0 \n" " beq 7f \n" " mov v8.d[1], v12.d[0] \n" " // v12: 0 1 \n" " ld1 {v12.2s}, [%9] \n" " zip1 v12.4s, v12.4s, v12.4s\n" " // v12: 0 0 1 1 \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " // fp32 *= scale_tm \n" " fmul v8.4s, v8.4s, v12.4s \n" " cmp %10, #0 \n" " beq 8f \n" " // fp32 += bias_tm \n" " ld1 {v12.2s}, [%10] \n" " zip1 v12.4s, v12.4s, v12.4s\n" " fadd v8.4s, v8.4s, v12.4s \n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s \n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.h}[0], [%2] \n" " add %2, %2, #2 \n" " st1 {v8.h}[1], [%3] \n" " add %3, %3, #2 \n" " b 10f \n" " 7:" " st1 {v8.2s}, [%2], #8 \n" " st1 {v12.2s}, [%3], #8 \n" " 10: \n" " mov %0, x8 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(k8_even), // %4 "=r"(k8), // %5 "=r"(k4), // %6 "=r"(k2), // %7 "=r"(k1), // %8 "=r"(scales), // %9 "=r"(bias) // %10 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(k8_even), "5"(k8), "6"(k4), "7"(k2), "8"(k1), "9"(scales), "10"(bias) : "cc", "memory", "x8", "x12", "w17", "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"); } if (n1 > 0) { asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \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" "9: \n" " cmp %w5, #0 \n" " beq 1f // k <=7\n" " mov w17, %w5\n" " cmp %w4, #0 \n" " beq 2f // loop number is even \n" " // start loopkd8_nd1 \n" " subs w17, w17, #1 \n" " ld1 {v4.8b}, [%1], #8 // load four lines of B\n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " cmp w17, #0 \n" " beq 3f \n" " 2: \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v24.8b, v25.8b, v26.8b, v27.8b}, [%0], #32\n" " smull v0.8h, v24.8b, v4.8b \n" " smlal v0.8h, v26.8b, v5.8b \n" " sadalp v8.4s, v0.8h \n" " smull v1.8h, v25.8b, v4.8b \n" " smlal v1.8h, v27.8b, v5.8b \n" " sadalp v12.4s, v1.8h \n" " subs w17, w17, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v8.4s \n" " addp v8.4s, v8.4s, v8.4s \n" " addp v12.4s, v12.4s, v12.4s\n" " addp v12.4s, v12.4s, v12.4s\n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w6, #0 \n" " beq 4f \n" " // start subkernel_m2n1k2 \n" " ld1 {v4.8b}, [%1] // load B4x1\n" " add %1, %1, #4 \n" " sxtl v4.8h, v4.8b // extend B4x1 to v4\n" " ld1 {v2.8b}, [%0], #8 // load A2x4 \n" " sxtl v2.8h, v2.8b \n" " mov v5.d[0], v2.d[1] \n" " smull v9.4s, v2.4h, v4.4h \n" " addp v9.4s, v9.4s, v9.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " smull v13.4s, v5.4h, v4.4h \n" " addp v13.4s, v13.4s, v13.4s\n" " addp v13.4s, v13.4s, v13.4s\n" " add v12.4s, v12.4s, v13.4s \n" " 4: \n" " cmp %w7, 0 \n" " beq 5f \n" " // start subkernel_m2n1k2 \n" " ld1 {v4.8b}, [%0] // load A2x2\n" " add %0, %0, #4 \n" " ld1 {v0.8b}, [%1] // load B2x1\n" " add %1, %1, #2 \n" " mov v0.h[1], v0.h[0] \n" " smull v0.8h, v0.8b, v4.8b \n" " saddlp v0.4s, v0.8h \n" " mov v9.s[0], v0.s[0] \n" " add v8.4s, v8.4s, v9.4s \n" " mov v13.s[0], v0.s[1] \n" " add v12.4s, v12.4s, v13.4s \n" " 5: \n" " cmp %w8, 0 \n" " beq 6f \n" " // start subkernel_m2n1k1 \n" " ld1 {v0.8b}, [%1] // load B1x1\n" " add %1, %1, #1 \n" " ld1 {v1.8b}, [%0] // load A2x1\n" " add %0, %0, #2 \n" " sxtl v1.8h, v1.8b \n" " sxtl v0.8h, v0.8b \n" " smull v0.4s, v1.4h, v0.h[0]\n" " mov v1.s[0], v0.s[1] \n" " add v8.4s, v8.4s, v0.4s \n" " add v12.4s, v12.4s, v1.4s \n" " 6: \n" " cmp %w9, #0 \n" " beq 7f \n" " mov v8.s[1], v12.s[0] \n" " // v12: s0 s1 \n" " ld1 {v12.2s}, [%9] \n" " // int32 => fp32 \n" " scvtf v8.2s, v8.2s \n" " // fp32 *= scale_tm \n" " fmul v8.2s, v8.2s, v12.2s \n" " cmp %10, #0 \n" " beq 8f \n" " // fp32 += bias_tm \n" " ld1 {v12.2s}, [%10] \n" " fadd v8.2s, v8.2s, v12.2s \n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.2s, v8.2s \n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.b}[0], [%2] \n" " st1 {v8.b}[1], [%3] \n" " b 10f \n" " 7: \n" " st1 {v8.s}[0], [%2] \n" " st1 {v12.s}[0], [%3] \n" " 10: \n" " mov x0, #0 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(k8_even), // %4 "=r"(k8), // %5 "=r"(k4), // %6 "=r"(k2), // %7 "=r"(k1), // %8 "=r"(scales), // %9 "=r"(bias) // %10 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(k8_even), "5"(k8), "6"(k4), "7"(k2), "8"(k1), "9"(scales), "10"(bias) : "cc", "memory", "x0", "x8", "w17", "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"); } } static void int8kernel_m4(void* dst, int8_t* sa, int8_t* sb, int, int k, int n, int ldc, float* scales, float* bias) { void *pc0, *pc1, *pc2, *pc3; if (scales == 0) { pc0 = (int32_t*)dst; pc1 = ((int32_t*)pc0) + ldc; pc2 = ((int32_t*)pc1) + ldc; pc3 = ((int32_t*)pc2) + ldc; } else { pc0 = dst; pc1 = ((int8_t*)pc0) + ldc; pc2 = ((int8_t*)pc1) + ldc; pc3 = ((int8_t*)pc2) + ldc; } int8_t* pa = sa; int8_t* pb = sb; DECOMPOSE_K DECOMPOSE_N if (n4 > 0) { asm volatile( "8: \n" " eor v8.8b, v8.8b, v8.8b \n" " eor v9.8b, v9.8b, v9.8b \n" " eor v10.8b, v10.8b, v10.8b \n" " eor v11.8b, v11.8b, v11.8b \n" " eor v12.8b, v12.8b, v12.8b \n" " eor v13.8b, v13.8b, v13.8b \n" " eor v14.8b, v14.8b, v14.8b \n" " eor v15.8b, v15.8b, v15.8b \n" " eor v16.8b, v16.8b, v16.8b \n" " eor v17.8b, v17.8b, v17.8b \n" " eor v18.8b, v18.8b, v18.8b \n" " eor v19.8b, v19.8b, v19.8b \n" " eor v20.8b, v20.8b, v20.8b \n" " eor v21.8b, v21.8b, v21.8b \n" " eor v22.8b, v22.8b, v22.8b \n" " eor v23.8b, v23.8b, v23.8b \n" " mov x8, %0 \n" " cmp %w7, #0 \n" " beq 1f \n" " mov w20, %w7 \n" " cmp %w6, #0 \n" " beq 2f \n" " subs w20, w20, #1 \n" " ld1 {v4.8b, v5.8b, v6.8b, v7.8b}, [%1], #32 \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v9.4s, v0.8h \n" " saddlp v13.4s, v1.8h \n" " smull v0.8h, v6.8b, v2.8b \n" " smull v1.8h, v6.8b, v3.8b \n" " saddlp v10.4s, v0.8h \n" " saddlp v14.4s, v1.8h \n" " smull v0.8h, v7.8b, v2.8b \n" " smull v1.8h, v7.8b, v3.8b \n" " saddlp v11.4s, v0.8h \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " saddlp v15.4s, v1.8h \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v16.4s, v0.8h \n" " saddlp v20.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v17.4s, v0.8h \n" " saddlp v21.4s, v1.8h \n" " smull v0.8h, v6.8b, v2.8b \n" " smull v1.8h, v6.8b, v3.8b \n" " saddlp v18.4s, v0.8h \n" " saddlp v22.4s, v1.8h \n" " smull v0.8h, v7.8b, v2.8b \n" " smull v1.8h, v7.8b, v3.8b \n" " saddlp v19.4s, v0.8h \n" " saddlp v23.4s, v1.8h \n" " cmp w20, #0 \n" " beq 3f \n" " 2: \n" " add x15, %x1, #32 \n" " add x14, %x0, #32 \n" " ld1 {v4.8b, v5.8b}, [%1], #16\n" " ld1 {v2.8b, v3.8b}, [%0], #16\n" " smull v0.8h, v4.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [x15], #16 \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v24.8b, v25.8b}, [x14], #16\n" " smlal v0.8h, v6.8b, v24.8b\n" " smlal v1.8h, v7.8b, v24.8b\n" " sadalp v8.4s, v0.8h\n" " sadalp v9.4s, v1.8h\n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v12.4s, v0.8h\n" " sadalp v13.4s, v1.8h\n" " // finish v8v9 v12v13, start proc v16v17,v20v21\n" " ld1 {v28.8b, v29.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v28.8b \n" " smull v1.8h, v5.8b, v28.8b \n" " ld1 {v26.8b, v27.8b}, [x14], #16\n" " smlal v0.8h, v6.8b, v26.8b \n" " smlal v1.8h, v7.8b, v26.8b \n" " sadalp v16.4s, v0.8h \n" " sadalp v17.4s, v1.8h \n" " smull v0.8h, v4.8b, v29.8b \n" " smull v1.8h, v5.8b, v29.8b \n" " smlal v0.8h, v6.8b, v27.8b \n" " smlal v1.8h, v7.8b, v27.8b \n" " sadalp v20.4s, v0.8h \n" " sadalp v21.4s, v1.8h \n" " // start v10v11, v14v15, v18v19, v22v23\n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [x15], #16 \n" " smlal v0.8h, v6.8b, v24.8b \n" " smlal v1.8h, v7.8b, v24.8b \n" " sadalp v10.4s, v0.8h \n" " sadalp v11.4s, v1.8h \n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v14.4s, v0.8h \n" " sadalp v15.4s, v1.8h \n" " smull v0.8h, v4.8b, v28.8b \n" " smull v1.8h, v5.8b, v28.8b \n" " smlal v0.8h, v6.8b, v26.8b \n" " smlal v1.8h, v7.8b, v26.8b \n" " sadalp v18.4s, v0.8h \n" " sadalp v19.4s, v1.8h \n" " smull v0.8h, v4.8b, v29.8b \n" " smull v1.8h, v5.8b, v29.8b \n" " smlal v0.8h, v6.8b, v27.8b \n" " smlal v1.8h, v7.8b, v27.8b \n" " sadalp v22.4s, v0.8h \n" " sadalp v23.4s, v1.8h \n" " add %0, %0, #32 \n" " add %1, %1, #32 \n" " subs w20, w20, #2 \n" " bne 2b \n" // start nd2 " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v10.4s, v10.4s, v11.4s\n" " addp v12.4s, v12.4s, v13.4s\n" " addp v14.4s, v14.4s, v15.4s\n" " addp v16.4s, v16.4s, v17.4s\n" " addp v18.4s, v18.4s, v19.4s\n" " addp v20.4s, v20.4s, v21.4s\n" " addp v22.4s, v22.4s, v23.4s\n" " addp v8.4s, v8.4s, v10.4s \n" " addp v9.4s, v12.4s, v14.4s \n" " addp v10.4s, v16.4s, v18.4s\n" " addp v11.4s, v20.4s, v22.4s\n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w8, #0 \n" " beq 4f \n" " // start subkernel_m4n4k4\n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load B4x4\n" " sxtl v4.8h, v4.8b \n" " mov v6.d[0], v4.d[1] \n" " sxtl v5.8h, v5.8b \n" " mov v7.d[0], v5.d[1] \n" " ld1 {v2.8b}, [%0], #8 // load A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v12.4s, v2.4h, v4.4h \n" " smull v13.4s, v2.4h, v6.4h \n" " smull v14.4s, v2.4h, v5.4h \n" " addp v12.4s, v12.4s, v13.4s\n" " smull v15.4s, v2.4h, v7.4h \n" " addp v14.4s, v14.4s, v15.4s\n" " addp v12.4s, v12.4s, v14.4s\n" " smull v16.4s, v3.4h, v4.4h \n" " add v8.4s, v8.4s, v12.4s \n" " smull v17.4s, v3.4h, v6.4h \n" " smull v18.4s, v3.4h, v5.4h \n" " addp v16.4s, v16.4s, v17.4s\n" " smull v19.4s, v3.4h, v7.4h \n" " addp v18.4s, v18.4s, v19.4s\n" " addp v16.4s, v16.4s, v18.4s\n" " add v9.4s, v9.4s, v16.4s \n" " ld1 {v2.8b}, [%0], #8 // load next A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v12.4s, v2.4h, v4.4h \n" " smull v13.4s, v2.4h, v6.4h \n" " smull v14.4s, v2.4h, v5.4h \n" " addp v12.4s, v12.4s, v13.4s\n" " smull v15.4s, v2.4h, v7.4h \n" " addp v14.4s, v14.4s, v15.4s\n" " addp v12.4s, v12.4s, v14.4s\n" " smull v16.4s, v3.4h, v4.4h \n" " add v10.4s, v10.4s, v12.4s \n" " smull v17.4s, v3.4h, v6.4h \n" " smull v18.4s, v3.4h, v5.4h \n" " addp v16.4s, v16.4s, v17.4s\n" " smull v19.4s, v3.4h, v7.4h \n" " addp v18.4s, v18.4s, v19.4s\n" " addp v16.4s, v16.4s, v18.4s\n" " add v11.4s, v11.4s, v16.4s \n" " 4: \n" " cmp %w9, #0 \n" " beq 5f \n" " // start subkernel_m4n4k2 \n" " ld1 {v0.8b}, [%1], #8 // load B2x4 \n" " // 00 11 22 33 \n" " rev32 v1.4h, v0.4h // 11 00 33 22 \n" " rev64 v2.2s, v0.2s // 22 33 00 11 \n" " ld1 {v4.8b}, [%0], #8 // load A4x2 \n" " rev64 v3.4h, v0.4h // 33 22 11 00 \n" " smull v12.8h, v4.8b, v0.8b \n" " smull v13.8h, v4.8b, v1.8b \n" " saddlp v12.4s, v12.8h \n" " smull v14.8h, v4.8b, v2.8b \n" " saddlp v13.4s, v13.8h \n" " smull v15.8h, v4.8b, v3.8b \n" " saddlp v14.4s, v14.8h \n" " saddlp v15.4s, v15.8h \n" " mov v16.s[0], v12.s[0] \n" " mov v16.s[1], v13.s[0] \n" " mov v16.s[2], v14.s[0] \n" " mov v16.s[3], v15.s[0] \n" " mov v17.s[0], v13.s[1] \n" " mov v17.s[1], v12.s[1] \n" " mov v17.s[2], v15.s[1] \n" " mov v17.s[3], v14.s[1] \n" " mov v18.s[0], v14.s[2] \n" " mov v18.s[1], v15.s[2] \n" " mov v18.s[2], v12.s[2] \n" " mov v18.s[3], v13.s[2] \n" " mov v19.s[0], v15.s[3] \n" " mov v19.s[1], v14.s[3] \n" " mov v19.s[2], v13.s[3] \n" " mov v19.s[3], v12.s[3] \n" " add v8.4s, v8.4s, v16.4s \n" " add v9.4s, v9.4s, v17.4s \n" " add v10.4s, v10.4s, v18.4s \n" " add v11.4s, v11.4s, v19.4s \n" " 5: \n" " cmp %w10, #0 \n" " beq 6f \n" " // start subkernel_m4n4k1\n" " ld1 {v4.8b}, [%1] // load B1x4\n" " add %1, %1, #4 \n" " ld1 {v2.8b}, [%0] // load A4x1\n" " add %0, %0, #4 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0] \n" " smlal v9.4s, v4.4h, v2.h[1] \n" " smlal v10.4s, v4.4h, v2.h[2] \n" " smlal v11.4s, v4.4h, v2.h[3] \n" " 6: \n" " cmp %12, #0 \n" " beq 9f \n" " ld1 {v12.4s}, [%12] \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " scvtf v9.4s, v9.4s \n" " scvtf v10.4s, v10.4s \n" " scvtf v11.4s, v11.4s \n" " // fp32 *= scale_tm \n" " fmul v8.4s, v8.4s, v12.s[0] \n" " fmul v9.4s, v9.4s, v12.s[1] \n" " fmul v10.4s, v10.4s, v12.s[2] \n" " fmul v11.4s, v11.4s, v12.s[3] \n" " cmp %13, #0 \n" " beq 7f \n" " ld1 {v14.4s}, [%13] \n" " dup v15.4s, v14.s[0] \n" " fadd v8.4s, v8.4s, v15.4s \n" " dup v15.4s, v14.s[1] \n" " fadd v9.4s, v9.4s, v15.4s \n" " dup v15.4s, v14.s[2] \n" " fadd v10.4s, v10.4s, v15.4s\n" " dup v15.4s, v14.s[3] \n" " fadd v11.4s, v11.4s, v15.4s\n" " 7: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s \n" " fcvtas v9.4s, v9.4s \n" " fcvtas v10.4s, v10.4s \n" " fcvtas v11.4s, v11.4s \n" " // int32 -> int16 \n" " sqxtn v6.4h, v8.4s \n" " sqxtn2 v6.8h, v9.4s \n" " sqxtn v7.4h, v10.4s \n" " sqxtn2 v7.8h, v11.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v6.8h \n" " sqxtn v9.8b, v7.8h \n" " // save \n" " st1 {v8.s}[0], [%2] \n" " add %x2, %x2, #4 \n" " st1 {v8.s}[1], [%3] \n" " add %x3, %x3, #4 \n" " st1 {v9.s}[0], [%4] \n" " add %x4, %x4, #4 \n" " st1 {v9.s}[1], [%5] \n" " add %x5, %x5, #4 \n" " b 10f \n" " 9: \n" " st1 {v8.4s}, [%x2], #16 \n" " st1 {v9.4s}, [%x3], #16 \n" " st1 {v10.4s}, [%x4], #16 \n" " st1 {v11.4s}, [%x5], #16 \n" " 10: \n" " subs %x11, %x11, #1 \n" " mov %x0, x8 \n" " bne 8b \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(pc2), // %4 "=r"(pc3), // %5 "=r"(k8_even), // %6 "=r"(k8), // %7 "=r"(k4), // %8 "=r"(k2), // %9 "=r"(k1), // %10 "=r"(n4), // %11 "=r"(scales), // %12 "=r"(bias) // %13 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(pc2), "5"(pc3), "6"(k8_even), "7"(k8), "8"(k4), "9"(k2), "10"(k1), "11"(n4), "12"(scales), "13"(bias) : "cc", "memory", "x8", "w20", "x14", "x15", "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"); } if (n2 > 0) { asm volatile( " eor v8.8b, v8.8b, v8.8b \n" " eor v9.8b, v9.8b, v9.8b \n" " eor v10.8b, v10.8b, v10.8b \n" " eor v11.8b, v11.8b, v11.8b \n" " eor v12.8b, v12.8b, v12.8b \n" " eor v13.8b, v13.8b, v13.8b \n" " eor v14.8b, v14.8b, v14.8b \n" " eor v15.8b, v15.8b, v15.8b \n" " eor v16.8b, v16.8b, v16.8b \n" " eor v17.8b, v17.8b, v17.8b \n" " eor v18.8b, v18.8b, v18.8b \n" " eor v19.8b, v19.8b, v19.8b \n" " eor v20.8b, v20.8b, v20.8b \n" " eor v21.8b, v21.8b, v21.8b \n" " eor v22.8b, v22.8b, v22.8b \n" " eor v23.8b, v23.8b, v23.8b \n" "9: \n" " mov x8, %x0 // PanelA \n" " cmp %w7, #0 \n" " beq 1f // k <= 7 \n" " mov w20, %w7 \n" " cmp %w6, #0 \n" " beq 2f// loop number is even \n" " // start loopkd8_nd2 \n" " subs w20, w20, #1 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 // load two lines of B\n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v9.4s, v0.8h \n" " saddlp v13.4s, v1.8h \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v16.4s, v0.8h \n" " saddlp v20.4s, v1.8h \n" " smull v0.8h, v5.8b, v2.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " saddlp v17.4s, v0.8h \n" " saddlp v21.4s, v1.8h \n" " cmp w20, #0 \n" " beq 3f \n" " 2: \n" " add x15, %1, #16 \n" " add x14, %0, #32 \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " ld1 {v6.8b, v7.8b}, [x15], #16 \n" " smull v1.8h, v5.8b, v2.8b \n" " ld1 {v24.8b, v25.8b}, [x14], #16 \n" " smlal v0.8h, v6.8b, v24.8b \n" " smlal v1.8h, v7.8b, v24.8b \n" " sadalp v8.4s, v0.8h \n" " sadalp v9.4s, v1.8h \n" " smull v0.8h, v4.8b, v3.8b \n" " smull v1.8h, v5.8b, v3.8b \n" " smlal v0.8h, v6.8b, v25.8b \n" " smlal v1.8h, v7.8b, v25.8b \n" " sadalp v12.4s, v0.8h \n" " sadalp v13.4s, v1.8h \n" " // finish v8v9 v12v13, start proc v16v17,v20v21\n" " ld1 {v28.8b, v29.8b}, [%0], #16\n" " smull v0.8h, v4.8b, v28.8b\n" " smull v1.8h, v5.8b, v28.8b\n" " ld1 {v26.8b, v27.8b}, [x14], #16\n" " smlal v0.8h, v6.8b, v26.8b\n" " smlal v1.8h, v7.8b, v26.8b\n" " sadalp v16.4s, v0.8h\n" " sadalp v17.4s, v1.8h\n" " smull v0.8h, v4.8b, v29.8b\n" " smull v1.8h, v5.8b, v29.8b\n" " smlal v0.8h, v6.8b, v27.8b\n" " smlal v1.8h, v7.8b, v27.8b\n" " sadalp v20.4s, v0.8h\n" " sadalp v21.4s, v1.8h\n" " add %0, %0, #32 \n" " add %1, %1, #16 \n" " subs w20, w20, #2 \n" " bne 2b \n" " 3: \n" " addp v8.4s, v8.4s, v9.4s \n" " addp v12.4s, v12.4s, v13.4s\n" " addp v16.4s, v16.4s, v17.4s\n" " addp v20.4s, v20.4s, v21.4s\n" " addp v8.4s, v8.4s, v8.4s \n" " addp v12.4s, v12.4s, v12.4s\n" " addp v16.4s, v16.4s, v16.4s\n" " addp v20.4s, v20.4s, v20.4s\n" " // start process kd4 kd2 kd1 cases\n" " 1: \n" " cmp %w8, 0 \n" " beq 4f \n" " // start subkernel_m4n2k4 \n" " ld1 {v4.8b}, [%1], #8 // load B4x2\n" " sxtl v4.8h, v4.8b \n" " mov v6.d[0], v4.d[1] \n" " ld1 {v2.8b}, [%0], #8 // load first A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v9.4s, v2.4h, v4.4h \n" " smull v10.4s, v2.4h, v6.4h \n" " addp v9.4s, v9.4s, v10.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " smull v13.4s, v3.4h, v4.4h \n" " smull v14.4s, v3.4h, v6.4h \n" " addp v13.4s, v13.4s, v14.4s\n" " addp v13.4s, v13.4s, v13.4s\n" " add v12.4s, v12.4s, v13.4s \n" " ld1 {v2.8b}, [%0], #8 // load next A2x4\n" " sxtl v2.8h, v2.8b \n" " mov v3.d[0], v2.d[1] \n" " smull v17.4s, v2.4h, v4.4h \n" " smull v18.4s, v2.4h, v6.4h \n" " addp v17.4s, v17.4s, v18.4s\n" " addp v17.4s, v17.4s, v17.4s\n" " add v16.4s, v16.4s, v17.4s \n" " smull v21.4s, v3.4h, v4.4h \n" " smull v22.4s, v3.4h, v6.4h \n" " addp v21.4s, v21.4s, v22.4s\n" " addp v21.4s, v21.4s, v21.4s\n" " add v20.4s, v20.4s, v21.4s \n" " 4: \n" " cmp %w9, 0 \n" " beq 5f \n" " // start subkernel_m4n2k2 \n" " ld1 {v4.8b}, [%0], #8 //load A4x2\n" " ld1 {v0.8b}, [%1] // load B2x2 \n" " add %1, %1, #4 \n" " // 00 11 22 33 \n" " rev32 v1.4h, v0.4h // 11 00 33 22 \n" " rev64 v2.2s, v0.2s // 22 33 00 11 \n" " rev64 v3.4h, v0.4h // 33 22 11 00 \n" " smull v21.8h, v4.8b, v0.8b \n" " smull v22.8h, v4.8b, v1.8b \n" " smull v23.8h, v4.8b, v2.8b \n" " smull v24.8h, v4.8b, v3.8b \n" " saddlp v21.4s, v21.8h \n" " saddlp v22.4s, v22.8h \n" " saddlp v23.4s, v23.8h \n" " saddlp v24.4s, v24.8h \n" " mov v9.s[0], v21.s[0] \n" " mov v9.s[1], v22.s[0] \n" " add v8.4s, v8.4s, v9.4s\n" " mov v13.s[0], v22.s[1] \n" " mov v13.s[1], v21.s[1] \n" " add v12.4s, v12.4s, v13.4s \n" " mov v17.s[0], v23.s[2] \n" " mov v17.s[1], v24.s[2] \n" " add v16.4s, v16.4s, v17.4s \n" " mov v21.s[0], v24.s[3] \n" " mov v21.s[1], v23.s[3] \n" " add v20.4s, v20.4s, v21.4s \n" " 5: \n" " cmp %w10, 0 \n" " beq 6f \n" " // start subkernel_m4n2k1\n" " ld1 {v4.8b}, [%1] // load B1x2\n" " add %1, %1, #2 \n" " ld1 {v2.8b}, [%0] // load A4x1\n" " add %0, %0, #4 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smlal v8.4s, v4.4h, v2.h[0] \n" " smlal v12.4s, v4.4h, v2.h[1] \n" " smlal v16.4s, v4.4h, v2.h[2] \n" " smlal v20.4s, v4.4h, v2.h[3] \n" " 6: \n" " cmp %11, #0 \n" " beq 7f \n" " mov v8.d[1], v12.d[0] \n" " mov v16.d[1], v20.d[0] \n" " // v12: 0 1 2 3 \n" " ld1 {v12.4s}, [%11] \n" " zip2 v13.4s, v12.4s, v12.4s \n" " zip1 v12.4s, v12.4s, v12.4s \n" " // v12: 0 0 1 1 \n" " // v13: 2 2 3 3 \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " scvtf v16.4s, v16.4s \n" " // fp32 *= scale_tm \n" " fmul v8.4s, v8.4s, v12.4s \n" " fmul v16.4s, v16.4s, v13.4s\n" " cmp %12, #0 \n" " beq 8f // skip add scales \n" " // fp32 += scales_tm \n" " ld1 {v12.4s}, [%12] \n" " zip2 v13.4s, v12.4s, v12.4s\n" " zip1 v12.4s, v12.4s, v12.4s\n" " fadd v8.4s, v8.4s, v12.4s \n" " fadd v16.4s, v16.4s, v13.4s\n" " 8: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s \n" " fcvtas v16.4s, v16.4s \n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " sqxtn v16.4h, v16.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " sqxtn v16.8b, v16.8h \n" " // save \n" " st1 {v8.h}[0], [%2] \n" " add %2, %2, #2 \n" " st1 {v8.h}[1], [%3] \n" " add %3, %3, #2 \n" " st1 {v16.h}[0], [%4] \n" " add %4, %4, #2 \n" " st1 {v16.h}[1], [%5] \n" " add %5, %5, #2 \n" " b 10f \n" " 7: \n" " st1 {v8.2s}, [%2], #8 \n" " st1 {v12.2s}, [%3], #8 \n" " st1 {v16.2s}, [%4], #8 \n" " st1 {v20.2s}, [%5], #8 \n" " 10: \n" " mov %0, x8 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(pc2), // %4 "=r"(pc3), // %5 "=r"(k8_even), // %6 "=r"(k8), // %7 "=r"(k4), // %8 "=r"(k2), // %9 "=r"(k1), // %10 "=r"(scales), // %11 "=r"(bias) // %12 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(pc2), "5"(pc3), "6"(k8_even), "7"(k8), "8"(k4), "9"(k2), "10"(k1), "11"(scales), "12"(bias) : "cc", "memory", "x8", "w20", "x14", "x15", "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"); } if (n1 > 0) { asm volatile( " eor v8.8b, v8.8b, v8.8b \n" " eor v9.8b, v9.8b, v9.8b \n" " eor v10.8b, v10.8b, v10.8b \n" " eor v11.8b, v11.8b, v11.8b \n" " eor v12.8b, v12.8b, v12.8b \n" " eor v13.8b, v13.8b, v13.8b \n" " eor v14.8b, v14.8b, v14.8b \n" " eor v15.8b, v15.8b, v15.8b \n" " eor v16.8b, v16.8b, v16.8b \n" " eor v17.8b, v17.8b, v17.8b \n" " eor v18.8b, v18.8b, v18.8b \n" " eor v19.8b, v19.8b, v19.8b \n" " eor v20.8b, v20.8b, v20.8b \n" " eor v21.8b, v21.8b, v21.8b \n" " eor v22.8b, v22.8b, v22.8b \n" " eor v23.8b, v23.8b, v23.8b \n" "1: \n" " cmp %w7, #0 \n" " beq 10f \n" " mov w20, %w7 \n" " cmp %w6, #0 \n" " beq 11f// loop number is even \n" " // start loopkd8_nd1 \n" " subs w20, w20, #1 \n" " ld1 {v4.8b}, [%1], #8 // load four lines of B\n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load two lines of PanelA\n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v8.4s, v0.8h \n" " saddlp v12.4s, v1.8h \n" " ld1 {v2.8b, v3.8b}, [%0], #16 \n" " smull v0.8h, v4.8b, v2.8b \n" " smull v1.8h, v4.8b, v3.8b \n" " saddlp v16.4s, v0.8h \n" " saddlp v20.4s, v1.8h \n" " cmp w20, #0 \n" " beq 12f \n" " 11: \n" " ld1 {v4.8b, v5.8b}, [%1], #16 \n" " ld1 {v24.8b, v25.8b, v26.8b, v27.8b}, [%0], #32\n" " ld1 {v28.8b, v29.8b, v30.8b, v31.8b}, [%0], #32\n" " smull v0.8h, v24.8b, v4.8b \n" " smlal v0.8h, v28.8b, v5.8b \n" " sadalp v8.4s, v0.8h \n" " smull v1.8h, v25.8b, v4.8b \n" " smlal v1.8h, v29.8b, v5.8b \n" " sadalp v12.4s, v1.8h \n" " smull v0.8h, v26.8b, v4.8b \n" " smlal v0.8h, v30.8b, v5.8b \n" " sadalp v16.4s, v0.8h \n" " smull v1.8h, v27.8b, v4.8b \n" " smlal v1.8h, v31.8b, v5.8b \n" " sadalp v20.4s, v1.8h \n" " subs w20, w20, #2 \n" " bne 11b \n" " 12: \n" " addp v8.4s, v8.4s, v8.4s \n" " addp v8.4s, v8.4s, v8.4s \n" " addp v12.4s, v12.4s, v12.4s\n" " addp v12.4s, v12.4s, v12.4s\n" " addp v16.4s, v16.4s, v16.4s\n" " addp v16.4s, v16.4s, v16.4s\n" " addp v20.4s, v20.4s, v20.4s\n" " addp v20.4s, v20.4s, v20.4s\n" " // start process kd4 kd2 kd1 cases\n" " 10: \n" " cmp %w8, #0 \n" " beq 13f \n" " // start subkernel_m4n1k2 \n" " ld1 {v4.8b}, [%1] // load B4x1\n" " add %x1, %x1, #4 \n" " sxtl v4.8h, v4.8b // extend B4x1 to v4 \n" " ld1 {v2.8b, v3.8b}, [%0], #16 // load A4x4\n" " sxtl v2.8h, v2.8b \n" " mov v5.d[0], v2.d[1] \n" " sxtl v3.8h, v3.8b \n" " mov v6.d[0], v3.d[1] // extend A4x4 to v2,v5,v3,v6\n" " smull v9.4s, v2.4h, v4.4h \n" " addp v9.4s, v9.4s, v9.4s \n" " addp v9.4s, v9.4s, v9.4s \n" " add v8.4s, v8.4s, v9.4s \n" " smull v13.4s, v5.4h, v4.4h \n" " addp v13.4s, v13.4s, v13.4s\n" " addp v13.4s, v13.4s, v13.4s\n" " add v12.4s, v12.4s, v13.4s \n" " smull v17.4s, v3.4h, v4.4h \n" " addp v17.4s, v17.4s, v17.4s\n" " addp v17.4s, v17.4s, v17.4s\n" " add v16.4s, v16.4s, v17.4s \n" " smull v21.4s, v6.4h, v4.4h \n" " addp v21.4s, v21.4s, v21.4s\n" " addp v21.4s, v21.4s, v21.4s\n" " add v20.4s, v20.4s, v21.4s \n" " 13: \n" " cmp %w9, #0 \n" " beq 14f \n" " // start subkernel_m4n1k2 \n" " ld1 {v4.8b}, [%0], #8 // load A4x2 \n" " ld1 {v0.8b}, [%1] // load B2x1 \n" " add %1, %1, #2 \n" " mov v0.h[1], v0.h[0] \n" " mov v0.s[1], v0.s[0] \n" " smull v0.8h, v0.8b, v4.8b \n" " saddlp v0.4s, v0.8h \n" " mov v9.s[0], v0.s[0] \n" " add v8.4s, v8.4s, v9.4s \n" " mov v13.s[0], v0.s[1] \n" " add v12.4s, v12.4s, v13.4s \n" " mov v17.s[0], v0.s[2] \n" " add v16.4s, v16.4s, v17.4s \n" " mov v21.s[0], v0.s[3] \n" " add v20.4s, v20.4s, v21.4s \n" " 14: \n" " cmp %w10, #0 \n" " beq 15f \n" " // start subkernel_m4n1k1 \n" " ld1 {v4.8b}, [%1] // load B1x1\n" " add %1, %1, #1 \n" " ld1 {v2.8b}, [%0] // load A4x1\n" " add %0, %0, #4 \n" " sxtl v4.8h, v4.8b \n" " sxtl v2.8h, v2.8b \n" " smull v0.4s, v2.4h, v4.h[0]\n" " add v8.4s, v8.4s, v0.4s \n" " mov v13.s[0], v0.s[1] \n" " add v12.4s, v12.4s, v13.4s \n" " mov v17.s[0], v0.s[2] \n" " add v16.4s, v16.4s, v17.4s \n" " mov v21.s[0], v0.s[3] \n" " add v20.4s, v20.4s, v21.4s \n" " 15: \n" // REQUANT " cmp %11, #0 \n" " beq 16f \n" " mov v8.s[1], v12.s[0] \n" " mov v8.s[2], v16.s[0] \n" " mov v8.s[3], v20.s[0] \n" " // v12: s0 s1 s2 s3 \n" " ld1 {v12.4s}, [%11] \n" " // int32 => fp32 \n" " scvtf v8.4s, v8.4s \n" " // fp32 *= scale_tm \n" " fmul v8.4s, v8.4s, v12.4s \n" " cmp %12, #0 \n" " beq 17f \n" " // fp32 += bias_tm \n" " ld1 {v12.4s}, [%12] \n" " fadd v8.4s, v8.4s, v12.4s \n" " 17: \n" " // fp32 -> int32 \n" " fcvtas v8.4s, v8.4s \n" " // int32 -> int16 \n" " sqxtn v8.4h, v8.4s \n" " // int16 -> int8 \n" " sqxtn v8.8b, v8.8h \n" " // save \n" " st1 {v8.b}[0], [%2] \n" " st1 {v8.b}[1], [%3] \n" " st1 {v8.b}[2], [%4] \n" " st1 {v8.b}[3], [%5] \n" " b 2f \n" " // no need to add the last output pointer\n" " 16: \n" " st1 {v8.s}[0], [%2] \n" " st1 {v12.s}[0], [%3] \n" " st1 {v16.s}[0], [%4] \n" " st1 {v20.s}[0], [%5] \n" " 2: \n" " mov x0, #0 \n" : "=r"(pa), // %0 "=r"(pb), // %1 "=r"(pc0), // %2 "=r"(pc1), // %3 "=r"(pc2), // %4 "=r"(pc3), // %5 "=r"(k8_even), // %6 "=r"(k8), // %7 "=r"(k4), // %8 "=r"(k2), // %9 "=r"(k1), // %10 "=r"(scales), // %11 "=r"(bias) // %12 : "0"(pa), "1"(pb), "2"(pc0), "3"(pc1), "4"(pc2), "5"(pc3), "6"(k8_even), "7"(k8), "8"(k4), "9"(k2), "10"(k1), "11"(scales), "12"(bias) : "cc", "memory", "x0", "x8", "w20", "x14", "x15", "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"); } } #undef DECOMPOSE_K #undef DECOMPOSE_N static void int8kernel(void* dst, const int8_t* sa, const int8_t* sb, int m, int k, int n, int ldc, float* scales, float* bias, const ncnn::Option& opt) { int8_t* pa = (int8_t*)sa; int8_t* pb = (int8_t*)sb; const int nn = (m >> 2) << 2; if (scales == 0) { int32_t* pc = (int32_t*)dst; #if PRINT_MATRIX int32_t* origin = pc; #endif #pragma omp parallel for num_threads(opt.num_threads) for (int i = 0; i < nn; i += 4) { int8kernel_m4((void*)(pc + i * ldc), pa + i * k, pb, m, k, n, ldc, 0, 0); } pa += nn * k; pc += nn * ldc; switch (m - nn) { case 3: int8kernel_m2((void*)pc, pa, pb, m, k, n, ldc, 0, 0); pc += 2 * ldc; pa += 2 * k; int8kernel_m1((void*)pc, pa, pb, m, k, n, ldc, 0, 0); break; case 2: int8kernel_m2((void*)pc, pa, pb, m, k, n, ldc, 0, 0); break; case 1: int8kernel_m1((void*)pc, pa, pb, m, k, n, ldc, 0, 0); break; case 0: default: break; } #if PRINT_MATRIX print_int32_matrix("pc", origin, m, n, ldc); #endif } else { int8_t* pc = (int8_t*)dst; #if PRINT_MATRIX print_fp32_vec("scales", scales, m); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int i = 0; i < nn; i += 4) { int8kernel_m4((void*)(pc + i * ldc), pa + i * k, pb, m, k, n, ldc, scales + i, (bias == 0) ? 0 : bias + i); } pa += nn * k; pc += nn * ldc; scales += nn; bias = (bias == 0) ? 0 : bias + nn; switch (m - nn) { case 3: int8kernel_m2((void*)pc, pa, pb, m, k, n, ldc, scales, bias); pc += 2 * ldc; pa += 2 * k; scales += 2; bias = (bias == 0) ? 0 : bias + 2; int8kernel_m1((void*)pc, pa, pb, m, k, n, ldc, scales, bias); break; case 2: int8kernel_m2((void*)pc, pa, pb, m, k, n, ldc, scales, bias); break; case 1: int8kernel_m1((void*)pc, pa, pb, m, k, n, ldc, scales, bias); break; case 0: default: break; } } return; } #ifdef PRINT_MATRIX #undef PRINT_MATRIX #endif #endif
core_strsm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_ztrsm.c, normal z -> s, Fri Sep 28 17:38:19 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_trsm * * Solves one of the matrix equations * * \f[ op( A )\times X = \alpha B, \f] or * \f[ X \times op( A ) = \alpha B, \f] * * where op( A ) is one of: * \f[ op( A ) = A, \f] * \f[ op( A ) = A^T, \f] * \f[ op( A ) = A^T, \f] * * alpha is a scalar, X and B are m-by-n matrices, and * A is a unit or non-unit, upper or lower triangular matrix. * The matrix X overwrites B. * ******************************************************************************* * * @param[in] side * - PlasmaLeft: op(A)*X = B, * - PlasmaRight: X*op(A) = B. * * @param[in] uplo * - PlasmaUpper: A is upper triangular, * - PlasmaLower: A is lower triangular. * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] diag * - PlasmaNonUnit: A has non-unit diagonal, * - PlasmaUnit: A has unit diagonal. * * @param[in] m * The number of rows of the matrix B. m >= 0. * * @param[in] n * The number of columns of the matrix B. n >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] A * The lda-by-ka triangular matrix, * where ka = m if side = PlasmaLeft, * and ka = n if side = PlasmaRight. * If uplo = PlasmaUpper, the leading k-by-k upper triangular part * of the array A contains the upper triangular matrix, and the * strictly lower triangular part of A is not referenced. * If uplo = PlasmaLower, the leading k-by-k lower triangular part * of the array A contains the lower triangular matrix, and the * strictly upper triangular part of A is not referenced. * If diag = PlasmaUnit, the diagonal elements of A are also not * referenced and are assumed to be 1. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,k). * * @param[in,out] B * On entry, the ldb-by-n right hand side matrix B. * On exit, if return value = 0, the ldb-by-n solution matrix X. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_strsm(plasma_enum_t side, plasma_enum_t uplo, plasma_enum_t transa, plasma_enum_t diag, int m, int n, float alpha, const float *A, int lda, float *B, int ldb) { cblas_strsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)transa, (CBLAS_DIAG)diag, m, n, (alpha), A, lda, B, ldb); } /******************************************************************************/ void plasma_core_omp_strsm( plasma_enum_t side, plasma_enum_t uplo, plasma_enum_t transa, plasma_enum_t diag, int m, int n, float alpha, const float *A, int lda, float *B, int ldb, plasma_sequence_t *sequence, plasma_request_t *request) { int ak; if (side == PlasmaLeft) ak = m; else ak = n; if (sequence->status == PlasmaSuccess) { int side_ = side, uplo_ = uplo; int transa_ = transa, diag_ = diag; int size_A = lda*ak, size_B = ldb*n; #pragma omp target nowait \ depend(in:A[0:size_A]) \ depend(inout:B[0:size_B]) \ firstprivate(side_, uplo_, transa_, diag_) \ firstprivate(m, n, alpha, lda, ldb) \ map(to:A[0:size_A]) \ map(tofrom:B[0:size_B]) { int block_size = 64; plasma_core_strsm(side_, uplo_, transa_, diag_, block_size, block_size, alpha, A, block_size, B, block_size); } } }
GB_binop__band_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__band_int8) // A.*B function (eWiseMult): GB (_AemultB_01__band_int8) // A.*B function (eWiseMult): GB (_AemultB_02__band_int8) // A.*B function (eWiseMult): GB (_AemultB_03__band_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_int8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__band_int8) // C+=b function (dense accum): GB (_Cdense_accumb__band_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_int8) // C=scalar+B GB (_bind1st__band_int8) // C=scalar+B' GB (_bind1st_tran__band_int8) // C=A+scalar GB (_bind2nd__band_int8) // C=A'+scalar GB (_bind2nd_tran__band_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_BAND || GxB_NO_INT8 || GxB_NO_BAND_INT8) //------------------------------------------------------------------------------ // 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__band_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__band_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_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 //------------------------------------------------------------------------------ #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 int8_t *restrict Cx = (int8_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 int8_t *restrict Cx = (int8_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__band_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__band_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__band_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__band_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__band_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) & (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_int8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__lnot_bool_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_bool_int64 // op(A') function: GB_tran__lnot_bool_int64 // C type: bool // A type: int64_t // cast: bool cij = (bool) aij // unaryop: cij = !aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !x ; // casting #define GB_CASTING(z, aij) \ bool z = (bool) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_bool_int64 ( bool *Cx, // Cx and Ax may be aliased int64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_bool_int64 ( 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
RefTraceTools.h
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2013) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// #ifndef REFTRACE_TOOLS_H #define REFTRACE_TOOLS_H // MakeDepend: library OMP // MakeDepend: cflags OMP_FLAGS #include "Basevector.h" #include "CoreTools.h" #include "paths/HyperBasevector.h" #include "pairwise_aligners/SmithWatAffine.h" #include "pairwise_aligners/SmithWatBandedA.h" #include "paths/long/MakeKmerStuff.h" #include "PrintAlignment.h" #include "paths/long/RefTrace.h" // Create a HyperBasevector hbp that equals hb plus its reverse complement. // However only do this for components that need it. void CreateHBPlus(const HyperBasevector& hb, const vec<int>& inv, HyperBasevector& hbp, vec<std::pair<int,Bool>>& hbp_to_hb); // Linearized reference sequences. Expand the paths from the source to the sink // of the reference graph, built a vecbasevector of expended sequence, and // record the origion of of the chromosome id. class LinearRef { public: LinearRef(const vec<HyperBasevector>& GH,const vec<bool>& c=vec<bool>()); int N() const { return G.size(); } int Source(int g) const {return G_source[g]; } bool IsDoubled(int g) const {return isDoubled[g]; } const basevector& Seq(int g) const { return G[g]; } const vecbasevector& Seqs() const { return G; } private: vec<int> G_source; vecbasevector G; vec<bool> isDoubled; }; // Some data structures. // The structure vedata has the following structure: // { (genome_tig_id, start_pos_on_genome_tig, left_vertex_of_edge_in_hbp ), // (genome_tig_id, stop_pos_on_genome_tig-K+1, right_vertex_of_edge_in_hbp ), // (hbp_edge_id, error_count), // (start_pos_on_hbp_edge, stop_pos_on_hbp_edge) }. class EdgePlacements { public: EdgePlacements(const HyperBasevector& hbp, const vec<std::pair<int,Bool>>& hbp_to_hb, const vecbasevector& G) : hbp(hbp), hbp_to_hb(hbp_to_hb), G(G) {} // Align edges of hbp to reference. template<int L> void AlignEdgesToRef( // heuristics: const double min_cov_frac, const double max_error_rate, const int max_offset_diff, const double min_group_frac, const int offset_add, const int min_group_save, const Bool fix_bug, // logging: bool REFTRACE_VARIANTS, const int verbosity, std::ostream& out ); template <int L> void AlignEdgesToRefExp(const int verbosity, std::ostream& out); void RemoveBadPlacements(); void Twiddle(const int max_twiddle); void TwiddleSmart(); // Generate the matching sequences from the best path. basevector BestSeq(const vec<int>& best_path, const vec<int>& eids , const vec<std::pair<int,int>>& limits , vec<std::tuple<int64_t,int64_t,int,int64_t,int64_t,int64_t,int64_t>>& coors_edge); public: const HyperBasevector& hbp; const vec<std::pair<int,Bool>>& hbp_to_hb; const vecbasevector& G; vec< quad< triple<int,int,int>, triple<int,int,int>, std::pair<int,int>, std::pair<int,int> > > vedata; vec<align> aligns; vec<int> xto_left, xto_right; private: int CorrelatePositionsAlways(const align& a, const int x1)const; }; class GraphZ { public: typedef int (*PenaltyFuncT)(int, int, int); GraphZ(const EdgePlacements& ep, PenaltyFuncT pf) : edge_placements(ep), hbp(ep.hbp), hbp_to_hb(ep.hbp_to_hb), G(ep.G) { Penalty = pf; } void FindShortestPath(const int min_dist, const int max_dist, vec< vec<int> >& spaths, vec< triple<int,int,int> >& spaths_egd, vec< std::pair<int,int> >& spaths_gg_pen, std::ostream& out, int verbosity = 0); // Find the corresponding best path in hbp edges. void FindBestEdgePath( const vec< triple<int,int,int> >& spaths_egd, const vec< vec<int> >& spaths, vec<vec<int>>& best_path, vec<vec<int>>& eids, int& best_g) ; public: const EdgePlacements& edge_placements; const HyperBasevector& hbp; const vec<std::pair<int,Bool>>& hbp_to_hb; const vecbasevector& G; PenaltyFuncT Penalty; vec< triple<int,int,int> > verts; vec< triple< int, int, std::pair<int,int> > > edges; vec< triple<int,int,int> > egd; digraphE<int> Z; private: void BuildGraph(const int verbosity, std::ostream& out); void AddGapEdges(const int min_dist, const int max_dist, const int verbosity, std::ostream& out ,const bool bPreserveDisconnectedComponents=false); void AddConnectedGapEdges(const int min_dist, const int max_dist, const int verbosity, std::ostream& out ,const bool bPreserveDisconnectedComponents=false); void AddSpecialVerts( const int K, const vec<int>& sources, const vec<int>& sinks, const bool bPreserveDisconnectedComponents=false); void AnnouncePaths( const vec< vec<int> >& spaths, const int K, const vec< triple<int,int,int> >& spaths_egd, const int verbosity, std::ostream& out ) const; void FindShortestPathBetween( const int this_source, const int this_sink, const digraphE<int>& ZS, const vec<int>& suc, vec< vec<int> >& spaths, vec< triple<int,int,int> >& spaths_egd, vec< std::pair<int,int> >& spaths_gg_pen, const int verbosity, std::ostream& out ) const; void MakeZDot(std::ostream& os); }; template<int L> void EdgePlacements::AlignEdgesToRef( const double min_cov_frac, const double max_error_rate, const int max_offset_diff, const double min_group_frac, const int offset_add, const int min_group_save, const Bool fix_bug, // logging: bool REFTRACE_VARIANTS, const int verbosity, std::ostream& out ) { // Setup for alignment. vecbasevector all(G); vec< triple<kmer<L>,int,int> > kmers_plus; MakeKmerLookup0( all, kmers_plus ); vec< kmer<L> > kmers( kmers_plus.size( ) ); for ( int64_t i = 0; i < kmers_plus.jsize( ); i++ ) kmers[i] = kmers_plus[i].first; hbp.ToLeft(xto_left), hbp.ToRight(xto_right); // Go through the edges of the (doubled) assembly. #pragma omp parallel for schedule(dynamic,1) for ( int i = 0; i < hbp.EdgeObjectCount( ); i++ ) { const basevector& e = hbp.EdgeObject(i); // For each kmer in the edge, find its hits to the reference and find // the kmers having the most hits. int nkmers = e.isize( ) - L + 1; vec< triple<int64_t,int64_t,int64_t> > locs(nkmers); vec<int> pos( nkmers, vec<int>::IDENTITY ); kmer<L> x; for ( int j = 0; j < nkmers; j++ ) { x.SetToSubOf( e, j ); int64_t low = LowerBound(kmers, x), high = UpperBound(kmers, x); locs[j].first = high - low; locs[j].second = low, locs[j].third = high; } if (fix_bug) ReverseSortSync( locs, pos ); else SortSync( locs, pos ); // Determine cutoff 'top'. double mcf = min_cov_frac; if ( REFTRACE_VARIANTS ) mcf = 0.6; int t = int( floor( nkmers * mcf ) ), top; for ( top = t + 1; top < nkmers; top++ ) if ( locs[top].first > locs[t].first ) break; // Find the associated offsets. vec< std::pair<int,int> > offset; for ( int j = 0; j < top; j++ ) { for ( int64_t m = locs[j].second; m < locs[j].third; m++ ) { int g = kmers_plus[m].second, o = kmers_plus[m].third - pos[j]; offset.push( g, o ); } } Sort(offset); // Form offsets into groups. vec< triple< int, int, std::pair<int,int> > > og; int mod = max_offset_diff; if ( REFTRACE_VARIANTS ) mod = 500; for ( int j = 0; j < offset.isize( ); j++ ) { int k; for ( k = j + 1; k < offset.isize( ); k++ ) { if ( offset[k].first != offset[j].first ) break; if ( offset[k].second - offset[k-1].second > mod ) break; } og.push( k - j, offset[j].first, std::make_pair( offset[j].second, offset[k-1].second ) ); j = k - 1; } ReverseSort(og); if ( verbosity >= 4 ) { #pragma omp critical { out << "\noriginal edge " << hbp_to_hb[i].first << ": "; PRINT4_TO( out, nkmers, top, offset.size( ), og.size( ) ); for ( int j = 0; j < og.isize( ); j++ ) PRINT2_TO( out, j, og[j].first ); } } // Filter offset groups. double mgf = min_group_frac; if ( REFTRACE_VARIANTS ) mgf = 0.65; int gj; for ( gj = 0; gj < og.isize( ); gj++ ) { if ( og[gj].first < min_group_save && og[gj].first < mgf * og[0].first ) { break; } } og.resize(gj); if ( verbosity >= 3 && og.nonempty( ) ) { #pragma omp critical { out << "\noffsets for edge " << i << " (hb_edge=" << hbp_to_hb[i].first << ", nkmers=" << nkmers << ")" << std::endl; for ( int j = 0; j < og.isize( ); j++ ) { out << "[" << j << "] " << og[j].second << "." << og[j].third.first << "-" << og[j].third.second << " (" << og[j].first << ")" << std::endl; } } } // Align. The reason for adding to the offset is that there could be in // indel in the first or last L bases. for ( int j = 0; j < og.isize( ); j++ ) { int g = og[j].second; int off_low = og[j].third.first, off_high = og[j].third.second; int mid_offset = ( off_low + off_high ) / 2; int bandwidth = Max(mid_offset - off_low, off_high - mid_offset) + offset_add; // Do the alignment. This is kludgy. If the alignment has too // many errors and the edge is long, we suspect that the problem // might be with a big indel, so we align using a larger bandwidth. // Note the unfortunate us of hardcoded constants. align a; int errors; if ( !REFTRACE_VARIANTS ) { const int SMA_method = 1; if (SMA_method == 1) { SmithWatBandedA( hbp.EdgeObject(i), G[g], -mid_offset, bandwidth, a, errors, 0, 1, 1 ); } else if(SMA_method == 2) { SmithWatAffineBanded( hbp.EdgeObject(i), G[g], -mid_offset, bandwidth, a, errors ); } else { std::cout << "unrecognized SMA_method" << std::endl; } if ( double(errors) / double( a.extent2( ) ) > max_error_rate ) { // So the following code (after the continue; // bandwidth=5000) was taking a ton of time // (0.5-1 sec per alignment). Also in my tests // it had a very low success rate <0.5% AND its // removal does not seem to impact the result. // We should do something clever with the // alignments (super aligner?) if we end up // needing it. -- neilw continue; #if 0 const int long_edge = 5000; const int max_indel = 5000; if ( hbp.EdgeLengthBases(i) < long_edge ) continue; SmithWatBandedA( hbp.EdgeObject(i), G[g], -mid_offset, max_indel, a, errors, 0, 1, 1 ); if ( double(errors) / double( a.extent2( ) ) > max_error_rate ) continue; #endif } } else { double score = SmithWatAffineBanded( hbp.EdgeObject(i), G[g], -mid_offset, bandwidth, a, errors ) / 3.0; if ( verbosity >= 3 ) { #pragma omp critical { double err_rate = score / double( a.extent2( ) ); int hb_edge = hbp_to_hb[i].first; int offset = -mid_offset; PRINT5( hb_edge, offset, bandwidth, score, err_rate ); } } double var_max_error_rate = 0.3; if ( score / double( a.extent2( ) ) > var_max_error_rate ) continue; } if ( verbosity >= 3 ) { #pragma omp critical { out << "\nalignment " << j << " of edge " << i << " (" << xto_left[i] << " --> " << xto_right[i] << ", hb_edge=" << hbp_to_hb[i].first << ")" << std::endl; vec<int> errs = a.MutationsGap1Gap2( hbp.EdgeObject(i), G[g] ); int mismatches = errs[0]; int indels = errs[1] + errs[2]; PRINT5_TO( out, g, a.pos2( ), a.Pos2( ), mismatches, indels ); if ( verbosity == 4 ) { PrintVisualAlignment( True, out, hbp.EdgeObject(i), G[g], a ); } if ( verbosity >= 5 ) { PrintVisualAlignment( False, out, hbp.EdgeObject(i), G[g], a ); } } } // Figure out where the position e.isize( ) - K + 1 should map to // under the alignment. Note that because there could be an indel // there, this is not necessarily a meaningful answer. int x1 = e.isize( ) - hbp.K( ) + 1; int x2 = CorrelatePositionsAlways( a, x1 ); // Save results. #pragma omp critical { vedata.push( make_triple( g, a.pos2( ), xto_left[i] ), make_triple( g, x2, xto_right[i] ), std::make_pair( i, errors ), std::make_pair( a.pos1( ), a.Pos1( ) ) ); aligns.push_back(a); } } } // Sort the output to avoid the stochastic downstream behavior of BuildGraph // that seems depend on the input order of the alignment data. SortSync(vedata, aligns); } // An experimental version of function to align edges to reference that // automatically adjust heuristics for best results. template<int L> void EdgePlacements::AlignEdgesToRefExp(const int verbosity, std::ostream& out) { // Setup for alignment. vecbasevector all(G); vec< triple<kmer<L>,int,int> > kmers_plus; MakeKmerLookup0( all, kmers_plus ); vec< kmer<L> > kmers( kmers_plus.size( ) ); for ( int64_t i = 0; i < kmers_plus.jsize( ); i++ ) kmers[i] = kmers_plus[i].first; hbp.ToLeft(xto_left), hbp.ToRight(xto_right); unsigned int max_g_len = G.front().size(); for(size_t gg=1;gg<G.size();++gg){max_g_len=std::max(max_g_len,G[gg].size());} vec<std::pair<int,int>> permutation(hbp.EdgeObjectCount()); for(int ii=0;ii<hbp.EdgeObjectCount();++ii){ permutation[ii]=std::make_pair(hbp.EdgeObject(ii).isize(),ii);} std::sort(permutation.rbegin(),permutation.rend()); //very dirty way of load balance, should be coded with a worklist.h instead. typedef triple< int, int, std::pair<int,int> > og_type; // the og specification from old code typedef std::tuple<og_type,double,int> work_type; // og_type, max_error_rate, offset_add vec< vec<work_type> > ee_vec_work( hbp.EdgeObjectCount() ); // edge_idx -> a list of work_type vec< std::pair<size_t,size_t> > unit_idx_tt_vec_work; // flattened indices of ee_vec_work const int np=3;//number of passes #pragma omp parallel { SmithWatBandedAEngine swbae(sqrt(max_g_len)*2,sqrt(max_g_len)); #pragma omp for schedule(dynamic,1) for ( int ee = 0; ee < hbp.EdgeObjectCount( ); ee++ ) { int i=permutation[ee].second; const basevector& e = hbp.EdgeObject(i); // For each kmer in the edge, find its hits to the reference and find // the kmers having the most hits. int nkmers = e.isize( ) - L + 1; vec< triple<int64_t,int64_t,int64_t> > locs(nkmers); vec<int> pos( nkmers, vec<int>::IDENTITY ); kmer<L> x; for ( int j = 0; j < nkmers; j++ ) { x.SetToSubOf( e, j ); int64_t low = LowerBound(kmers, x), high = UpperBound(kmers, x); locs[j].first = high - low; locs[j].second = low, locs[j].third = high; } ReverseSortSync( locs, pos ); // Determine cutoff 'top'. double min_cov_frac = 0.5; int t = int( floor( nkmers * min_cov_frac ) ), top; for ( top = t + 1; top < nkmers; top++ ) if ( locs[top].first > locs[t].first ) break; // Find the associated offsets. vec< std::pair<int,int> > offset; for ( int j = 0; j < top; j++ ) { for ( int64_t m = locs[j].second; m < locs[j].third; m++ ) { int g = kmers_plus[m].second, o = kmers_plus[m].third - pos[j]; offset.push( g, o ); } } Sort(offset); for(int pass = 0; pass < np; pass++) { // auto pt = getenv("PASS"); // if (pt) { // pass = atoi(pt); // np = 1; // std::cout << "pass= " << pass << std::endl; // } RefTraceHeuristics rth; switch (pass) { case 0: //rth.max_offset_diff = 10; // default //rth.max_error_rate = 0.05; //rth.offset_add = 1; // default //rth.max_twiddle = 3; // default rth.min_group_frac = 0.1; rth.min_group_save = 200; break; case 1: rth.max_offset_diff = 30; rth.max_error_rate = 0.31; rth.offset_add = 5; rth.min_group_frac = 0.1; rth.max_twiddle = 5; break; case 2: rth.max_offset_diff = 350; rth.max_error_rate = 0.31; rth.offset_add = 5; rth.min_group_frac = 0.75; rth.max_twiddle = 120; break; } // Form offsets into groups. vec< triple< int, int, std::pair<int,int> > > og; for ( int j = 0; j < offset.isize( ); j++ ) { int k; for ( k = j + 1; k < offset.isize( ); k++ ) { if ( offset[k].first != offset[j].first ) break; if ( offset[k].second - offset[k-1].second > rth.max_offset_diff ) break; } og.push( k - j, offset[j].first, std::make_pair( offset[j].second, offset[k-1].second ) ); j = k - 1; } ReverseSort(og); // Filter offset groups. int gj; for ( gj = 0; gj < og.isize( ); gj++ ) { if ( og[gj].first < rth.min_group_save && og[gj].first < rth.min_group_frac * og[0].first ) { break; } } og.resize(gj); for( const auto& entry: og ){ ee_vec_work[i].emplace_back( entry , rth.max_error_rate, rth.offset_add); } } } { #pragma omp barrier } #pragma omp master { const size_t n=std::accumulate(ee_vec_work.begin(),ee_vec_work.end(),size_t(0),[](size_t a,vec<work_type>const&b){return a+b.size();}); unit_idx_tt_vec_work.reserve(n); for(const auto& entry: permutation){ for(size_t ff=0;ff<ee_vec_work[entry.second].size();++ff){ unit_idx_tt_vec_work.emplace_back(entry.second,ff); } } } { #pragma omp barrier } #pragma omp for schedule(dynamic,1) nowait for ( size_t og_idx = 0 ; og_idx < unit_idx_tt_vec_work.size() ; ++og_idx) { { // Align. The reason for adding to the offset is that there could be in // indel in the first or last L bases. // for ( int j = 0; j < og.isize( ); j++ ) { const auto& indices = unit_idx_tt_vec_work[og_idx]; const auto& entry = ee_vec_work[indices.first][indices.second]; // int g = og[j].second; // int off_low = og[j].third.first, off_high = og[j].third.second; int g = std::get<0>(entry).second; int off_low = std::get<0>(entry).third.first, off_high = std::get<0>(entry).third.second; int mid_offset = ( off_low + off_high ) / 2; int bandwidth = Max(mid_offset - off_low, off_high - mid_offset) + std::get<2>(entry);// rth.offset_add; // Do the alignment. This is kludgy. If the alignment has too // many errors and the edge is long, we suspect that the problem // might be with a big indel, so we align using a larger bandwidth. // Note the unfortunate us of hardcoded constants. align a; int errors; swbae.run( hbp.EdgeObject(indices.first), G[g], -mid_offset, bandwidth, a, errors, 0, 1, 1 ); if ( double(errors) / double( a.extent2( ) ) > std::get<1>(entry) /*rth.max_error_rate*/ ) { const int long_edge = 5000; const int max_indel = 5000; if ( hbp.EdgeLengthBases(indices.first) < long_edge ) continue; swbae.run( hbp.EdgeObject(indices.first), G[g], -mid_offset, max_indel, a, errors, 0, 1, 1 ); if ( double(errors) / double( a.extent2( ) ) > std::get<1>(entry)/*rth.max_error_rate*/ ) continue; } // errors += a.pos1(); // errors += hbp.EdgeObject(i).size()-a.Pos1(); // Figure out where the position e.isize( ) - K + 1 should map to // under the alignment. Note that because there could be an indel // there, this is not necessarily a meaningful answer. int x1 = hbp.EdgeObject(indices.first).isize( ) - hbp.K( ) + 1; int x2 = CorrelatePositionsAlways( a, x1 ); #pragma omp critical { vedata.push( make_triple( g, a.pos2( ), xto_left[indices.first] ), make_triple( g, x2, xto_right[indices.first] ), std::make_pair( indices.first, errors ), std::make_pair( a.pos1( ), a.Pos1( ) ) ); aligns.push_back(a); } } } } }//omp parallel // Sort the output to avoid the stochastic downstream behavior of BuildGraph // that seems depend on the input order of the alignment data. UniqueSortSync(vedata, aligns); } #endif
residual_criteria.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // #if !defined(KRATOS_RESIDUAL_CRITERIA ) #define KRATOS_RESIDUAL_CRITERIA // System includes // External includes // Project includes #include "includes/model_part.h" #include "includes/define.h" #include "utilities/constraint_utilities.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualCriteria * @ingroup KratosCore * @brief This is a convergence criteria that employes the residual as criteria * @details The reactions from the RHS are not computed in the residual * @author Riccardo Rossi */ template<class TSparseSpace, class TDenseSpace > class ResidualCriteria : public ConvergenceCriteria< TSparseSpace, TDenseSpace > { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION( ResidualCriteria ); /// The definition of the base ConvergenceCriteria typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType; /// The definition of the current class typedef ResidualCriteria< TSparseSpace, TDenseSpace > ClassType; /// The data type typedef typename BaseType::TDataType TDataType; /// The dofs array type typedef typename BaseType::DofsArrayType DofsArrayType; /// The sparse matrix type typedef typename BaseType::TSystemMatrixType TSystemMatrixType; /// The dense vector type typedef typename BaseType::TSystemVectorType TSystemVectorType; /// Definition of the IndexType typedef std::size_t IndexType; /// Definition of the size type typedef std::size_t SizeType; ///@} ///@name Life Cycle ///@{ //* Constructor. explicit ResidualCriteria() : BaseType() { } /** * @brief Default constructor. (with parameters) * @param ThisParameters The configuration parameters */ explicit ResidualCriteria(Kratos::Parameters ThisParameters) : BaseType() { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); this->mActualizeRHSIsNeeded = true; } //* Constructor. explicit ResidualCriteria( TDataType NewRatioTolerance, TDataType AlwaysConvergedNorm) : BaseType(), mRatioTolerance(NewRatioTolerance), mAlwaysConvergedNorm(AlwaysConvergedNorm) { this->mActualizeRHSIsNeeded = true; } //* Copy constructor. explicit ResidualCriteria( ResidualCriteria const& rOther ) :BaseType(rOther) ,mRatioTolerance(rOther.mRatioTolerance) ,mInitialResidualNorm(rOther.mInitialResidualNorm) ,mCurrentResidualNorm(rOther.mCurrentResidualNorm) ,mAlwaysConvergedNorm(rOther.mAlwaysConvergedNorm) ,mReferenceDispNorm(rOther.mReferenceDispNorm) { this->mActualizeRHSIsNeeded = true; } //* Destructor. ~ResidualCriteria() override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Create method * @param ThisParameters The configuration parameters */ typename BaseType::Pointer Create(Parameters ThisParameters) const override { return Kratos::make_shared<ClassType>(ThisParameters); } /** * @brief Criterias that need to be called after getting the solution * @details Compute relative and absolute error. * @param rModelPart Reference to the ModelPart containing the problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual + reactions) * @return true if convergence is achieved, false otherwise */ bool PostCriteria( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { const SizeType size_b = TSparseSpace::Size(rb); if (size_b != 0) { //if we are solving for something SizeType size_residual; CalculateResidualNorm(rModelPart, mCurrentResidualNorm, size_residual, rDofSet, rb); TDataType ratio = 0.0; if(mInitialResidualNorm < std::numeric_limits<TDataType>::epsilon()) { ratio = 0.0; } else { ratio = mCurrentResidualNorm/mInitialResidualNorm; } const TDataType float_size_residual = static_cast<TDataType>(size_residual); const TDataType absolute_norm = (mCurrentResidualNorm/float_size_residual); KRATOS_INFO_IF("RESIDUAL CRITERION", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << " :: [ Initial residual norm = " << mInitialResidualNorm << "; Current residual norm = " << mCurrentResidualNorm << "]" << std::endl; KRATOS_INFO_IF("RESIDUAL CRITERION", this->GetEchoLevel() > 0 && rModelPart.GetCommunicator().MyPID() == 0) << " :: [ Obtained ratio = " << ratio << "; Expected ratio = " << mRatioTolerance << "; Absolute norm = " << absolute_norm << "; Expected norm = " << mAlwaysConvergedNorm << "]" << std::endl; rModelPart.GetProcessInfo()[CONVERGENCE_RATIO] = ratio; rModelPart.GetProcessInfo()[RESIDUAL_NORM] = absolute_norm; if (ratio <= mRatioTolerance || absolute_norm < mAlwaysConvergedNorm) { KRATOS_INFO_IF("RESIDUAL CRITERION", this->GetEchoLevel() > 0 && rModelPart.GetCommunicator().MyPID() == 0) << "Convergence is achieved" << std::endl; return true; } else { return false; } } else { return true; } } /** * @brief This function initialize the convergence criteria * @param rModelPart Reference to the ModelPart containing the problem. (unused) */ void Initialize(ModelPart& rModelPart) override { BaseType::Initialize(rModelPart); KRATOS_ERROR_IF(rModelPart.IsDistributed() && rModelPart.NumberOfMasterSlaveConstraints() > 0) << "This Criteria does not yet support constraints in MPI!" << std::endl; } /** * @brief This function initializes the solution step * @param rModelPart Reference to the ModelPart containing the problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual + reactions) */ void InitializeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { BaseType::InitializeSolutionStep(rModelPart, rDofSet, rA, rDx, rb); // Filling mActiveDofs when MPC exist if (rModelPart.NumberOfMasterSlaveConstraints() > 0) { ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet); } SizeType size_residual; CalculateResidualNorm(rModelPart, mInitialResidualNorm, size_residual, rDofSet, rb); } /** * @brief This function finalizes the solution step * @param rModelPart Reference to the ModelPart containing the problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param A System matrix (unused) * @param Dx Vector of results (variations on nodal variables) * @param b RHS vector (residual + reactions) */ void FinalizeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { BaseType::FinalizeSolutionStep(rModelPart, rDofSet, rA, rDx, rb); } /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors * @return The default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "residual_criteria", "residual_absolute_tolerance" : 1.0e-4, "residual_relative_tolerance" : 1.0e-9 })"); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "residual_criteria"; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualCriteria"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief This method computes the norm of the residual * @details It checks if the dof is fixed * @param rModelPart Reference to the ModelPart containing the problem. * @param rResidualSolutionNorm The norm of the residual * @param rDofNum The number of DoFs * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rb RHS vector (residual + reactions) */ virtual void CalculateResidualNorm( ModelPart& rModelPart, TDataType& rResidualSolutionNorm, SizeType& rDofNum, DofsArrayType& rDofSet, const TSystemVectorType& rb ) { // Initialize TDataType residual_solution_norm = TDataType(); SizeType dof_num = 0; // Auxiliar values TDataType residual_dof_value = 0.0; const auto it_dof_begin = rDofSet.begin(); const int number_of_dof = static_cast<int>(rDofSet.size()); // Loop over Dofs if (rModelPart.NumberOfMasterSlaveConstraints() > 0) { #pragma omp parallel for firstprivate(residual_dof_value) reduction(+:residual_solution_norm, dof_num) for (int i = 0; i < number_of_dof; i++) { auto it_dof = it_dof_begin + i; const IndexType dof_id = it_dof->EquationId(); if (mActiveDofs[dof_id] == 1) { residual_dof_value = TSparseSpace::GetValue(rb,dof_id); residual_solution_norm += std::pow(residual_dof_value, 2); dof_num++; } } } else { #pragma omp parallel for firstprivate(residual_dof_value) reduction(+:residual_solution_norm, dof_num) for (int i = 0; i < number_of_dof; i++) { auto it_dof = it_dof_begin + i; if (!it_dof->IsFixed()) { const IndexType dof_id = it_dof->EquationId(); residual_dof_value = TSparseSpace::GetValue(rb,dof_id); residual_solution_norm += std::pow(residual_dof_value, 2); dof_num++; } } } rDofNum = dof_num; rResidualSolutionNorm = std::sqrt(residual_solution_norm); } /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); mAlwaysConvergedNorm = ThisParameters["residual_absolute_tolerance"].GetDouble(); mRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble(); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ TDataType mRatioTolerance; /// The ratio threshold for the norm of the residual TDataType mInitialResidualNorm; /// The reference norm of the residual TDataType mCurrentResidualNorm; /// The current norm of the residual TDataType mAlwaysConvergedNorm; /// The absolute value threshold for the norm of the residual TDataType mReferenceDispNorm; /// The norm at the beginning of the iterations std::vector<int> mActiveDofs; /// This vector contains the dofs that are active ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class ClassName ///@} ///@name Type Definitions ///@{ ///@} } // namespace Kratos. #endif // KRATOS_NEW_DISPLACEMENT_CRITERIA defined
GB_unop__identity_fp32_int32.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_fp32_int32) // op(A') function: GB (_unop_tran__identity_fp32_int32) // C type: float // A type: int32_t // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ float z = (float) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp32_int32) ( float *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] ; float z = (float) 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] ; float z = (float) 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_fp32_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
Regression.h
#ifndef SYCL_ML_LIB_REGRESSION_H #define SYCL_ML_LIB_REGRESSION_H #include<CL/sycl.hpp> #include<SYCL/device_selector.h> #include <random> #include <vector> #include <iostream> #include "Kernels/RegressionKernel.h" #include "Device.h" using namespace cl::sycl; using namespace std; vector<size_t> getPowersofTwo(size_t input_size){ vector<size_t> powers; while(input_size > 0){ powers.push_back(input_size % 2); input_size = input_size/2; } return powers; } class LinearRegression{ public: LinearRegression(size_t input_size){ std::random_device device{}; std::normal_distribution<float> distribution{0, 1}; std::ranlux48 generator{device()}; this->num_features = input_size; this->bias = 0.5f; this->weights = (float*)malloc(this->num_features * sizeof(float )); #pragma omp parallel for for(int i=0; i<input_size; i++){ *(this->weights + i) = distribution(generator); } this->use_sycl = 0; } void sycl(std::string Target_Device = " "){ this->use_sycl = 1; this->selector = getDeviceSelector(Target_Device, this->selector); this->Queue = queue(*(*this->selector)); } void setDevice(std::string Target_Device){ this->selector = getDeviceSelector(Target_Device, this->selector); this->Queue = queue(*(*this->selector)); } float forward(vector<float> input){ //To be replaced by dot in BLAS once installed this->current_input = input.data(); float output = 0.0f; if (this->use_sycl){ if(!(this->num_features & (this->num_features -1))) { std::cout<<"Found true"; output = RegressionForward(input.data(), this->weights, this->bias, size_t(input.size()), this->Queue); } else{ vector<size_t> powers = getPowersofTwo(this->num_features); float sum = 0.0f; size_t offset = 0; for(size_t power: powers){ std::vector<float> subvector_weight(power); std::vector<float> subvector_input(power); std::copy(this->weights+offset, this->weights + power, subvector_weight.begin()); std::copy(this->current_input + offset, this->current_input + power, subvector_input.begin()); sum += RegressionForward(subvector_input.data(), subvector_weight.data(), 0.0f , power, this->Queue); offset = offset + power; } sum = sum + this->bias; output = sum; } } else{ float* _input = input.data(); output = 0.0f; float intermediate = 0.0f; int i =0; #pragma omp parallel default(none) private(intermediate) shared(result, model_weights, _input) { #pragma omp for for (i = 0; i < this->num_features; ++i) { intermediate = intermediate + *(this->weights + i) * *(_input + i); } #pragma omp atomic output += intermediate; } output = output + this->bias; } return output; } //float* weights, float* inputs, size_t num_features, float lr, float loss void backward(float loss, float learning_rate){ if(this->use_sycl){ updateWeights(this->weights, this->current_input, this->num_features, learning_rate, loss); } else{ #pragma omp parallel for for (int i = 0; i < this->num_features; ++i) { *(this->weights + i) = *(this->weights + i) - 2*learning_rate*loss*(*(this->current_input + i)); } } this->bias = this->bias - 2*learning_rate*loss; } template<typename Func> void backward(float loss, float learning_rate, Func loss_grad_func, float output, float target){ if(this->use_sycl){ updateWeights_custom(this->weights, this->current_input, this->num_features, learning_rate, loss, output, target, loss_grad_func); } else { #pragma omp parallel for for (int i = 0; i < this->num_features; ++i) { *(this->weights + i) = *(this->weights + i) - learning_rate * loss_grad_func(*(this->current_input + i), output, target); } } this->bias = this->bias - learning_rate*loss_grad_func(this->bias, output, target); } void setWeights(float value){ vector<float> weight_vector(this->num_features, value); std::copy(weight_vector.begin(), weight_vector.end(), this->weights); } float* getWeight() noexcept{ return this->weights; } private: int num_features; float* weights; float bias; float* current_input; int use_sycl; queue Queue; unique_ptr<device_selector*> selector = std::make_unique<device_selector*>(new default_selector); }; class LogisticRegression{ public: LogisticRegression(size_t input_size){ std::random_device device{}; std::normal_distribution<float> distribution{0, 1}; std::ranlux48 generator{device()}; this->num_features = input_size; this->bias = 0.5f; this->weights = (float*)malloc(this->num_features * sizeof(float )); #pragma omp parallel for for(int i=0; i<input_size; i++){ *(this->weights + i) = distribution(generator); } this->use_sycl = 0; } void sycl(std::string Target_Device = " "){ this->selector = getDeviceSelector(Target_Device, this->selector); this->Queue = queue(*(*this->selector)); this->use_sycl = 1; } template<typename Func> float forward(vector<float> input, Func activation){ //To be replaced by dot in BLAS once installed this->current_input = input.data(); float output = 0.0f; if (this->use_sycl){ if(!(this->num_features & (this->num_features -1))) { std::cout<<"Found true"; output = RegressionForward(input.data(), this->weights, this->bias, size_t(input.size()), this->Queue); } else{ vector<size_t> powers = getPowersofTwo(this->num_features); float sum = 0.0f; size_t offset = 0; for(size_t power: powers){ std::vector<float> subvector_weight(power); std::vector<float> subvector_input(power); std::copy(this->weights+offset, this->weights + power, subvector_weight.begin()); std::copy(this->current_input + offset, this->current_input + power, subvector_input.begin()); sum += RegressionForward(subvector_input.data(), subvector_weight.data(), 0.0f , power, this->Queue); offset = offset + power; } sum = sum + this->bias; output = sum; } } else{ float* _input = input.data(); output = 0.0f; float intermediate = 0.0f; int i =0; #pragma omp parallel default(none) private(intermediate) shared(result, model_weights, _input) { #pragma omp for for (i = 0; i < this->num_features; ++i) { intermediate = intermediate + *(this->weights + i) * *(_input + i); } #pragma omp atomic output += intermediate; } output = output + this->bias; } return activation(output); } template<typename Func> void backward(float loss, float learning_rate, Func loss_grad_func, float output, float target){ if(this->use_sycl){ updateWeights_custom(this->weights, this->current_input, this->num_features, learning_rate, loss, output, target, loss_grad_func); } else { #pragma omp parallel for for (int i = 0; i < this->num_features; ++i) { *(this->weights + i) = *(this->weights + i) - learning_rate * loss_grad_func(*(this->current_input + i), output, target); } } this->bias = this->bias - learning_rate*loss_grad_func(this->bias, output, target); } void setWeights(float value){ vector<float> weight_vector(this->num_features, value); std::copy(weight_vector.begin(), weight_vector.end(), this->weights); } float* getWeight() noexcept{ return this->weights; } void setDevice(std::string Target_Device){ this->selector = getDeviceSelector(Target_Device, this->selector); this->Queue = queue(*(*this->selector)); } private: int num_features; float* weights; float bias; float* current_input; int use_sycl; queue Queue; unique_ptr<device_selector*> selector = std::make_unique<device_selector*>(new default_selector); }; #endif //SYCL_ML_LIB_REGRESSION_H
hmacSHA384_fmt_plug.c
/* * This software is Copyright (c) 2012 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * Based on hmac-md5 by Bartavelle */ #if FMT_EXTERNS_H extern struct fmt_main fmt_hmacSHA384; #elif FMT_REGISTERS_H john_register_one(&fmt_hmacSHA384); #else #include "sha2.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #define OMP_SCALE 64 #endif #include "memdbg.h" #define FORMAT_LABEL "HMAC-SHA384" #define FORMAT_NAME "" #if ARCH_BITS >= 64 #define ALGORITHM_NAME "password is key, SHA384 64/" ARCH_BITS_STR " " SHA2_LIB #else #define ALGORITHM_NAME "password is key, SHA384 32/" ARCH_BITS_STR " " SHA2_LIB #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define PAD_SIZE 128 #define BINARY_SIZE (384/8) #define BINARY_ALIGN 4 #define SALT_SIZE PAD_SIZE #define SALT_ALIGN 1 #define CIPHERTEXT_LENGTH (SALT_SIZE + 1 + BINARY_SIZE * 2) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"what do ya want for nothing?#af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649", "Jefe"}, {"Beppe#Grillo#8361922C63506E53714F8A8491C6621A76CF0FD6DFEAD91BF59B420A23DFF2745C0A0D5E142D4F937E714EA8C228835B", "Io credo nella reincarnazione e sono di Genova; per cui ho fatto testamento e mi sono lasciato tutto a me."}, {NULL} }; static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD (*crypt_key)[BINARY_SIZE / sizeof(ARCH_WORD) + 1]; static unsigned char (*opad)[PAD_SIZE]; static unsigned char (*ipad)[PAD_SIZE]; static unsigned char cursalt[SALT_SIZE]; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_plain = mem_calloc_tiny(sizeof(*saved_plain) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_key = mem_calloc_tiny(sizeof(*crypt_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); opad = mem_calloc_tiny(sizeof(*opad) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); ipad = mem_calloc_tiny(sizeof(*opad) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int valid(char *ciphertext, struct fmt_main *self) { int pos, i; char *p; p = strrchr(ciphertext, '#'); // allow # in salt if (!p || p > &ciphertext[strlen(ciphertext)-1]) return 0; i = (int)(p - ciphertext); if(i > SALT_SIZE) return 0; pos = i+1; if (strlen(ciphertext+pos) != BINARY_SIZE*2) return 0; for (i = pos; i < BINARY_SIZE*2+pos; i++) { if (!( (('0' <= ciphertext[i])&&(ciphertext[i] <= '9')) || (('a' <= ciphertext[i])&&(ciphertext[i] <= 'f')) || (('A' <= ciphertext[i])&&(ciphertext[i] <= 'F')))) return 0; } return 1; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[CIPHERTEXT_LENGTH + 1]; strnzcpy(out, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(strrchr(out, '#')); return out; } static int get_hash_0(int index) { return crypt_key[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_key[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_key[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_key[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_key[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_key[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_key[index][0] & 0x7ffffff; } static void set_salt(void *salt) { memcpy(cursalt, salt, SALT_SIZE); } static void set_key(char *key, int index) { int len; int i; len = strlen(key); memset(ipad[index], 0x36, PAD_SIZE); memset(opad[index], 0x5C, PAD_SIZE); #if PLAINTEXT_LENGTH > PAD_SIZE memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; if (len > PAD_SIZE) { SHA512_CTX ctx; unsigned char k0[BINARY_SIZE]; SHA384_Init( &ctx ); SHA384_Update( &ctx, key, len); SHA384_Final( k0, &ctx); len = BINARY_SIZE; for(i=0;i<len;i++) { ipad[index][i] ^= k0[i]; opad[index][i] ^= k0[i]; } } else #endif /* PLAINTEXT_LENGTH > PAD_SIZE */ for(i=0;i<len;i++) { ipad[index][i] ^= key[i]; opad[index][i] ^= key[i]; } } static char *get_key(int index) { #if PLAINTEXT_LENGTH > PAD_SIZE return saved_plain[index]; #else unsigned int i; for(i=0;i<PLAINTEXT_LENGTH;i++) saved_plain[index][i] = ipad[index][ i ] ^ 0x36; saved_plain[index][i] = 0; return (char*) saved_plain[index]; #endif } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_key[index], BINARY_SIZE)) return 1; return 0; } static int cmp_exact(char *source, int count) { return (1); } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_key[index], BINARY_SIZE); } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { SHA512_CTX ctx; SHA384_Init( &ctx ); SHA384_Update( &ctx, ipad[index], PAD_SIZE ); SHA384_Update( &ctx, cursalt, strlen( (char*) cursalt) ); SHA384_Final( (unsigned char*) crypt_key[index], &ctx); SHA384_Init( &ctx ); SHA384_Update( &ctx, opad[index], PAD_SIZE ); SHA384_Update( &ctx, crypt_key[index], BINARY_SIZE); SHA384_Final( (unsigned char*) crypt_key[index], &ctx); } return count; } static void *binary(char *ciphertext) { static union toalign { unsigned char c[BINARY_SIZE]; ARCH_WORD_32 a[1]; } a; unsigned char *realcipher = a.c; int i,pos; for(i=strlen(ciphertext);ciphertext[i]!='#';i--); // allow # in salt pos=i+1; for(i=0;i<BINARY_SIZE;i++) realcipher[i] = atoi16[ARCH_INDEX(ciphertext[i*2+pos])]*16 + atoi16[ARCH_INDEX(ciphertext[i*2+1+pos])]; return (void*)realcipher; } static void *salt(char *ciphertext) { static unsigned char salt[SALT_SIZE]; memset(salt, 0, sizeof(salt)); // allow # in salt memcpy(salt, ciphertext, strrchr(ciphertext, '#') - ciphertext); return salt; } struct fmt_main fmt_hmacSHA384 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, binary, salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
LAGraph_BF_full2.c
//------------------------------------------------------------------------------ // LAGraph_BF_full2.c: Bellman-Ford single-source shortest paths, returns tree, // while diagonal of input matrix A needs not to be explicit 0, using the // frontier idea from Roi Lipman //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2019 LAGraph Contributors. (see Contributors.txt for a full list of Contributors; see ContributionInstructions.txt for information on how you can Contribute to this project). All Rights Reserved. NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. Released under a BSD license, please see the LICENSE file distributed with this Software or contact permission@sei.cmu.edu for full terms. Created, in part, with funding and support from the United States Government. (see Acknowledgments.txt file). This program includes and/or can make use of certain third party source code, object code, documentation and other files ("Third Party Software"). See LICENSE file for more details. */ //------------------------------------------------------------------------------ // LAGraph_BF_full2: Bellman-Ford single source shortest paths, returning both // the path lengths and the shortest-path tree. contributed by Jinhao Chen and // Tim Davis, Texas A&M. // LAGraph_BF_full2 performs a Bellman-Ford to find out shortest path, parent // nodes along the path and the hops (number of edges) in the path from given // source vertex s in the range of [0, n) on graph given as matrix A with size // n*n. The sparse matrix A has entry A(i, j) if there is an edge from vertex i // to vertex j with weight w, then A(i, j) = w. // TODO: think about the return values // LAGraph_BF_full2 returns GrB_SUCCESS if it succeeds. In this case, there // are no negative-weight cycles in the graph, and d, pi, and h are returned. // The vector d has d(k) as the shortest distance from s to k. pi(k) = p+1, // where p is the parent node of k-th node in the shortest path. In particular, // pi(s) = 0. h(k) = hop(s, k), the number of edges from s to k in the shortest // path. // If the graph has a negative-weight cycle, GrB_NO_VALUE is returned, and the // GrB_Vectors d(k), pi(k) and h(k) (i.e., *pd_output, *ppi_output and // *ph_output respectively) will be NULL when negative-weight cycle detected. // Otherwise, other errors such as GrB_OUT_OF_MEMORY, GrB_INVALID_OBJECT, and // so on, can be returned, if these errors are found by the underlying // GrB_* functions. //------------------------------------------------------------------------------ #include "BF_test.h" #define LAGRAPH_FREE_WORK \ { \ GrB_free(&d); \ GrB_free(&dtmp); \ GrB_free(&dfrontier); \ GrB_free(&Atmp); \ GrB_free(&BF_Tuple3); \ GrB_free(&BF_lMIN_Tuple3); \ GrB_free(&BF_PLUSrhs_Tuple3); \ GrB_free(&BF_EQ_Tuple3); \ GrB_free(&BF_lMIN_Tuple3_Monoid); \ GrB_free(&BF_lMIN_PLUSrhs_Tuple3); \ LAGRAPH_FREE (I); \ LAGRAPH_FREE (J); \ LAGRAPH_FREE (w); \ LAGRAPH_FREE (W); \ LAGRAPH_FREE (h); \ LAGRAPH_FREE (pi); \ } #define LAGRAPH_FREE_ALL \ { \ LAGRAPH_FREE_WORK \ GrB_free (pd_output); \ GrB_free (ppi_output); \ GrB_free (ph_output); \ } //------------------------------------------------------------------------------ // data type for each entry of the adjacent matrix A and "distance" vector d; // <INFINITY,INFINITY,INFINITY> corresponds to nonexistence of a path, and // the value <0, 0, NULL> corresponds to a path from a vertex to itself //------------------------------------------------------------------------------ typedef struct { double w; // w corresponds to a path weight. GrB_Index h; // h corresponds to a path size or number of hops. GrB_Index pi;// pi corresponds to the penultimate vertex along a path. // vertex indexed as 1, 2, 3, ... , V, and pi = 0 (as nil) // for u=v, and pi = UINT64_MAX (as inf) for (u,v) not in E } BF_Tuple3_struct; //------------------------------------------------------------------------------ // 2 binary functions, z=f(x,y), where Tuple3xTuple3 -> Tuple3 //------------------------------------------------------------------------------ void BF_lMIN2 ( BF_Tuple3_struct *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { if (x->w < y->w || (x->w == y->w && x->h < y->h) || (x->w == y->w && x->h == y->h && x->pi < y->pi)) { if (z != x) { *z = *x; } } else { *z = *y; } } void BF_PLUSrhs2 ( BF_Tuple3_struct *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { z->w = x->w + y->w; z->h = x->h + y->h; if (x->pi != UINT64_MAX && y->pi != 0) { z->pi = y->pi; } else { z->pi = x->pi; } } void BF_EQ ( bool *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { if (x->w == y->w && x->h == y->h && x->pi == y->pi) { *z = true; } else { *z = false; } } // Given a n-by-n adjacency matrix A and a source vertex s. // If there is no negative-weight cycle reachable from s, return the distances // of shortest paths from s and parents along the paths as vector d. Otherwise, // returns d=NULL if there is a negtive-weight cycle. // pd_output is pointer to a GrB_Vector, where the i-th entry is d(s,i), the // sum of edges length in the shortest path // ppi_output is pointer to a GrB_Vector, where the i-th entry is pi(i), the // parent of i-th vertex in the shortest path // ph_output is pointer to a GrB_Vector, where the i-th entry is h(s,i), the // number of edges from s to i in the shortest path // A has weights on corresponding entries of edges // s is given index for source vertex GrB_Info LAGraph_BF_full2 ( GrB_Vector *pd_output, //the pointer to the vector of distance GrB_Vector *ppi_output, //the pointer to the vector of parent GrB_Vector *ph_output, //the pointer to the vector of hops const GrB_Matrix A, //matrix for the graph const GrB_Index s //given index of the source ) { GrB_Info info; // tmp vector to store distance vector after n (i.e., V) loops GrB_Vector d = NULL, dtmp = NULL, dfrontier = NULL; GrB_Matrix Atmp = NULL; GrB_Type BF_Tuple3; GrB_BinaryOp BF_lMIN_Tuple3; GrB_BinaryOp BF_PLUSrhs_Tuple3; GrB_BinaryOp BF_EQ_Tuple3; GrB_Monoid BF_lMIN_Tuple3_Monoid; GrB_Semiring BF_lMIN_PLUSrhs_Tuple3; GrB_Index nrows, ncols, n, nz; // n = # of row/col, nz = # of nnz in graph GrB_Index *I = NULL, *J = NULL; // for col/row indices of entries from A GrB_Index *h = NULL, *pi = NULL; double *w = NULL; BF_Tuple3_struct *W = NULL; if (A == NULL || pd_output == NULL || ppi_output == NULL || ph_output == NULL) { // required argument is missing LAGRAPH_ERROR ("required arguments are NULL", GrB_NULL_POINTER) ; } *pd_output = NULL; *ppi_output = NULL; *ph_output = NULL; LAGr_Matrix_nrows (&nrows, A) ; LAGr_Matrix_ncols (&ncols, A) ; LAGr_Matrix_nvals (&nz, A); if (nrows != ncols) { // A must be square LAGRAPH_ERROR ("A must be square", GrB_INVALID_VALUE) ; } n = nrows; if (s >= n || s < 0) { LAGRAPH_ERROR ("invalid value for source vertex s", GrB_INVALID_VALUE); } //-------------------------------------------------------------------------- // create all GrB_Type GrB_BinaryOp GrB_Monoid and GrB_Semiring //-------------------------------------------------------------------------- // GrB_Type LAGr_Type_new(&BF_Tuple3, sizeof(BF_Tuple3_struct)); // GrB_BinaryOp LAGr_BinaryOp_new(&BF_EQ_Tuple3, (LAGraph_binary_function) (&BF_EQ), GrB_BOOL, BF_Tuple3, BF_Tuple3); LAGr_BinaryOp_new(&BF_lMIN_Tuple3, (LAGraph_binary_function) (&BF_lMIN2), BF_Tuple3, BF_Tuple3, BF_Tuple3); LAGr_BinaryOp_new(&BF_PLUSrhs_Tuple3, (LAGraph_binary_function)(&BF_PLUSrhs2), BF_Tuple3, BF_Tuple3, BF_Tuple3); // GrB_Monoid BF_Tuple3_struct BF_identity = (BF_Tuple3_struct) { .w = INFINITY, .h = UINT64_MAX, .pi = UINT64_MAX }; LAGRAPH_OK(GrB_Monoid_new_UDT(&BF_lMIN_Tuple3_Monoid, BF_lMIN_Tuple3, &BF_identity)); //GrB_Semiring LAGr_Semiring_new(&BF_lMIN_PLUSrhs_Tuple3, BF_lMIN_Tuple3_Monoid, BF_PLUSrhs_Tuple3); //-------------------------------------------------------------------------- // allocate arrays used for tuplets //-------------------------------------------------------------------------- I = LAGraph_malloc (nz, sizeof(GrB_Index)) ; J = LAGraph_malloc (nz, sizeof(GrB_Index)) ; w = LAGraph_malloc (nz, sizeof(double)) ; W = LAGraph_malloc (nz, sizeof(BF_Tuple3_struct)) ; if (I == NULL || J == NULL || w == NULL || W == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // create matrix Atmp based on A, while its entries become BF_Tuple3 type //-------------------------------------------------------------------------- LAGRAPH_OK(GrB_Matrix_extractTuples_FP64(I, J, w, &nz, A)); int nthreads = LAGraph_get_nthreads ( ) ; printf ("nthreads %d\n", nthreads) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (GrB_Index k = 0; k < nz; k++) { if (w[k] == 0) //diagonal entries { W[k] = (BF_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; } else { W[k] = (BF_Tuple3_struct) { .w = w[k], .h = 1, .pi = I[k] + 1 }; } } LAGr_Matrix_new(&Atmp, BF_Tuple3, n, n); LAGRAPH_OK(GrB_Matrix_build_UDT(Atmp, I, J, W, nz, BF_lMIN_Tuple3)); LAGRAPH_FREE (I); LAGRAPH_FREE (J); LAGRAPH_FREE (W); LAGRAPH_FREE (w); //-------------------------------------------------------------------------- // create and initialize "distance" vector d //-------------------------------------------------------------------------- LAGr_Vector_new(&d, BF_Tuple3, n); // initial distance from s to itself BF_Tuple3_struct d0 = (BF_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; LAGRAPH_OK(GrB_Vector_setElement_UDT(d, &d0, s)); //-------------------------------------------------------------------------- // start the Bellman Ford process //-------------------------------------------------------------------------- // copy d to dtmp in order to create a same size of vector LAGr_Vector_dup(&dtmp, d); LAGr_Vector_dup(&dfrontier, d); bool same= false; // variable indicating if d == dtmp int64_t iter = 0; // number of iterations // terminate when no new path is found or more than V-1 loops while (!same && iter < n - 1) { // execute semiring on d and A, and save the result to dtmp LAGr_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL); // dtmp[i] = min(d[i], dfrontier[i]). GrB_eWiseAdd_Vector_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); LAGRAPH_OK (LAGraph_Vector_isequal(&same, dtmp, d, BF_EQ_Tuple3)); if (!same) { GrB_Vector ttmp = dtmp; dtmp = d; d = ttmp; } iter ++; } // check for negative-weight cycle only when there was a new path in the // last loop, otherwise, there can't be a negative-weight cycle. if (!same) { // execute semiring again to check for negative-weight cycle LAGr_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL); // dtmp[i] = min(d[i], dfrontier[i]). GrB_eWiseAdd_Vector_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); // if d != dtmp, then there is a negative-weight cycle in the graph LAGRAPH_OK (LAGraph_Vector_isequal(&same, dtmp, d, BF_EQ_Tuple3)); if (!same) { // printf("A negative-weight cycle found. \n"); LAGRAPH_FREE_ALL; return (GrB_NO_VALUE) ; } } //-------------------------------------------------------------------------- // extract tuple from "distance" vector d and create GrB_Vectors for output //-------------------------------------------------------------------------- I = LAGraph_malloc (n, sizeof(GrB_Index)) ; W = LAGraph_malloc (n, sizeof(BF_Tuple3_struct)) ; w = LAGraph_malloc (n, sizeof(double)) ; h = LAGraph_malloc (n, sizeof(GrB_Index)) ; pi = LAGraph_malloc (n, sizeof(GrB_Index)) ; if (I == NULL || W == NULL || w == NULL || h == NULL || pi == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } LAGRAPH_OK(GrB_Vector_extractTuples_UDT (I, (void *) W, &nz, d)); for (GrB_Index k = 0; k < nz; k++) { w [k] = W[k].w ; h [k] = W[k].h ; pi[k] = W[k].pi; } LAGr_Vector_new(pd_output, GrB_FP64, n); LAGr_Vector_new(ppi_output, GrB_UINT64, n); LAGr_Vector_new(ph_output, GrB_UINT64, n); LAGr_Vector_build (*pd_output , I, w , nz,GrB_MIN_FP64 ); LAGr_Vector_build (*ppi_output, I, pi, nz,GrB_MIN_UINT64); LAGr_Vector_build (*ph_output , I, h , nz,GrB_MIN_UINT64); LAGRAPH_FREE_WORK; return (GrB_SUCCESS) ; }
GB_unop__abs_uint64_uint64.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__abs_uint64_uint64) // op(A') function: GB (_unop_tran__abs_uint64_uint64) // C type: uint64_t // A type: uint64_t // cast: uint64_t cij = aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint64_t // 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 = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_uint64_uint64) ( uint64_t *Cx, // Cx and Ax may be aliased const uint64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; uint64_t z = aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint64_t aij = Ax [p] ; uint64_t z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_uint64_uint64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_assign_zombie2.c
//------------------------------------------------------------------------------ // GB_assign_zombie2: delete all entries in C(i,:) for GB_assign //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C(i,:)<!> = anything: GrB_Row_assign or GrB_Col_assign with an empty // complemented mask requires all entries in C(i,:) to be deleted. // C must be sparse or hypersparse. // C->iso is not affected. #include "GB_assign.h" #include "GB_assign_zombie.h" void GB_assign_zombie2 ( GrB_Matrix C, const int64_t i, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_FULL (C)) ; ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (GB_ZOMBIES_OK (C)) ; ASSERT (!GB_JUMBLED (C)) ; // binary search is used ASSERT (!GB_PENDING (C)) ; //-------------------------------------------------------------------------- // get C //-------------------------------------------------------------------------- const int64_t *restrict Cp = C->p ; int64_t *restrict Ci = C->i ; const int64_t Cnvec = C->nvec ; int64_t nzombies = C->nzombies ; const int64_t zorig = nzombies ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (Cnvec, chunk, nthreads_max) ; int ntasks = (nthreads == 1) ? 1 : (64 * nthreads) ; //-------------------------------------------------------------------------- // C(i,:) = empty //-------------------------------------------------------------------------- int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { int64_t kfirst, klast ; GB_PARTITION (kfirst, klast, Cnvec, taskid, ntasks) ; for (int64_t k = kfirst ; k < klast ; k++) { //------------------------------------------------------------------ // find C(i,j) //------------------------------------------------------------------ int64_t pC = Cp [k] ; int64_t pC_end = Cp [k+1] ; int64_t pright = pC_end - 1 ; bool found, is_zombie ; GB_BINARY_SEARCH_ZOMBIE (i, Ci, pC, pright, found, zorig, is_zombie) ; //------------------------------------------------------------------ // if found and not a zombie, mark it as a zombie //------------------------------------------------------------------ if (found && !is_zombie) { ASSERT (i == Ci [pC]) ; nzombies++ ; Ci [pC] = GB_FLIP (i) ; } } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- C->nzombies = nzombies ; }
test_core.c
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (C) 2007-2017 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or * modify it under the terms of the 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. * * RELIC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with RELIC. If not, see <http://www.gnu.org/licenses/>. */ /** * @file * * Tests for configuration management. * * @ingroup test */ #include <stdio.h> #include <relic.h> #include <relic_test.h> #if MULTI == PTHREAD void *master(void *ptr) { int *code = (int *)ptr; core_init(); THROW(ERR_NO_MEMORY); if (err_get_code() != STS_ERR) { *code = STS_ERR; } else { *code = STS_OK; } core_clean(); return NULL; } void *tester(void *ptr) { int *code = (int *)ptr; core_init(); if (err_get_code() != STS_OK) { *code = STS_ERR; } else { *code = STS_OK; } core_clean(); return NULL; } #endif int main(void) { int code = STS_ERR; /* Initialize library with default configuration. */ if (core_init() != STS_OK) { core_clean(); return 1; } util_banner("Tests for the CORE module:\n", 0); TEST_ONCE("the library context is consistent") { TEST_ASSERT(core_get() != NULL, end); } TEST_END; TEST_ONCE("switching the library context is correct") { ctx_t new_ctx, *old_ctx; /* Backup the old context. */ old_ctx = core_get(); /* Switch the library context. */ core_set(&new_ctx); /* Reinitialize library with new context. */ core_init(); /* Run function to manipulate the library context. */ THROW(ERR_NO_MEMORY); core_set(old_ctx); TEST_ASSERT(err_get_code() == STS_OK, end); core_set(&new_ctx); TEST_ASSERT(err_get_code() == STS_ERR, end); /* Now we need to finalize the new context. */ core_clean(); /* And restore the original context. */ core_set(old_ctx); } TEST_END; code = STS_OK; #if MULTI == OPENMP TEST_ONCE("library context is thread-safe") { omp_set_num_threads(CORES); #pragma omp parallel shared(code) { if (omp_get_thread_num() == 0) { THROW(ERR_NO_MEMORY); if (err_get_code() != STS_ERR) { code = STS_ERR; } } else { core_init(); if (err_get_code() != STS_OK) { code = STS_ERR; } core_clean(); } } TEST_ASSERT(code == STS_OK, end); } TEST_END; #endif #if MULTI == PTHREAD TEST_ONCE("library context is thread-safe") { pthread_t thread[CORES]; int result[CORES] = { STS_OK }; for (int i = 0; i < CORES; i++) { if (i == 0) { if (pthread_create(&(thread[0]), NULL, master, &(result[0]))) { code = STS_ERR; } } else { if (pthread_create(&(thread[i]), NULL, tester, &(result[i]))) { code = STS_ERR; } } if (result[i] != STS_OK) { code = STS_ERR; } } for (int i = 0; i < CORES; i++) { if (pthread_join(thread[i], NULL)) { code = STS_ERR; } } TEST_ASSERT(code == STS_OK, end); } TEST_END; #endif util_banner("All tests have passed.\n", 0); end: core_clean(); return code; }
parallel-if.c
// Test if clause handling // number of threads should be set to 1 if the if-clause's expression evaluates to be false #include <assert.h> #include <stdio.h> #include <omp.h> int main(void) { int i=0; #pragma omp parallel if(i == 0) { printf("Mutual exclusive output 1.\n"); } #pragma omp parallel if(i != 0) { #pragma omp single { assert (omp_get_num_threads() == 1 ); } printf("Mutual exclusive output 2.\n"); } return 0; }
GB_unop__exp2_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__exp2_fc64_fc64 // op(A') function: GB_unop_tran__exp2_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_cexp2 (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cexp2 (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_cexp2 (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EXP2 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__exp2_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] = GB_cexp2 (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__exp2_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
effect.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT % % E F F E C T % % EEE FFF FFF EEE C T % % E F F E C T % % EEEEE F F EEEEE CCCC T % % % % % % MagickCore Image Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2014 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 "MagickCore/studio.h" #include "MagickCore/accelerate.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/morphology.h" #include "MagickCore/morphology-private.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/threshold.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveBlurImage() adaptively blurs the image by blurring less % intensely near image edges and more intensely far from edges. We blur the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveBlurImage() selects a suitable radius for you. % % The format of the AdaptiveBlurImage method is: % % Image *AdaptiveBlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define AdaptiveBlurImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *blur_view, *edge_view, *image_view; double normalize; Image *blur_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType **kernel; register ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); blur_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) < MagickEpsilon) return(blur_image); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } /* Edge detect the image brighness channel, level, blur, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image,exception); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image,exception); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(MagickRealType **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,sizeof(*kernel))); if (kernel == (MagickRealType **) NULL) { edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( (size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (MagickRealType *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(MagickRealType) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(j-1)/2]+=(1.0-normalize); if (sigma < MagickEpsilon) kernel[i][(j-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(MagickRealType *) RelinquishAlignedMemory(kernel[i]); kernel=(MagickRealType **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { register const Quantum *restrict r; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((r == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) blur_image->columns; x++) { register const Quantum *restrict p; register ssize_t i; ssize_t center, j; j=(ssize_t) ceil((double) width*QuantumScale* GetPixelIntensity(edge_image,r)-0.5); if (j < 0) j=0; else if (j > (ssize_t) width) j=(ssize_t) width; if ((j & 0x01) != 0) j--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-j)/2L),y- (ssize_t) ((width-j)/2L),width-j,width-j,exception); if (p == (const Quantum *) NULL) break; center=(ssize_t) GetPixelChannels(image)*(width-j)*((width-j)/2L)+ GetPixelChannels(image)*((width-j)/2L); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; register const MagickRealType *restrict k; register const Quantum *restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if (((blur_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p+center) == 0)) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } k=kernel[j]; pixels=p; pixel=0.0; gamma=0.0; if ((blur_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { pixel+=(*k)*pixels[i]; gamma+=(*k); k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } /* Alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(blur_image); r+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveBlurImage) #endif proceed=SetImageProgress(image,AdaptiveBlurImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(MagickRealType *) RelinquishAlignedMemory(kernel[i]); kernel=(MagickRealType **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveSharpenImage() adaptively sharpens the image by sharpening more % intensely near image edges and less intensely far from edges. We sharpen the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveSharpenImage() selects a suitable radius for you. % % The format of the AdaptiveSharpenImage method is: % % Image *AdaptiveSharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveSharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define AdaptiveSharpenImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *sharp_view, *edge_view, *image_view; double normalize; Image *sharp_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType **kernel; register ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); sharp_image=CloneImage(image,0,0,MagickTrue,exception); if (sharp_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) < MagickEpsilon) return(sharp_image); if (SetImageStorageClass(sharp_image,DirectClass,exception) == MagickFalse) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } /* Edge detect the image brightness channel, level, sharp, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image,exception); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image,exception); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(MagickRealType **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,sizeof(*kernel))); if (kernel == (MagickRealType **) NULL) { edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( (size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (MagickRealType *) NULL) break; normalize=0.0; j=(ssize_t) (width-i)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(MagickRealType) (-exp(-((double) u*u+v*v)/(2.0* MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]=(double) ((-2.0)*normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(MagickRealType *) RelinquishAlignedMemory(kernel[i]); kernel=(MagickRealType **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively sharpen image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); sharp_view=AcquireAuthenticCacheView(sharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,sharp_image,sharp_image->rows,1) #endif for (y=0; y < (ssize_t) sharp_image->rows; y++) { register const Quantum *restrict r; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sharp_view,0,y,sharp_image->columns,1, exception); if ((r == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) sharp_image->columns; x++) { register const Quantum *restrict p; register ssize_t i; ssize_t center, j; j=(ssize_t) ceil((double) width*(1.0-QuantumScale* GetPixelIntensity(edge_image,r))-0.5); if (j < 0) j=0; else if (j > (ssize_t) width) j=(ssize_t) width; if ((j & 0x01) != 0) j--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-j)/2L),y- (ssize_t) ((width-j)/2L),width-j,width-j,exception); if (p == (const Quantum *) NULL) break; center=(ssize_t) GetPixelChannels(image)*(width-j)*((width-j)/2L)+ GetPixelChannels(image)*((width-j)/2); for (i=0; i < (ssize_t) GetPixelChannels(sharp_image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait sharp_traits, traits; register const MagickRealType *restrict k; register const Quantum *restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); sharp_traits=GetPixelChannelTraits(sharp_image,channel); if ((traits == UndefinedPixelTrait) || (sharp_traits == UndefinedPixelTrait)) continue; if (((sharp_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p+center) == 0)) { SetPixelChannel(sharp_image,channel,p[center+i],q); continue; } k=kernel[j]; pixels=p; pixel=0.0; gamma=0.0; if ((sharp_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { pixel+=(*k)*pixels[i]; gamma+=(*k); k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(sharp_image,channel,ClampToQuantum(gamma*pixel),q); continue; } /* Alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(sharp_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(sharp_image); r+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(sharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveSharpenImage) #endif proceed=SetImageProgress(image,AdaptiveSharpenImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sharp_image->type=image->type; sharp_view=DestroyCacheView(sharp_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(MagickRealType *) RelinquishAlignedMemory(kernel[i]); kernel=(MagickRealType **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) sharp_image=DestroyImage(sharp_image); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlurImage() blurs an image. We convolve the image with a Gaussian operator % of the given radius and standard deviation (sigma). For reasonable results, % the radius should be larger than sigma. Use a radius of 0 and BlurImage() % selects a suitable radius for you. % % The format of the BlurImage method is: % % Image *BlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_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); (void) FormatLocaleString(geometry,MaxTextExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n v o l v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvolveImage() applies a custom convolution kernel to the image. % % The format of the ConvolveImage method is: % % Image *ConvolveImage(const Image *image,const KernelInfo *kernel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kernel: the filtering kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConvolveImage(const Image *image, const KernelInfo *kernel_info,ExceptionInfo *exception) { Image *convolve_image; convolve_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); return(convolve_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s p e c k l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DespeckleImage() reduces the speckle noise in an image while perserving the % edges of the original image. A speckle removing filter uses a complementary % hulling technique (raising pixels that are darker than their surrounding % neighbors, then complementarily lowering pixels that are brighter than their % surrounding neighbors) to reduce the speckle index of that image (reference % Crimmins speckle removal). % % The format of the DespeckleImage method is: % % Image *DespeckleImage(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 void Hull(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const int polarity,Quantum *restrict f,Quantum *restrict g) { register Quantum *p, *q, *r, *s; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(f != (Quantum *) NULL); assert(g != (Quantum *) NULL); p=f+(columns+2); q=g+(columns+2); r=p+(y_offset*(columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickRealType v; register ssize_t i, x; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) p[i]; if ((MagickRealType) r[i] >= (v+ScaleCharToQuantum(2))) v+=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) p[i]; if ((MagickRealType) r[i] <= (v-ScaleCharToQuantum(2))) v-=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } } p=f+(columns+2); q=g+(columns+2); r=q+(y_offset*(columns+2)+x_offset); s=q-(y_offset*(columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) rows; y++) { register ssize_t i, x; MagickRealType v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) q[i]; if (((MagickRealType) s[i] >= (v+ScaleCharToQuantum(2))) && ((MagickRealType) r[i] > v)) v+=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) q[i]; if (((MagickRealType) s[i] <= (v-ScaleCharToQuantum(2))) && ((MagickRealType) r[i] < v)) v-=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } } } MagickExport Image *DespeckleImage(const Image *image,ExceptionInfo *exception) { #define DespeckleImageTag "Despeckle/Image" CacheView *despeckle_view, *image_view; Image *despeckle_image; MagickBooleanType status; MemoryInfo *buffer_info, *pixel_info; Quantum *restrict buffer, *restrict pixels; register ssize_t i; size_t length; static const ssize_t X[4] = {0, 1, 1,-1}, Y[4] = {1, 0, 1, 1}; /* Allocate despeckled 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); despeckle_image=CloneImage(image,0,0,MagickTrue,exception); if (despeckle_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(despeckle_image,DirectClass,exception); if (status == MagickFalse) { despeckle_image=DestroyImage(despeckle_image); return((Image *) NULL); } /* Allocate image buffer. */ length=(size_t) ((image->columns+2)*(image->rows+2)); pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); buffer_info=AcquireVirtualMemory(length,sizeof(*buffer)); if ((pixel_info == (MemoryInfo *) NULL) || (buffer_info == (MemoryInfo *) NULL)) { if (buffer_info != (MemoryInfo *) NULL) buffer_info=RelinquishVirtualMemory(buffer_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image=DestroyImage(despeckle_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(Quantum *) GetVirtualMemoryBlob(pixel_info); buffer=(Quantum *) GetVirtualMemoryBlob(buffer_info); /* Reduce speckle in the image. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); despeckle_view=AcquireAuthenticCacheView(despeckle_image,exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait despeckle_traits, traits; register ssize_t k, x; ssize_t j, y; if (status == MagickFalse) continue; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); despeckle_traits=GetPixelChannelTraits(despeckle_image,channel); if ((traits == UndefinedPixelTrait) || (despeckle_traits == UndefinedPixelTrait)) continue; if ((despeckle_traits & CopyPixelTrait) != 0) continue; (void) ResetMagickMemory(pixels,0,length*sizeof(*pixels)); j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } j++; for (x=0; x < (ssize_t) image->columns; x++) { pixels[j++]=p[i]; p+=GetPixelChannels(image); } j++; } (void) ResetMagickMemory(buffer,0,length*sizeof(*buffer)); for (k=0; k < 4; k++) { Hull(image,X[k],Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,-1,pixels,buffer); Hull(image,X[k],Y[k],image->columns,image->rows,-1,pixels,buffer); } j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *restrict q; q=GetCacheViewAuthenticPixels(despeckle_view,0,y,despeckle_image->columns, 1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } j++; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelChannel(despeckle_image,channel,pixels[j++],q); q+=GetPixelChannels(despeckle_image); } sync=SyncCacheViewAuthenticPixels(despeckle_view,exception); if (sync == MagickFalse) status=MagickFalse; j++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DespeckleImageTag,(MagickOffsetType) i, GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } despeckle_view=DestroyCacheView(despeckle_view); image_view=DestroyCacheView(image_view); buffer_info=RelinquishVirtualMemory(buffer_info); pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image->type=image->type; if (status == MagickFalse) despeckle_image=DestroyImage(despeckle_image); return(despeckle_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EdgeImage() finds edges in an image. Radius defines the radius of the % convolution filter. Use a radius of 0 and EdgeImage() selects a suitable % radius for you. % % The format of the EdgeImage method is: % % Image *EdgeImage(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 *EdgeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *edge_image; KernelInfo *kernel_info; register ssize_t i; size_t width; 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); width=GetOptimalKernelWidth1D(radius,0.5); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (kernel_info->width-1)/2; kernel_info->y=(ssize_t) (kernel_info->height-1)/2; kernel_info->signature=MagickSignature; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->height* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]=(-1.0); kernel_info->values[i/2]=(double) kernel_info->width*kernel_info->height-1.0; edge_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E m b o s s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EmbossImage() returns a grayscale image with a three-dimensional effect. % We convolve the image with a Gaussian operator of the given radius and % standard deviation (sigma). For reasonable results, radius should be % larger than sigma. Use a radius of 0 and Emboss() selects a suitable % radius for you. % % The format of the EmbossImage method is: % % Image *EmbossImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EmbossImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *emboss_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, k, u, v; 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); width=GetOptimalKernelWidth1D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->width* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } j=(ssize_t) (kernel_info->width-1)/2; k=j; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(MagickRealType) (((u < 0) || (v < 0) ? -8.0 : 8.0)*exp(-((double) u*u+v*v)/(2.0*MagickSigma*MagickSigma))/ (2.0*MagickPI*MagickSigma*MagickSigma)); if (u != k) kernel_info->values[i]=0.0; i++; } k--; } normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; emboss_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); if (emboss_image != (Image *) NULL) (void) EqualizeImage(emboss_image,exception); return(emboss_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a u s s i a n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GaussianBlurImage() blurs an image. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, the radius should be larger than sigma. Use a % radius of 0 and GaussianBlurImage() selects a suitable radius for you % % The format of the GaussianBlurImage method is: % % Image *GaussianBlurImage(const Image *image,onst double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GaussianBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_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); (void) FormatLocaleString(geometry,MaxTextExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % K u w a h a r a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % KuwaharaImage() is an edge preserving noise reduction filter. % % The format of the KuwaharaImage method is: % % Image *KuwaharaImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickRealType GetMeanLuma(const Image *restrict image, const double *restrict pixel) { if (image->colorspace == GRAYColorspace) return((MagickRealType) pixel[image->channel_map[GrayPixelChannel].offset]); return(0.212656f*pixel[image->channel_map[RedPixelChannel].offset]+ 0.715158f*pixel[image->channel_map[GreenPixelChannel].offset]+ 0.072186f*pixel[image->channel_map[BluePixelChannel].offset]); /* Rec709 */ } MagickExport Image *KuwaharaImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define KuwaharaImageTag "Kuwahara/Image" CacheView *image_view[4], *kuwahara_view; Image *gaussian_image, *kuwahara_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; size_t width; ssize_t y; /* Initialize kuwahara image attributes. */ 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); gaussian_image=BlurImage(image,1.0,sigma,exception); if (gaussian_image == (Image *) NULL) return((Image *) NULL); kuwahara_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (kuwahara_image == (Image *) NULL) { gaussian_image=DestroyImage(gaussian_image); return((Image *) NULL); } if (SetImageStorageClass(kuwahara_image,DirectClass,exception) == MagickFalse) { gaussian_image=DestroyImage(gaussian_image); kuwahara_image=DestroyImage(kuwahara_image); return((Image *) NULL); } /* Edge preserving noise reduction filter. */ status=MagickTrue; progress=0; width=(size_t) radius+1; for (i=0; i < 4; i++) image_view[i]=AcquireVirtualCacheView(gaussian_image,exception); kuwahara_view=AcquireAuthenticCacheView(kuwahara_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,kuwahara_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(kuwahara_view,0,y,kuwahara_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { const Quantum *restrict p[4]; double min_variance, pixel[MaxPixelChannels]; ssize_t j; for (i=0; i < 4; i++) { ssize_t x_offset, y_offset; switch (i) { case 0: { x_offset=x-(ssize_t) (width-1); y_offset=y-(ssize_t) (width-1); break; } case 1: { x_offset=x; y_offset=y-(ssize_t) (width-1); break; } case 2: { x_offset=x-(ssize_t) (width-1); y_offset=y; break; } case 3: default: { x_offset=x; y_offset=y; break; } } p[i]=GetCacheViewVirtualPixels(image_view[i],x_offset,y_offset, width,width,exception); if (p[i] == (const Quantum *) NULL) break; } if (i < 4) { status=MagickFalse; break; } min_variance=MagickMaximumValue; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) pixel[j]=0.0; for (i=0; i < 4; i++) { const Quantum *restrict k; double mean[MaxPixelChannels], variance; ssize_t z; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) mean[j]=0.0; k=p[i]; for (z=0; z < (ssize_t) (width*width); z++) { for (j=0; j < (ssize_t) GetPixelChannels(image); j++) mean[j]+=(double) k[j]; k+=GetPixelChannels(image); } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) mean[j]/=(double) (width*width); k=p[i]; variance=0.0; for (z=0; z < (ssize_t) (width*width); z++) { double luma; luma=GetPixelLuma(image,k); variance+=(luma-GetMeanLuma(gaussian_image,mean))* (luma-GetMeanLuma(gaussian_image,mean)); k+=GetPixelChannels(image); } if (variance < min_variance) { min_variance=variance; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) pixel[j]=mean[j]; } } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) q[j]=ClampToQuantum(pixel[j]); q+=GetPixelChannels(kuwahara_image); } if (SyncCacheViewAuthenticPixels(kuwahara_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_KuwaharaImage) #endif proceed=SetImageProgress(image,KuwaharaImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } kuwahara_view=DestroyCacheView(kuwahara_view); for (i=0; i < 4; i++) image_view[i]=DestroyCacheView(image_view[i]); gaussian_image=DestroyImage(gaussian_image); if (status == MagickFalse) kuwahara_image=DestroyImage(kuwahara_image); return(kuwahara_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o t i o n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MotionBlurImage() simulates motion blur. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, radius should be larger than sigma. Use a % radius of 0 and MotionBlurImage() selects a suitable radius for you. % Angle gives the angle of the blurring motion. % % Andrew Protano contributed this effect. % % The format of the MotionBlurImage method is: % % Image *MotionBlurImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting % the center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ static MagickRealType *GetMotionBlurKernel(const size_t width, const double sigma) { MagickRealType *kernel, normalize; register ssize_t i; /* Generate a 1-D convolution kernel. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,sizeof(*kernel))); if (kernel == (MagickRealType *) NULL) return(kernel); normalize=0.0; for (i=0; i < (ssize_t) width; i++) { kernel[i]=(MagickRealType) (exp((-((double) i*i)/(double) (2.0*MagickSigma* MagickSigma)))/(MagickSQ2PI*MagickSigma)); normalize+=kernel[i]; } for (i=0; i < (ssize_t) width; i++) kernel[i]/=normalize; return(kernel); } MagickExport Image *MotionBlurImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { #define BlurImageTag "Blur/Image" CacheView *blur_view, *image_view, *motion_view; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType *kernel; OffsetInfo *offset; PointInfo point; register ssize_t i; size_t width; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); width=GetOptimalKernelWidth1D(radius,sigma); kernel=GetMotionBlurKernel(width,sigma); if (kernel == (MagickRealType *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); offset=(OffsetInfo *) AcquireQuantumMemory(width,sizeof(*offset)); if (offset == (OffsetInfo *) NULL) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } blur_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); blur_image=DestroyImage(blur_image); return((Image *) NULL); } point.x=(double) width*sin(DegreesToRadians(angle)); point.y=(double) width*cos(DegreesToRadians(angle)); for (i=0; i < (ssize_t) width; i++) { offset[i].x=(ssize_t) ceil((double) (i*point.y)/hypot(point.x,point.y)-0.5); offset[i].y=(ssize_t) ceil((double) (i*point.x)/hypot(point.x,point.y)-0.5); } /* Motion blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); motion_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; register const Quantum *restrict r; register MagickRealType *restrict k; register ssize_t j; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if (((blur_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(blur_image,channel,p[i],q); continue; } k=kernel; pixel=0.0; if ((blur_traits & BlendPixelTrait) == 0) { for (j=0; j < (ssize_t) width; j++) { r=GetCacheViewVirtualPixels(motion_view,x+offset[j].x,y+ offset[j].y,1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } pixel+=(*k)*r[i]; k++; } SetPixelChannel(blur_image,channel,ClampToQuantum(pixel),q); continue; } alpha=0.0; gamma=0.0; for (j=0; j < (ssize_t) width; j++) { r=GetCacheViewVirtualPixels(motion_view,x+offset[j].x,y+offset[j].y,1, 1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } alpha=(double) (QuantumScale*GetPixelAlpha(image,r)); pixel+=(*k)*alpha*r[i]; gamma+=(*k)*alpha; k++; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(blur_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MotionBlurImage) #endif proceed=SetImageProgress(image,BlurImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); motion_view=DestroyCacheView(motion_view); image_view=DestroyCacheView(image_view); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r e v i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PreviewImage() tiles 9 thumbnails of the specified image with an image % processing operation applied with varying parameters. This may be helpful % pin-pointing an appropriate parameter for a particular image processing % operation. % % The format of the PreviewImages method is: % % Image *PreviewImages(const Image *image,const PreviewType preview, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o preview: the image processing operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PreviewImage(const Image *image,const PreviewType preview, ExceptionInfo *exception) { #define NumberTiles 9 #define PreviewImageTag "Preview/Image" #define DefaultPreviewGeometry "204x204+10+10" char factor[MaxTextExtent], label[MaxTextExtent]; double degrees, gamma, percentage, radius, sigma, threshold; extern const char DefaultTileFrame[]; Image *images, *montage_image, *preview_image, *thumbnail; ImageInfo *preview_info; MagickBooleanType proceed; MontageInfo *montage_info; QuantizeInfo quantize_info; RectangleInfo geometry; register ssize_t i, x; size_t colors; ssize_t y; /* Open output image file. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); colors=2; degrees=0.0; gamma=(-0.2f); preview_info=AcquireImageInfo(); SetGeometry(image,&geometry); (void) ParseMetaGeometry(DefaultPreviewGeometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); images=NewImageList(); percentage=12.5; GetQuantizeInfo(&quantize_info); radius=0.0; sigma=1.0; threshold=0.0; x=0; y=0; for (i=0; i < NumberTiles; i++) { thumbnail=ThumbnailImage(image,geometry.width,geometry.height,exception); if (thumbnail == (Image *) NULL) break; (void) SetImageProgressMonitor(thumbnail,(MagickProgressMonitor) NULL, (void *) NULL); (void) SetImageProperty(thumbnail,"label",DefaultTileLabel,exception); if (i == (NumberTiles/2)) { (void) QueryColorCompliance("#dfdfdf",AllCompliance, &thumbnail->matte_color,exception); AppendImageToList(&images,thumbnail); continue; } switch (preview) { case RotatePreview: { degrees+=45.0; preview_image=RotateImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"rotate %g",degrees); break; } case ShearPreview: { degrees+=5.0; preview_image=ShearImage(thumbnail,degrees,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"shear %gx%g",degrees, 2.0*degrees); break; } case RollPreview: { x=(ssize_t) ((i+1)*thumbnail->columns)/NumberTiles; y=(ssize_t) ((i+1)*thumbnail->rows)/NumberTiles; preview_image=RollImage(thumbnail,x,y,exception); (void) FormatLocaleString(label,MaxTextExtent,"roll %+.20gx%+.20g", (double) x,(double) y); break; } case HuePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,100,%g",2.0* percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case SaturationPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,%g",2.0*percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case BrightnessPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"%g",2.0*percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case GammaPreview: default: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; gamma+=0.4f; (void) GammaImage(preview_image,gamma,exception); (void) FormatLocaleString(label,MaxTextExtent,"gamma %g",gamma); break; } case SpiffPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image != (Image *) NULL) for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickTrue,exception); (void) FormatLocaleString(label,MaxTextExtent,"contrast (%.20g)", (double) i+1); break; } case DullPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickFalse,exception); (void) FormatLocaleString(label,MaxTextExtent,"+contrast (%.20g)", (double) i+1); break; } case GrayscalePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; quantize_info.colorspace=GRAYColorspace; (void) QuantizeImage(&quantize_info,preview_image,exception); (void) FormatLocaleString(label,MaxTextExtent, "-colorspace gray -colors %.20g",(double) colors); break; } case QuantizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; (void) QuantizeImage(&quantize_info,preview_image,exception); (void) FormatLocaleString(label,MaxTextExtent,"colors %.20g",(double) colors); break; } case DespecklePreview: { for (x=0; x < (i-1); x++) { preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; thumbnail=DestroyImage(thumbnail); thumbnail=preview_image; } preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(label,MaxTextExtent,"despeckle (%.20g)", (double) i+1); break; } case ReduceNoisePreview: { preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) radius, (size_t) radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"noise %g",radius); break; } case AddNoisePreview: { switch ((int) i) { case 0: { (void) CopyMagickString(factor,"uniform",MaxTextExtent); break; } case 1: { (void) CopyMagickString(factor,"gaussian",MaxTextExtent); break; } case 2: { (void) CopyMagickString(factor,"multiplicative",MaxTextExtent); break; } case 3: { (void) CopyMagickString(factor,"impulse",MaxTextExtent); break; } case 5: { (void) CopyMagickString(factor,"laplacian",MaxTextExtent); break; } case 6: { (void) CopyMagickString(factor,"Poisson",MaxTextExtent); break; } default: { (void) CopyMagickString(thumbnail->magick,"NULL",MaxTextExtent); break; } } preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) i, (size_t) i,exception); (void) FormatLocaleString(label,MaxTextExtent,"+noise %s",factor); break; } case SharpenPreview: { preview_image=SharpenImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"sharpen %gx%g",radius, sigma); break; } case BlurPreview: { preview_image=BlurImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"blur %gx%g",radius, sigma); break; } case ThresholdPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) BilevelImage(thumbnail,(double) (percentage*((double) QuantumRange+1.0))/100.0,exception); (void) FormatLocaleString(label,MaxTextExtent,"threshold %g",(double) (percentage*((double) QuantumRange+1.0))/100.0); break; } case EdgeDetectPreview: { preview_image=EdgeImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"edge %g",radius); break; } case SpreadPreview: { preview_image=SpreadImage(thumbnail,radius,thumbnail->interpolate, exception); (void) FormatLocaleString(label,MaxTextExtent,"spread %g",radius+0.5); break; } case SolarizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) SolarizeImage(preview_image,(double) QuantumRange*percentage/ 100.0,exception); (void) FormatLocaleString(label,MaxTextExtent,"solarize %g", (QuantumRange*percentage)/100.0); break; } case ShadePreview: { degrees+=10.0; preview_image=ShadeImage(thumbnail,MagickTrue,degrees,degrees, exception); (void) FormatLocaleString(label,MaxTextExtent,"shade %gx%g",degrees, degrees); break; } case RaisePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; geometry.width=(size_t) (2*i+2); geometry.height=(size_t) (2*i+2); geometry.x=(i-1)/2; geometry.y=(i-1)/2; (void) RaiseImage(preview_image,&geometry,MagickTrue,exception); (void) FormatLocaleString(label,MaxTextExtent, "raise %.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); break; } case SegmentPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; threshold+=0.4f; (void) SegmentImage(preview_image,sRGBColorspace,MagickFalse,threshold, threshold,exception); (void) FormatLocaleString(label,MaxTextExtent,"segment %gx%g", threshold,threshold); break; } case SwirlPreview: { preview_image=SwirlImage(thumbnail,degrees,image->interpolate, exception); (void) FormatLocaleString(label,MaxTextExtent,"swirl %g",degrees); degrees+=45.0; break; } case ImplodePreview: { degrees+=0.1f; preview_image=ImplodeImage(thumbnail,degrees,image->interpolate, exception); (void) FormatLocaleString(label,MaxTextExtent,"implode %g",degrees); break; } case WavePreview: { degrees+=5.0f; preview_image=WaveImage(thumbnail,0.5*degrees,2.0*degrees, image->interpolate,exception); (void) FormatLocaleString(label,MaxTextExtent,"wave %gx%g",0.5*degrees, 2.0*degrees); break; } case OilPaintPreview: { preview_image=OilPaintImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MaxTextExtent,"charcoal %gx%g",radius, sigma); break; } case CharcoalDrawingPreview: { preview_image=CharcoalImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MaxTextExtent,"charcoal %gx%g",radius, sigma); break; } case JPEGPreview: { char filename[MaxTextExtent]; int file; MagickBooleanType status; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; preview_info->quality=(size_t) percentage; (void) FormatLocaleString(factor,MaxTextExtent,"%.20g",(double) preview_info->quality); file=AcquireUniqueFileResource(filename); if (file != -1) file=close(file)-1; (void) FormatLocaleString(preview_image->filename,MaxTextExtent, "jpeg:%s",filename); status=WriteImage(preview_info,preview_image,exception); if (status != MagickFalse) { Image *quality_image; (void) CopyMagickString(preview_info->filename, preview_image->filename,MaxTextExtent); quality_image=ReadImage(preview_info,exception); if (quality_image != (Image *) NULL) { preview_image=DestroyImage(preview_image); preview_image=quality_image; } } (void) RelinquishUniqueFileResource(preview_image->filename); if ((GetBlobSize(preview_image)/1024) >= 1024) (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%gmb ", factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/ 1024.0/1024.0); else if (GetBlobSize(preview_image) >= 1024) (void) FormatLocaleString(label,MaxTextExtent, "quality %s\n%gkb ",factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/1024.0); else (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%.20gb ", factor,(double) ((MagickOffsetType) GetBlobSize(thumbnail))); break; } } thumbnail=DestroyImage(thumbnail); percentage+=12.5; radius+=0.5; sigma+=0.25; if (preview_image == (Image *) NULL) break; (void) DeleteImageProperty(preview_image,"label"); (void) SetImageProperty(preview_image,"label",label,exception); AppendImageToList(&images,preview_image); proceed=SetImageProgress(image,PreviewImageTag,(MagickOffsetType) i, NumberTiles); if (proceed == MagickFalse) break; } if (images == (Image *) NULL) { preview_info=DestroyImageInfo(preview_info); return((Image *) NULL); } /* Create the montage. */ montage_info=CloneMontageInfo(preview_info,(MontageInfo *) NULL); (void) CopyMagickString(montage_info->filename,image->filename,MaxTextExtent); montage_info->shadow=MagickTrue; (void) CloneString(&montage_info->tile,"3x3"); (void) CloneString(&montage_info->geometry,DefaultPreviewGeometry); (void) CloneString(&montage_info->frame,DefaultTileFrame); montage_image=MontageImages(images,montage_info,exception); montage_info=DestroyMontageInfo(montage_info); images=DestroyImageList(images); if (montage_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (montage_image->montage != (char *) NULL) { /* Free image directory. */ montage_image->montage=(char *) RelinquishMagickMemory( montage_image->montage); if (image->directory != (char *) NULL) montage_image->directory=(char *) RelinquishMagickMemory( montage_image->directory); } preview_info=DestroyImageInfo(preview_info); return(montage_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o t a t i o n a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotationalBlurImage() applies a radial blur to the image. % % Andrew Protano contributed this effect. % % The format of the RotationalBlurImage method is: % % Image *RotationalBlurImage(const Image *image,const double angle, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o angle: the angle of the radial blur. % % o blur: the blur. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RotationalBlurImage(const Image *image,const double angle, ExceptionInfo *exception) { CacheView *blur_view, *image_view, *radial_view; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; double blur_radius, *cos_theta, offset, *sin_theta, theta; PointInfo blur_center; register ssize_t i; size_t n; ssize_t y; /* Allocate blur 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); blur_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } blur_center.x=(double) (image->columns-1)/2.0; blur_center.y=(double) (image->rows-1)/2.0; blur_radius=hypot(blur_center.x,blur_center.y); n=(size_t) fabs(4.0*DegreesToRadians(angle)*sqrt((double) blur_radius)+2UL); theta=DegreesToRadians(angle)/(double) (n-1); cos_theta=(double *) AcquireQuantumMemory((size_t) n, sizeof(*cos_theta)); sin_theta=(double *) AcquireQuantumMemory((size_t) n, sizeof(*sin_theta)); if ((cos_theta == (double *) NULL) || (sin_theta == (double *) NULL)) { blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } offset=theta*(double) (n-1)/2.0; for (i=0; i < (ssize_t) n; i++) { cos_theta[i]=cos((double) (theta*i-offset)); sin_theta[i]=sin((double) (theta*i-offset)); } /* Radial blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); radial_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double radius; PointInfo center; register ssize_t i; size_t step; center.x=(double) x-blur_center.x; center.y=(double) y-blur_center.y; radius=hypot((double) center.x,center.y); if (radius == 0) step=1; else { step=(size_t) (blur_radius/radius); if (step == 0) step=1; else if (step >= n) step=n-1; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; register const Quantum *restrict r; register ssize_t j; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if (((blur_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(blur_image,channel,p[i],q); continue; } gamma=0.0; pixel=0.0; if ((blur_traits & BlendPixelTrait) == 0) { for (j=0; j < (ssize_t) n; j+=(ssize_t) step) { r=GetCacheViewVirtualPixels(radial_view, (ssize_t) (blur_center.x+ center.x*cos_theta[j]-center.y*sin_theta[j]+0.5),(ssize_t) (blur_center.y+center.x*sin_theta[j]+center.y*cos_theta[j]+0.5), 1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } pixel+=r[i]; gamma++; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } for (j=0; j < (ssize_t) n; j+=(ssize_t) step) { r=GetCacheViewVirtualPixels(radial_view, (ssize_t) (blur_center.x+ center.x*cos_theta[j]-center.y*sin_theta[j]+0.5),(ssize_t) (blur_center.y+center.x*sin_theta[j]+center.y*cos_theta[j]+0.5), 1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } pixel+=GetPixelAlpha(image,r)*r[i]; gamma+=GetPixelAlpha(image,r); } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(blur_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RotationalBlurImage) #endif proceed=SetImageProgress(image,BlurImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); radial_view=DestroyCacheView(radial_view); image_view=DestroyCacheView(image_view); cos_theta=(double *) RelinquishMagickMemory(cos_theta); sin_theta=(double *) RelinquishMagickMemory(sin_theta); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e l e c t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SelectiveBlurImage() selectively blur pixels within a contrast threshold. % It is similar to the unsharpen mask that sharpens everything with contrast % above a certain threshold. % % The format of the SelectiveBlurImage method is: % % Image *SelectiveBlurImage(const Image *image,const double radius, % const double sigma,const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o threshold: only pixels within this contrast threshold are included % in the blur operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SelectiveBlurImage(const Image *image,const double radius, const double sigma,const double threshold,ExceptionInfo *exception) { #define SelectiveBlurImageTag "SelectiveBlur/Image" CacheView *blur_view, *image_view, *luminance_view; Image *blur_image, *luminance_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType *kernel; register ssize_t i; size_t width; ssize_t center, j, u, v, y; /* Initialize blur image attributes. */ 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); width=GetOptimalKernelWidth1D(radius,sigma); kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,width*sizeof(*kernel))); if (kernel == (MagickRealType *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); j=(ssize_t) (width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) kernel[i++]=(MagickRealType) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); } if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; register const MagickRealType *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " SelectiveBlurImage with %.20gx%.20g kernel:",(double) width,(double) width); message=AcquireString(""); k=kernel; for (v=0; v < (ssize_t) width; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) width; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%+f ",(double) *k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } blur_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } luminance_image=CloneImage(image,0,0,MagickTrue,exception); if (luminance_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } status=TransformImageColorspace(luminance_image,GRAYColorspace,exception); if (status == MagickFalse) { luminance_image=DestroyImage(luminance_image); blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } /* Threshold blur image. */ status=MagickTrue; progress=0; center=(ssize_t) (GetPixelChannels(image)*(image->columns+width)* ((width-1)/2L)+GetPixelChannels(image)*((width-1)/2L)); image_view=AcquireVirtualCacheView(image,exception); luminance_view=AcquireVirtualCacheView(luminance_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double contrast; MagickBooleanType sync; register const Quantum *restrict l, *restrict p; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (width-1)/2L),y-(ssize_t) ((width-1)/2L),image->columns+width,width,exception); l=GetCacheViewVirtualPixels(luminance_view,-((ssize_t) (width-1)/2L),y- (ssize_t) ((width-1)/2L),luminance_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity; register ssize_t i; intensity=GetPixelIntensity(image,p+center); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; register const MagickRealType *restrict k; register const Quantum *restrict luminance_pixels, *restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if (((blur_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p+center) == 0)) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } k=kernel; pixel=0.0; pixels=p; luminance_pixels=l; gamma=0.0; if ((blur_traits & BlendPixelTrait) == 0) { for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,luminance_pixels)- intensity; if (fabs(contrast) < threshold) { pixel+=(*k)*pixels[i]; gamma+=(*k); } k++; pixels+=GetPixelChannels(image); luminance_pixels+=GetPixelChannels(luminance_image); } pixels+=(image->columns-1)*GetPixelChannels(image); luminance_pixels+=luminance_image->columns* GetPixelChannels(luminance_image); } if (fabs((double) gamma) < MagickEpsilon) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(image,pixels)-intensity; if (fabs(contrast) < threshold) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; } k++; pixels+=GetPixelChannels(image); luminance_pixels+=GetPixelChannels(luminance_image); } pixels+=(image->columns-1)*GetPixelChannels(image); luminance_pixels+=luminance_image->columns* GetPixelChannels(luminance_image); } if (fabs((double) gamma) < MagickEpsilon) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); l+=GetPixelChannels(luminance_image); q+=GetPixelChannels(blur_image); } sync=SyncCacheViewAuthenticPixels(blur_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SelectiveBlurImage) #endif proceed=SetImageProgress(image,SelectiveBlurImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); luminance_image=DestroyImage(luminance_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadeImage() shines a distant light on an image to create a % three-dimensional effect. You control the positioning of the light with % azimuth and elevation; azimuth is measured in degrees off the x axis % and elevation is measured in pixels above the Z axis. % % The format of the ShadeImage method is: % % Image *ShadeImage(const Image *image,const MagickBooleanType gray, % const double azimuth,const double elevation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o gray: A value other than zero shades the intensity of each pixel. % % o azimuth, elevation: Define the light source direction. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadeImage(const Image *image,const MagickBooleanType gray, const double azimuth,const double elevation,ExceptionInfo *exception) { #define ShadeImageTag "Shade/Image" CacheView *image_view, *shade_view; Image *linear_image, *shade_image; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo light; ssize_t y; /* Initialize shaded image attributes. */ 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); linear_image=CloneImage(image,0,0,MagickTrue,exception); shade_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (shade_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (shade_image != (Image *) NULL) shade_image=DestroyImage(shade_image); return((Image *) NULL); } if (SetImageStorageClass(shade_image,DirectClass,exception) == MagickFalse) { linear_image=DestroyImage(linear_image); shade_image=DestroyImage(shade_image); return((Image *) NULL); } /* Compute the light vector. */ light.x=(double) QuantumRange*cos(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.y=(double) QuantumRange*sin(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.z=(double) QuantumRange*sin(DegreesToRadians(elevation)); /* Shade image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); shade_view=AcquireAuthenticCacheView(shade_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(linear_image,shade_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { double distance, normal_distance, shade; PrimaryInfo normal; register const Quantum *restrict center, *restrict p, *restrict post, *restrict pre; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-1,y-1,linear_image->columns+2,3, exception); q=QueueCacheViewAuthenticPixels(shade_view,0,y,shade_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } /* Shade this row of pixels. */ normal.z=2.0*(double) QuantumRange; /* constant Z of surface normal */ pre=p+GetPixelChannels(linear_image); center=pre+(linear_image->columns+2)*GetPixelChannels(linear_image); post=center+(linear_image->columns+2)*GetPixelChannels(linear_image); for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i; /* Determine the surface normal and compute shading. */ normal.x=(double) ( GetPixelIntensity(linear_image,pre-GetPixelChannels(linear_image))+ GetPixelIntensity(linear_image,center-GetPixelChannels(linear_image))+ GetPixelIntensity(linear_image,post-GetPixelChannels(linear_image))- GetPixelIntensity(linear_image,pre+GetPixelChannels(linear_image))- GetPixelIntensity(linear_image,center+GetPixelChannels(linear_image))- GetPixelIntensity(linear_image,post+GetPixelChannels(linear_image))); normal.y=(double) ( GetPixelIntensity(linear_image,post-GetPixelChannels(linear_image))+ GetPixelIntensity(linear_image,post)+ GetPixelIntensity(linear_image,post+GetPixelChannels(linear_image))- GetPixelIntensity(linear_image,pre-GetPixelChannels(linear_image))- GetPixelIntensity(linear_image,pre)- GetPixelIntensity(linear_image,pre+GetPixelChannels(linear_image))); if ((normal.x == 0.0) && (normal.y == 0.0)) shade=light.z; else { shade=0.0; distance=normal.x*light.x+normal.y*light.y+normal.z*light.z; if (distance > MagickEpsilon) { normal_distance=normal.x*normal.x+normal.y*normal.y+ normal.z*normal.z; if (normal_distance > (MagickEpsilon*MagickEpsilon)) shade=distance/sqrt((double) normal_distance); } } for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++) { PixelChannel channel; PixelTrait shade_traits, traits; channel=GetPixelChannelChannel(linear_image,i); traits=GetPixelChannelTraits(linear_image,channel); shade_traits=GetPixelChannelTraits(shade_image,channel); if ((traits == UndefinedPixelTrait) || (shade_traits == UndefinedPixelTrait)) continue; if (((shade_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(linear_image,center) == 0)) { SetPixelChannel(shade_image,channel,center[i],q); continue; } if (gray != MagickFalse) { SetPixelChannel(shade_image,channel,ClampToQuantum(shade),q); continue; } SetPixelChannel(shade_image,channel,ClampToQuantum(QuantumScale*shade* center[i]),q); } pre+=GetPixelChannels(linear_image); center+=GetPixelChannels(linear_image); post+=GetPixelChannels(linear_image); q+=GetPixelChannels(shade_image); } if (SyncCacheViewAuthenticPixels(shade_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ShadeImage) #endif proceed=SetImageProgress(image,ShadeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } shade_view=DestroyCacheView(shade_view); image_view=DestroyCacheView(image_view); linear_image=DestroyImage(linear_image); if (status == MagickFalse) shade_image=DestroyImage(shade_image); return(shade_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SharpenImage() sharpens the image. We convolve the image with a Gaussian % operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SharpenImage() selects a suitable radius for you. % % Using a separable kernel would be faster, but the negative weights cancel % out on the corners of the kernel producing often undesirable ringing in the % filtered result; this can be avoided by using a 2D gaussian shaped image % sharpening kernel instead. % % The format of the SharpenImage method is: % % Image *SharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *sharp_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, u, v; 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); width=GetOptimalKernelWidth2D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->signature=MagickSignature; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->height* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } normalize=0.0; j=(ssize_t) (kernel_info->width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(MagickRealType) (-exp(-((double) u*u+v*v)/(2.0* MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel_info->values[i]; i++; } } kernel_info->values[i/2]=(double) ((-2.0)*normalize); normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; sharp_image=MorphologyApply(image,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p r e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpreadImage() is a special effects method that randomly displaces each % pixel in a block defined by the radius parameter. % % The format of the SpreadImage method is: % % Image *SpreadImage(const Image *image,const double radius, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: choose a random pixel in a neighborhood of this extent. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpreadImage(const Image *image,const double radius, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define SpreadImageTag "Spread/Image" CacheView *image_view, *spread_view; Image *spread_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **restrict random_info; size_t width; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize spread image attributes. */ 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); spread_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (spread_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(spread_image,DirectClass,exception) == MagickFalse) { spread_image=DestroyImage(spread_image); return((Image *) NULL); } /* Spread image. */ status=MagickTrue; progress=0; width=GetOptimalKernelWidth1D(radius,0.5); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); spread_view=AcquireAuthenticCacheView(spread_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,spread_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(spread_view,0,y,spread_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PointInfo point; point.x=GetPseudoRandomValue(random_info[id]); point.y=GetPseudoRandomValue(random_info[id]); status=InterpolatePixelChannels(image,image_view,spread_image,method, (double) x+width*point.x-0.5,(double) y+width*point.y-0.5,q,exception); q+=GetPixelChannels(spread_image); } if (SyncCacheViewAuthenticPixels(spread_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SpreadImage) #endif proceed=SetImageProgress(image,SpreadImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } spread_view=DestroyCacheView(spread_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) spread_image=DestroyImage(spread_image); return(spread_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h a r p M a s k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnsharpMaskImage() sharpens one or more image channels. We convolve the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and UnsharpMaskImage() selects a suitable radius for you. % % The format of the UnsharpMaskImage method is: % % Image *UnsharpMaskImage(const Image *image,const double radius, % const double sigma,const double amount,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o gain: the percentage of the difference between the original and the % blur image that is added back into the original. % % o threshold: the threshold in pixels needed to apply the diffence gain. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *UnsharpMaskImage(const Image *image,const double radius, const double sigma,const double gain,const double threshold, ExceptionInfo *exception) { #define SharpenImageTag "Sharpen/Image" CacheView *image_view, *unsharp_view; Image *unsharp_image; MagickBooleanType status; MagickOffsetType progress; double quantum_threshold; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); unsharp_image=BlurImage(image,radius,sigma,exception); if (unsharp_image == (Image *) NULL) return((Image *) NULL); quantum_threshold=(double) QuantumRange*threshold; /* Unsharp-mask image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); unsharp_view=AcquireAuthenticCacheView(unsharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,unsharp_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(unsharp_view,0,y,unsharp_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits, unsharp_traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); unsharp_traits=GetPixelChannelTraits(unsharp_image,channel); if ((traits == UndefinedPixelTrait) || (unsharp_traits == UndefinedPixelTrait)) continue; if (((unsharp_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(unsharp_image,channel,p[i],q); continue; } pixel=p[i]-(double) GetPixelChannel(unsharp_image,channel,q); if (fabs(2.0*pixel) < quantum_threshold) pixel=(double) p[i]; else pixel=(double) p[i]+gain*pixel; SetPixelChannel(unsharp_image,channel,ClampToQuantum(pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(unsharp_image); } if (SyncCacheViewAuthenticPixels(unsharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_UnsharpMaskImage) #endif proceed=SetImageProgress(image,SharpenImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } unsharp_image->type=image->type; unsharp_view=DestroyCacheView(unsharp_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) unsharp_image=DestroyImage(unsharp_image); return(unsharp_image); }
endif3.c
/* various cases of #if ...#endif * */ #include<stdio.h> static int par_res; int fib (int, int); // Easiest case: the extend of #if ..#endif is explicit as {} is used int fib0 (int n) { //#pragma omp parallel #pragma omp single { #if defined(MANUAL_CUTOFF) || defined(IF_CUTOFF) par_res = fib(n,0); #else par_res = fib0(n); #endif } printf("Fibonacci result for %d is %d\n",n,par_res); } // hard case for ROSE: #endif is attached to printf // it should be moved to par_res = fib(n) int fib1 (int n) { //#pragma omp parallel #pragma omp single #if defined(MANUAL_CUTOFF) || defined(IF_CUTOFF) par_res = fib(n,0); #else par_res = fib1(n); #endif // printf("Fibonacci result for %d is %d\n",n,par_res); } //TODO parallel joins the party int fib2 (int n) { #pragma omp parallel #pragma omp single { // this bracket is essential now, since we don't use wave by default to decide the scope of #endif!! #if defined(MANUAL_CUTOFF) || defined(IF_CUTOFF) par_res = fib(n,0); #else par_res = fib2(n); #endif } }
single.c
/* $ gcc -fopenmp -O2 src/single.c -o bin/single $ ./bin/single Introduce valor de inicialización a: 1 Single ejecutada por el thread 0 Depués de la región parallel: b[0] = 1 b[1] = 1 b[2] = 1 b[3] = 1 b[4] = 1 b[5] = 1 b[6] = 1 b[7] = 1 b[8] = 1 */ #include <stdio.h> #include <omp.h> main() { int n = 9, i, a, b[n]; for (i=0; i<n; i++) b[i] = -1; #pragma omp parallel { #pragma omp single { printf("Introduce valor de inicialización a: "); scanf("%d", &a ); printf("Single ejecutada por el thread %d\n", omp_get_thread_num()); } #pragma omp for for (i=0; i<n; i++) b[i] = a; } printf("Depués de la región parallel:\n"); for (i=0; i<n; i++) printf("b[%d] = %d\t",i,b[i]); printf("\n"); }
GB_binop__rminus_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__rminus_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__rminus_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__rminus_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_uint16) // A*D function (colscale): GB (_AxD__rminus_uint16) // D*A function (rowscale): GB (_DxB__rminus_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_uint16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_uint16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_uint16) // C=scalar+B GB (_bind1st__rminus_uint16) // C=scalar+B' GB (_bind1st_tran__rminus_uint16) // C=A+scalar GB (_bind2nd__rminus_uint16) // C=A'+scalar GB (_bind2nd_tran__rminus_uint16) // C type: uint16_t // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = (bij - 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) \ uint16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ 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 = (y - 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_RMINUS || GxB_NO_UINT16 || GxB_NO_RMINUS_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rminus_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__rminus_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__rminus_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rminus_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rminus_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__rminus_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__rminus_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__rminus_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__rminus_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__rminus_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__rminus_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rminus_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = (y - aij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__lnot_int64_uint32.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__lnot_int64_uint32 // op(A') function: GB_tran__lnot_int64_uint32 // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int64_uint32 ( int64_t *restrict Cx, const uint32_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__lnot_int64_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__sin_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__sin_fp32_fp32) // op(A') function: GB (_unop_tran__sin_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = sinf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = sinf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = sinf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SIN || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__sin_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = sinf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = sinf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__sin_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mlp.c
#include <stdio.h> #include <stdlib.h> #include "popc.h" #include "activation.h" #include "loss.h" #include "optimization.h" #include "ann.h" #include "cell.h" #include "mlp.h" #include "training.h" mlpSingleton ptr mlpSingletonNew () { static mlpSingleton ptr np = NULL; if (np == NULL) { np = (mlpSingleton ptr) malloc (sizeof (mlpSingleton)); dbcEnsure (np != NULL, "Memory Allocation Error!"); np -> mlpNew = mlpNew; np -> mlpDel = mlpDel; np -> addLayer = mlpAddLayer; np -> train = mlpTrain; np -> trainTuple = mlpTrainTuple; np -> predict = mlpPredict; np -> predictTuple = mlpPredictTuple; np -> setInput = mlpSetInput; np -> setTarget = mlpSetTarget; np -> propagateForward = mlpPropagateForward; np -> propagateBackward = mlpPropagateBackward; } return np; } mlp ptr mlpNew () { mlp ptr nw = (mlp ptr) malloc (sizeof (mlp)); dbcEnsure (nw != NULL, "Memory Allocation Error!"); nw -> annt = anntMultiLayerPerceptron; nw -> layer2d = NULL; nw -> inputLayerCount = 0; nw -> hiddenLayerCount = 0; nw -> outputLayerCount = 0; nw -> totalLayerCount = 0; nw -> onTrainEpochBegin = NULL; nw -> onTrainEpochEnd = NULL; nw -> onTrainTupleBegin = NULL; nw -> onTrainTupleEnd = NULL; return nw; } void mlpDel (mlp ptr nw) { // PENDING! need to clean-up inner objects free (nw); nw = NULL; } void mlpAddInputLayer () { } void mlpAddHiddenLayer () { } void mlpAddOutputLayer () { } void mlpAddLayer ( mlp ptr nw, int cellCount, layerType lt, cellType ct, activationFunctionType aft, lossFunctionType lft, optimizationFunctionType oft ) { /* subject mlpLayer { // header layerIndex index; layerCellCount cellCount; layerType lt; cellType ct; layerError error; layerDeltaError deltaErrorGradient; activationFunctionType aft; lossFunctionType lft; optimizationFunctionType oft; double learningRate; double learningMomentumRate; // /header // cell vector cellConnectionCount ptr connectionCount1d; cellInput ptr2d input2d; cellWeight ptr2d weight2d; cellOutput ptr output1d; cellTarget ptr target1d; cellError ptr outputError1d; cellDeltaError ptr outputDeltaErrorGradient1d; cellBias ptr bias1d; cellDeltaBias ptr biasDeltaGradient1d; activation ptr2d actFn2d; loss ptr2d lossFn2d; optimization ptr2d optFn2d; // /cell vector } mlpLayer; */ //mlpLayer ptr currentLayer; mlpLayerAppend (nw, cellCount, lt, ct, aft, lft, oft); } // Propagation/ void mlpPropagateForward (mlp ptr nw) { mlpLayer ptr previousLayer, ptr currentLayer //ptr nextLayer ; /* printf ("SL\t\ II:0\tII:1\tIO:0\tIO:1\t\ HW:00\tHW:01\tHW:10\tHW:11\tHO:0\tHO:1\t\ OW:00\tOW:01\tOO:0\n" ); int sl = 0; */ //#pragma omp parallel for for (int index = 1; index < nw -> totalLayerCount; index ++) { previousLayer = index == 0 ? NULL : nw -> layer2d [index - 1]; currentLayer = nw -> layer2d [index]; //nextLayer = index == nw -> totalLayerCount - 1 ? NULL : nw -> layer2d [index + 1]; mlpLayerPropagateForward (previousLayer, currentLayer); } /* printf ("%d\t\ %lf\t%lf\t%lf\t%lf\t\ %lf\t%lf\t%lf\t%lf\t%lf\t%lf\t\ %lf\t%lf\t%lf\n", sl ++, nw -> layer2d [0] -> input2d [0][0], nw -> layer2d [0] -> input2d [0][1], nw -> layer2d [0] -> output1d [0], nw -> layer2d [0] -> output1d [1], nw -> layer2d [1] -> weight2d [0][0], nw -> layer2d [1] -> weight2d [0][1], nw -> layer2d [1] -> weight2d [1][0], nw -> layer2d [1] -> weight2d [1][1], nw -> layer2d [1] -> output1d [0], nw -> layer2d [1] -> output1d [1], nw -> layer2d [2] -> weight2d [0][0], nw -> layer2d [2] -> weight2d [0][1], nw -> layer2d [2] -> output1d [0] ); */ } // Back Propagation/ void mlpPropagateBackward (mlp ptr nw, double learningRate, double learningMomentumRate) { mlpLayer ptr previousLayer, ptr currentLayer, ptr nextLayer ; //#pragma omp parallel for for (int index = nw -> totalLayerCount - 1; index > 0; index --) { previousLayer = index == 0 ? NULL : nw -> layer2d [index - 1]; currentLayer = nw -> layer2d [index]; nextLayer = index == nw -> totalLayerCount - 1 ? NULL : nw -> layer2d [index + 1]; mlpLayerPropagateBackward (previousLayer, currentLayer, nextLayer, learningRate, learningMomentumRate); } } void mlpTrain (mlp ptr nn, double ptr1d inputTable1d, int inputTupleMax, int inputColumnMax, double ptr1d targetTable1d, int targetTupleMax, int targetColumnMax, trainingType tt, int epochMax, int batchSize, double learningRate, double learningMomentumRate) { dbcRequire (tt == ttOnlineTraining, "Only Online Training Type is allowed."); dbcRequire (batchSize == 1, "Only batch size of 1 is allowed, due to the Online Training Type implementation."); // reset epoch statistics fn ()/ nn -> epochTally = 0; for (int epoch = 0; epoch < epochMax; epoch ++) { if (nn -> onTrainEpochBegin != NULL && nn -> onTrainEpochBegin (nn, inputTable1d, inputTupleMax, inputColumnMax, targetTable1d, targetTupleMax, targetColumnMax, epoch) == /* should we skip? */ true) continue ; // reset table statistics fn ()/ nn -> tupleTally = 0; //#pragma omp parallel for for (int r = 0; r < inputTupleMax; r ++) { //mlp ptr nw, double ptr inputTuple1d, int inputColumnMax, double ptr targetTuple1d, int targetColumnMax if (nn -> onTrainTupleBegin != NULL && nn -> onTrainTupleBegin (nn, addr inputTable1d [r * inputColumnMax], inputColumnMax, addr targetTable1d[r * targetColumnMax], targetColumnMax) == /* should we skip? */ true) continue ; mlpTrainTuple (nn, tt, addr inputTable1d [r * inputColumnMax], /*(double ptr)*/ addr targetTable1d [r * targetColumnMax], learningRate, learningMomentumRate); // update table statistics fn ()/ nn -> tupleTally ++; if (nn -> onTrainTupleEnd != NULL) nn -> onTrainTupleEnd (nn, addr inputTable1d [r * inputColumnMax], inputColumnMax, addr targetTable1d[r * targetColumnMax], targetColumnMax) ; } // update epoch statistics fn ()/ nn -> epochTally ++; if (nn -> onTrainEpochEnd != NULL) nn -> onTrainEpochEnd (nn, inputTable1d, inputTupleMax, inputColumnMax, targetTable1d, targetTupleMax, targetColumnMax, epoch) ; } } void mlpTrainTuple (mlp ptr nw, trainingType tt, double ptr input1d, double ptr target1d, double learningRate, double learningMomentumRate) { dbcRequire (tt == ttOnlineTraining, "Given Training Type not implemented yet."); mlpSetInput (nw, input1d); mlpSetTarget (nw, target1d); mlpPropagateForward (nw); mlpPropagateBackward (nw, learningRate, learningMomentumRate); } void mlpPredict (mlp ptr nn, double ptr2d input2d) { int inputEndTuple = sizeof (input2d); //#pragma omp parallel for for (int r = 0; r < inputEndTuple; r ++) { mlpPredictTuple (nn, input2d [r]); //printf ("%f XOR %f = %f. Predicted: %f\n", dataIn [r][0], dataIn [r][1], dataOut [r][0], ((layer ptr) nw -> layerLinkedList -> tail -> obj) -> neuron1d [0] -> axon -> output ); //printf ("%f XOR %f = %f. Target: %f; Predicted: %f.\n", input2d [r][0], input2d [r][1], dataOut [r][0], nw -> layer2d [nw -> totalLayerCount - 1] -> target1d [0], nw -> layer2d [nw -> totalLayerCount - 1] -> output1d [0] ); } } void mlpPredictTuple (mlp ptr nw, double ptr input1d) { mlpSetInput (nw, input1d); mlpPropagateForward (nw); } void mlpSetInput (mlp ptr nw, double ptr input1d) { mlpLayer ptr inputLayer = nw -> layer2d [0]; //#pragma omp parallel for for (int c = 0; c < inputLayer -> cellCount; c ++) { // <output = input> //inputLayer -> input2d [c][0] = input1d [c]; // We could omit this line. Kept for brevity. inputLayer -> output1d [c] = input1d [c]; // </output = input> } } void mlpSetTarget (mlp ptr nw, double ptr target1d) { mlpLayer ptr outputLayer = nw -> layer2d [nw -> totalLayerCount - 1]; //#pragma omp parallel for for (int c = 0; c < outputLayer -> cellCount; c ++) { outputLayer -> target1d [c] = target1d [c]; } }
boundaries.c
/* Author: Mohammed Ahmed Al Farhan Email: mohammed.farhan@kaust.edu.sa */ #include <stdio.h> #include <stdint.h> #include <omp.h> #include "inc/allocator.h" #include "inc/geometry.h" #include "inc/msh/mesh.h" #include "inc/msh/fio.h" static size_t fbmalloc(char *restrict fbuf, struct bface *restrict f) { size_t sz = f->sz * 4; uint32_t *restrict buf; kmalloc(sz, sizeof(uint32_t), (void *) &buf); size_t bytes = sz * sizeof(uint32_t); struct wtbl w; { w.l = fbuf; w.h = fbuf + bytes; w.t = UINT; w.sz = sz; } walkfbuf(&w, buf); uint32_t i; #pragma omp parallel for for(i = 0; i < f->sz; i++) { f->fptr[i].f0 = buf[i] - 1; f->fptr[i].f1 = buf[i + f->sz] - 1; f->fptr[i].f2 = buf[i + f->sz + f->sz] - 1; f->fptr[i].f3 = buf[i + f->sz + f->sz + f->sz] - 1; } kfree(buf); return bytes; } static size_t nbmalloc(char *restrict fbuf, struct bnode *restrict n) { size_t bytes = n->sz * sizeof(uint32_t); struct wtbl w0; { w0.l = fbuf; w0.h = fbuf + bytes; w0.t = UINT; w0.sz = n->sz; } walkfbuf(&w0, n->nptr); size_t sz = n->sz * 3; size_t bytes_ = sz * sizeof(double); double *restrict buf; kmalloc(sz, sizeof(double), (void *) &buf); struct wtbl w1; { w1.l = fbuf + bytes; w1.h = w1.l + bytes_; w1.t = DOUBLE; w1.sz = sz; } walkfbuf(&w1, buf); uint32_t i; #pragma omp parallel for for(i = 0; i < n->sz; i++) { n->nptr[i]--; n->xyz->x0[i] = buf[i]; n->xyz->x1[i] = buf[i + n->sz]; n->xyz->x2[i] = buf[i + n->sz + n->sz]; } kfree(buf); return (bytes + bytes_); } static size_t bmallocl(const size_t p1, const size_t p2, const size_t p3, char *restrict fbuf, struct boundary *restrict b) { // Shift the file pointer to avoid reading the boundaries data, // which they are negligible in our core calculations size_t bytes = p3 * 2 * sizeof(uint32_t); struct bface *restrict f; kmalloc(1, sizeof(struct bface), (void *) &f); f->sz = p1; kmalloc(f->sz, sizeof(struct facet), (void *) &f->fptr); bytes += fbmalloc((fbuf + bytes), f); b->f = f; struct bnode *restrict n; kmalloc(1, sizeof(struct bnode), (void *) &n); n->sz = p2; kmalloc(n->sz, sizeof(uint32_t), (void *) &n->nptr); kmalloc(1, sizeof(struct xyz), (void *) &n->xyz); kmalloc(n->sz, sizeof(double), (void *) &n->xyz->x0); kmalloc(n->sz, sizeof(double), (void *) &n->xyz->x1); kmalloc(n->sz, sizeof(double), (void *) &n->xyz->x2); bytes += nbmalloc((fbuf + bytes), n); b->n = n; return bytes; } size_t bmalloc(const uint32_t *restrict p, char *restrict fbuf, struct btbl *restrict b) { size_t bytes = 0; struct boundary *restrict s; kmalloc(1, sizeof(struct boundary), (void *) &s); bytes += bmallocl(p[6], p[9], p[3], fbuf, s); b->s = s; struct boundary *restrict f; kmalloc(1, sizeof(struct boundary), (void *) &f); bytes += bmallocl(p[8], p[11], p[5], (fbuf + bytes), f); b->f = f; return bytes; }
binop.c
#include <TH/TH.h> #include <stdio.h> #include <stdint.h> #include "matmul.h" inline uint32_t encode_val(float* array, int n) { uint32_t sign, r = 0; for(int i=0; i<ENCODE_BIT && i<n; i++){ sign = array[i]>0; r |= (sign<<i); } return r; } void encode_rows_cpu_kernel(float *columns, uint32_t *columns_binary, int m, int n) { int i, l = 1+(n-1)/ENCODE_BIT; //#pragma omp parallel for for (i = 0; i < m*l; i++) { int p = n*(i/l)+ENCODE_BIT*(i%l); columns_binary[i] = encode_val(&columns[p], n-ENCODE_BIT*(i%l)); } } void encode_cols_cpu_kernel(float *columns, uint32_t *columns_binary, int m, int n) { int col_bin_m = 1 + (m-1) / ENCODE_BIT; int i, j, k; //#pragma omp parallel for for (i = 0; i < col_bin_m; i++) { int i64 = i * ENCODE_BIT; for (j = 0; j < n && i64<m ; j++) { uint32_t sign, rvalue = 0; for (k = 0; j + n * (i64 + k) < m*n && k < ENCODE_BIT; k++) { sign = columns[j + n * (i64 + k)]>0; rvalue |= (sign << k); } columns_binary[j + n * i] = rvalue; } } } void encode_rows_cpu(THFloatTensor* input, THIntTensor* output) { int m = input->size[0]; int n = input->size[1]; int l = 1+(n-1)/ENCODE_BIT; THIntTensor_resize2d(output, m, l); float* a = THFloatTensor_data(input); uint32_t* b = (uint32_t*)THIntTensor_data(output); encode_rows_cpu_kernel(a, b, m, n); } void encode_cols_cpu(THFloatTensor* input, THIntTensor* output) { int n = input->size[0]; int k = input->size[1]; int l = 1+(n-1)/ENCODE_BIT; THIntTensor_resize2d(output, l, k); float* a = THFloatTensor_data(input); uint32_t* b = (uint32_t*)THIntTensor_data(output); encode_cols_cpu_kernel(a, b, n, k); } void binary_gemm_cpu(THIntTensor* a, THIntTensor* b, THFloatTensor* c, int m, int nn, int k, int transb, int beta, int alpha, THFloatTensor* alphas){ if (c->nDimension != 2 || c->size[0]*c->size[1] < m*k) { THFloatTensor_resize2d(c, m, k); } uint32_t *A = (uint32_t*)THIntTensor_data(a); uint32_t *B = (uint32_t*)THIntTensor_data(b); float *C = THFloatTensor_data(c); float *D = THFloatTensor_data(alphas); int n = 1 + (nn-1) / ENCODE_BIT, brow = transb? 1:k, bcol = transb? n:1; dgemm_nn(m, k, nn, A, n, 1, B, brow, bcol, C, k, 1, beta, alpha, D); } void THNN_unfolded_copy( THFloatTensor *columns, THFloatTensor *input, int kW, int kH, int dW, int dH, int padW, int padH, int nInputPlane, int inputWidth, int inputHeight, int outputWidth, int outputHeight) { // This function assumes that // kH*kW does not overflow an int // nInputPlane*kH*kW does not overflow a int64_t // outputHeight*dH does not overflow a int64_t // outputWidth*dW does not overflow a int64_t int64_t k; float *input_data = THFloatTensor_data(input); float *columns_data = THFloatTensor_data(columns); #pragma omp parallel for private(k) for(k = 0; k < (int64_t)nInputPlane*kH*kW; k++) { int64_t nip = k / (kH*kW); int64_t rest = k % (kH*kW); int64_t kh = rest / kW; int64_t kw = rest % kW; int x, y; int64_t ix, iy; float *dst = columns_data + nip*((size_t)kH*kW*outputHeight*outputWidth) + kh*((size_t)kW*outputHeight*outputWidth) + kw*((size_t)outputHeight*outputWidth); float *src = input_data + nip*((size_t)inputHeight*inputWidth); if (padW > 0 || padH > 0) { int64_t lpad,rpad; for(y = 0; y < outputHeight; y++) { iy = (int64_t)y*dH - padH + kh; if (iy < 0 || iy >= inputHeight) { memset(dst+(size_t)y*outputWidth, 0, sizeof(float)*outputWidth); } else { if (dW==1){ ix = 0 - padW + kw; lpad = fmaxf(0,padW-kw); rpad = fmaxf(0,padW-(kW-kw-1)); if (outputWidth-rpad-lpad <= 0) { memset(dst+(size_t)y*outputWidth, 0, sizeof(float)*outputWidth); } else { if (lpad > 0) memset(dst+(size_t)y*outputWidth, 0, sizeof(float)*lpad); memcpy(dst+(size_t)y*outputWidth+lpad, src+(size_t)iy*inputWidth+ix+lpad, sizeof(float)*(outputWidth-rpad-lpad)); if (rpad > 0) memset(dst+(size_t)y*outputWidth + outputWidth - rpad, 0, sizeof(float)*rpad); } } else{ for (x=0; x<outputWidth; x++){ ix = (int64_t)x*dW - padW + kw; if (ix < 0 || ix >= inputWidth) memset(dst+(size_t)y*outputWidth+x, 0, sizeof(float)*1); else memcpy(dst+(size_t)y*outputWidth+x, src+(size_t)iy*inputWidth+ix, sizeof(float)*(1)); } } } } } else { for(y = 0; y < outputHeight; y++) { iy = (int64_t)y*dH + kh; ix = 0 + kw; if (dW == 1) memcpy(dst+(size_t)y*outputWidth, src+(size_t)iy*inputWidth+ix, sizeof(float)*outputWidth); else{ for (x=0; x<outputWidth; x++) memcpy(dst+(size_t)y*outputWidth+x, src+(size_t)iy*inputWidth+ix+(int64_t)x*dW, sizeof(float)*(1)); } } } } } static void THNN_Bin_SpatialConvolutionMM_updateOutput_frame( THFloatTensor *output, THIntTensor *weight, THFloatTensor *bias, THFloatTensor *ones, THIntTensor *bin_col, THFloatTensor *alphas, int kW, int kH, int dW, int dH, int padW, int padH, int64_t nInputPlane, int64_t inputWidth, int64_t inputHeight, int64_t nOutputPlane, int64_t outputWidth, int64_t outputHeight) { THFloatTensor *output2d; output2d = THFloatTensor_newWithStorage2d(output->storage, output->storageOffset, nOutputPlane, -1, outputHeight*outputWidth, -1); THFloatTensor_zero(output2d); binary_gemm_cpu(weight, bin_col, output2d, nOutputPlane, kW*kH*nInputPlane, outputHeight*outputWidth, 0, 1, 1, alphas); if (bias->nDimension) { THFloatTensor_addmm(output2d, 1, output2d, 1, bias, ones); } THFloatTensor_free(output2d); } void THNN_Bin_SpatialConvolutionMM_updateOutput( THFloatTensor *input, THFloatTensor *output, THIntTensor *weight, THFloatTensor *bias, THFloatTensor *columns, THFloatTensor *alphas, int kH, int kW, int dH, int dW, int padH, int padW) { THIntTensor *bin_col = THIntTensor_new(); THFloatTensor *ones = THFloatTensor_new(); input = THFloatTensor_newContiguous(input); int ndim = input->nDimension; int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } int64_t nInputPlane = input->size[dimf]; int64_t inputHeight = input->size[dimh]; int64_t inputWidth = input->size[dimw]; int64_t nOutputPlane = weight->size[0]; int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; if (bias->nDimension ==1) { THFloatTensor_resize2d(bias, bias->size[0], 1); } THFloatTensor_resize2d(ones, 1, outputHeight*outputWidth); THFloatTensor_fill(ones, 1); int64_t T = input->size[0]; int64_t t; THFloatTensor_resize4d(output, T, nOutputPlane, outputHeight, outputWidth); THFloatTensor_resize3d(columns, T, kW*kH*nInputPlane, outputHeight*outputWidth); THIntTensor_resize3d(bin_col, T, weight->size[0], outputHeight*outputWidth); #pragma omp parallel for private(t) for(t = 0; t < T; t++) { THFloatTensor *input_t = THFloatTensor_newSelect(input, 0, t); THFloatTensor *columns_t = THFloatTensor_newSelect(columns, 0, t); THIntTensor *bin_col_t = THIntTensor_newSelect(bin_col, 0, t); THNN_unfolded_copy( columns_t, input_t, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, outputWidth, outputHeight ); encode_cols_cpu(columns_t, bin_col_t); THFloatTensor_free(input_t); THFloatTensor_free(columns_t); THIntTensor_free(bin_col_t); } for(t = 0; t < T; t++){ THFloatTensor *output_t = THFloatTensor_newSelect(output, 0, t); THIntTensor *bin_col_t = THIntTensor_newSelect(bin_col, 0, t); THNN_Bin_SpatialConvolutionMM_updateOutput_frame( output_t, weight, bias, ones, bin_col_t, alphas, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight ); THFloatTensor_free(output_t); THIntTensor_free(bin_col_t); } THFloatTensor_free(input); THFloatTensor_free(ones); THIntTensor_free(bin_col); }
9.race1.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 100 int main() { int A[N]; #pragma omp for for (int i = 1; i < N; i++) { A[i] = A[i] + A[i - 1]; } return 0; } // CHECK: Data Race detected // END
DRACC_OMP_051_MxV_working_no.c
/* Matrix Vector multiplication without application errors. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define C 512 int *a; int *b; int *c; int init(){ for(int i=0; i<C; i++){ for(int j=0; j<C; j++){ b[j+i*C]=1; } a[i]=1; c[i]=0; } return 0; } int Mult(){ #pragma omp target map(to:a[0:C],b[0:C*C]) map(from:c[0:C]) #pragma omp teams distribute parallel for for(int i=0; i<C; i++){ for(int j=0; j<C; j++){ c[i]+=b[j+i*C]*a[j]; } } return 0; } int check(){ bool test = false; for(int i=0; i<C; i++){ if(c[i]!=C){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ a = malloc(C*sizeof(int)); b = malloc(C*C*sizeof(int)); c = malloc(C*sizeof(int)); init(); Mult(); check(); free(a); free(b); free(c); return 0; }
brute.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> uint32_t table[3][4][256] = { /* [[[cog import cog, differentials def arrout(arr): return str(arr).replace('[', '{').replace(']', '}') cog.outl(arrout(differentials.tes) + ',') ds1 = [[te[a] ^ te[a^1] for a in range(256)] for te in differentials.tes] cog.outl(arrout(ds1) + ',') ds2 = [[te[a] ^ te[a^128] for a in range(256)] for te in differentials.tes] cog.outl(arrout(ds2)) ]]] */ {{3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986}, {2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766}, {1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126}, {1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436}}, {{1042226977, 1042226977, 403442708, 403442708, 697932208, 697932208, 1336584933, 1336584933, 1647391059, 1647391059, 2555137236, 2555137236, 1378429307, 1378429307, 2715671932, 2715671932, 2420656344, 2420656344, 1941222599, 1941222599, 1571005438, 1571005438, 1974974402, 1974974402, 4068047243, 4068047243, 437062935, 437062935, 1882732616, 1882732616, 2142417613, 2142417613, 2487896798, 2487896798, 1907733956, 1907733956, 302582043, 302582043, 1983593293, 1983593293, 965841320, 965841320, 672404540, 672404540, 1235855840, 1235855840, 1210328172, 1210328172, 2646852446, 2646852446, 3688947771, 3688947771, 126783113, 126783113, 631218106, 631218106, 706024767, 706024767, 3294782118, 3294782118, 2211236943, 2211236943, 2512897874, 2512897874, 260737669, 260737669, 1815492186, 1815492186, 3933566367, 3933566367, 4026202645, 4026202645, 3530123707, 3530123707, 3395642799, 3395642799, 2412431941, 2412431941, 1303096294, 1303096294, 528646813, 528646813, 3253595436, 3253595436, 2749160575, 2749160575, 3488279077, 3488279077, 1503764984, 1503764984, 361203602, 361203602, 201721354, 201721354, 899127202, 899127202, 2118074177, 2118074177, 2723238387, 2723238387, 470683154, 470683154, 2008463041, 2008463041, 1673313503, 1673313503, 4202528135, 4202528135, 3630984372, 3630984372, 1849112409, 1849112409, 4294111757, 4294111757, 2244988746, 2244988746, 504303377, 504303377, 2177748300, 2177748300, 336202270, 336202270, 3992714006, 3992714006, 3320835882, 3320835882, 1109467491, 1109467491, 2579611992, 2579611992, 3858759450, 3858759450, 2345191491, 2345191491, 2790478837, 2790478837, 3328402341, 3328402341, 2252555205, 2252555205, 1916352843, 1916352843, 3563743934, 3563743934, 3655459128, 3655459128, 1033081774, 1033081774, 268961816, 268961816, 806885416, 806885416, 1269344483, 1269344483, 1135389935, 1135389935, 461406363, 461406363, 3151024235, 3151024235, 3218264685, 3218264685, 1613770832, 1613770832, 2655997905, 2655997905, 4034427016, 4034427016, 571543859, 571543859, 2278477385, 2278477385, 134480908, 134480908, 563977660, 563977660, 1580150641, 1580150641, 3025820398, 3025820398, 2958579944, 2958579944, 3588745010, 3588745010, 1949973070, 1949973070, 1008606754, 1008606754, 1042226977, 1042226977, 1470539505, 1470539505, 2680341085, 2680341085, 369822493, 369822493, 1874508501, 1874508501, 3832705686, 3832705686, 1781871967, 1781871967, 3597364157, 3597364157, 4160157185, 4160157185, 33620227, 33620227, 2622377682, 2622377682, 3184776046, 3184776046, 2521517021, 2521517021, 3958962195, 3958962195, 2824099068, 2824099068, 3354324521, 3354324521, 2387036105, 2387036105, 495158174, 495158174, 840505643, 840505643, 160008576, 160008576, 2075177163, 2075177163, 874125870, 874125870, 293963156, 293963156, 3698224818, 3698224818, 765172662, 765172662, 4126668546, 4126668546, 1512910199, 1512910199, 327451799, 327451799, 2992200171, 2992200171, 1412049534, 1412049534, 2883115123, 2883115123, 1143087718, 1143087718, 3554993207, 3554993207, 1101901292, 1101901292}, {557719327, 557719327, 337120268, 337120268, 2955516313, 2955516313, 3847203498, 3847203498, 1398944049, 1398944049, 3566750796, 3566750796, 2068982057, 2068982057, 2090982877, 2090982877, 3633334344, 3633334344, 3346248884, 3346248884, 4267549603, 4267549603, 3262494647, 3262494647, 2347923833, 2347923833, 387583245, 387583245, 1215313976, 1215313976, 3447698098, 3447698098, 3734260298, 3734260298, 3295786421, 3295786421, 454166793, 454166793, 1299594043, 1299594043, 2822345105, 2822345105, 1009259540, 1009259540, 3762923945, 3762923945, 1816667172, 1816667172, 1587397571, 1587397571, 1004265696, 1004265696, 2298973838, 2298973838, 3123027871, 3123027871, 1059722517, 1059722517, 2797888098, 2797888098, 1334037708, 1334037708, 1385547719, 1385547719, 2232388234, 2232388234, 1517041206, 1517041206, 2682942837, 2682942837, 368048890, 368048890, 3151128937, 3151128937, 2949277029, 2949277029, 1167051466, 1167051466, 3863849899, 3863849899, 2636087938, 2636087938, 750906861, 750906861, 2141445340, 2141445340, 634383082, 634383082, 4166623649, 4166623649, 2450884487, 2450884487, 168560134, 168560134, 2721421207, 2721421207, 1098792767, 1098792767, 4087501137, 4087501137, 303828494, 303828494, 3245848246, 3245848246, 3747855548, 3747855548, 2281340285, 2281340285, 3034082412, 3034082412, 1500395319, 1500395319, 234877682, 234877682, 1250283471, 1250283471, 287182607, 287182607, 1283575245, 1283575245, 504629770, 504629770, 384695291, 384695291, 717615087, 717615087, 1665278241, 1665278241, 1486471617, 1486471617, 451280895, 451280895, 1133234376, 1133234376, 4121318227, 4121318227, 2781242211, 2781242211, 3313910595, 3313910595, 1265776953, 1265776953, 3201591914, 3201591914, 953803233, 953803233, 2923271059, 2923271059, 403703816, 403703816, 674240536, 674240536, 3813386408, 3813386408, 4014189740, 4014189740, 2602270848, 2602270848, 1807470800, 1807470800, 1841287890, 1841287890, 1348481072, 1348481072, 3516813135, 3516813135, 2297460856, 2297460856, 857870609, 857870609, 1233637070, 1233637070, 201851908, 201851908, 3156319645, 3156319645, 1901997871, 1901997871, 4004797018, 4004797018, 3903871064, 3903871064, 852879335, 852879335, 1316239930, 1316239930, 574365214, 574365214, 557719327, 557719327, 4049053350, 4049053350, 1570751170, 1570751170, 487983883, 487983883, 3580869306, 3580869306, 2531553906, 2531553906, 1600795957, 1600795957, 3184946027, 3184946027, 33027830, 33027830, 50462977, 50462977, 3533459022, 3533459022, 1857934291, 1857934291, 3717614411, 3717614411, 334231800, 334231800, 4238890068, 4238890068, 700968686, 700968686, 3381544775, 3381544775, 2652734339, 2652734339, 724703513, 724703513, 2148108681, 2148108681, 3413881008, 3413881008, 775166490, 775166490, 2484176261, 2484176261, 3000790638, 3000790638, 3056442267, 3056442267, 49674231, 49674231, 2002398509, 2002398509, 2534638724, 2534638724, 3954334041, 3954334041, 2119445034, 2119445034, 1940642008, 1940642008, 1715741218, 1715741218, 936633572, 936633572, 3963727277, 3963727277}, {522272287, 522272287, 202643468, 202643468, 2578459033, 2578459033, 2867154858, 2867154858, 827548209, 827548209, 1289001036, 1289001036, 695947817, 695947817, 3715932637, 3715932637, 1222152264, 1222152264, 3032970164, 3032970164, 2751356323, 2751356323, 3082974647, 3082974647, 2039214713, 2039214713, 219617805, 219617805, 944271416, 944271416, 2999812018, 2999812018, 1256100938, 1256100938, 3049550261, 3049550261, 152769033, 152769033, 994932283, 994932283, 2443721105, 2443721105, 339486740, 339486740, 2850048425, 2850048425, 611076132, 611076132, 3277757891, 3277757891, 3762019296, 3762019296, 2391345038, 2391345038, 2679776671, 2679776671, 356461077, 356461077, 1655096418, 1655096418, 3427763148, 3427763148, 3344078279, 3344078279, 2323976074, 2323976074, 911895606, 911895606, 1973414517, 1973414517, 4195741690, 4195741690, 1773916777, 1773916777, 1706019429, 1706019429, 3393556426, 3393556426, 2883997099, 2883997099, 2191335298, 2191335298, 3979133421, 3979133421, 3699352540, 3699352540, 3928346602, 3928346602, 2717407649, 2717407649, 2274497927, 2274497927, 101321734, 101321734, 2543990167, 2543990167, 1061256767, 1061256767, 1374921297, 1374921297, 236067854, 236067854, 3066132406, 3066132406, 3168756668, 3168756668, 2106063485, 2106063485, 1823791212, 1823791212, 928607799, 928607799, 4061003762, 4061003762, 3477767631, 3477767631, 252780047, 252780047, 3444343245, 3444343245, 169743370, 169743370, 4212583931, 4212583931, 4012557807, 4012557807, 560153121, 560153121, 3243809217, 3243809217, 4279952895, 4279952895, 3359869896, 3359869896, 1408607827, 1408607827, 1671808611, 1671808611, 1137018435, 1137018435, 961245753, 961245753, 1790891114, 1790891114, 3778599393, 3778599393, 2477669779, 2477669779, 135794696, 135794696, 405286936, 405286936, 2833468328, 2833468328, 2901361580, 2901361580, 2157648768, 2157648768, 3496721360, 3496721360, 3530407890, 3530407890, 810573872, 810573872, 1339137615, 1339137615, 2022240376, 2022240376, 288563729, 288563729, 3460925390, 3460925390, 67897348, 67897348, 2646352285, 2646352285, 795958831, 795958831, 1525593178, 1525593178, 1491644504, 1491644504, 3878868455, 3878868455, 978220090, 978220090, 505560094, 505560094, 522272287, 522272287, 2800834470, 2800834470, 3260915650, 3260915650, 186455563, 186455563, 3134549946, 3134549946, 1922491506, 1922491506, 895445557, 895445557, 1807603307, 1807603307, 4127324150, 4127324150, 16974337, 16974337, 1322425422, 1322425422, 3547250131, 3547250131, 1272813131, 1272813131, 4162055160, 4162055160, 1425844308, 1425844308, 3995715566, 3995715566, 1204391495, 1204391495, 2208177539, 2208177539, 422261273, 422261273, 2306869641, 2306869641, 2966125488, 2966125488, 439235610, 439235610, 2241073541, 2241073541, 1857215598, 1857215598, 2612407707, 2612407707, 4144166391, 4144166391, 762796589, 762796589, 2224493444, 2224493444, 1508618841, 1508618841, 712922154, 712922154, 3631459288, 3631459288, 577127458, 577127458, 3828863972, 3828863972, 2917941677, 2917941677}, {522133822, 522133822, 202118168, 202118168, 2576986153, 2576986153, 2863326543, 2863326543, 825316194, 825316194, 1280103576, 1280103576, 690584402, 690584402, 3722280097, 3722280097, 1212733584, 1212733584, 3031746419, 3031746419, 2745433693, 2745433693, 3082273397, 3082273397, 2038008818, 2038008818, 218961690, 218961690, 943212656, 943212656, 2998062463, 2998062463, 1246420628, 1246420628, 3048588401, 3048588401, 151591698, 151591698, 993742198, 993742198, 2442242105, 2442242105, 336870440, 336870440, 2846482505, 2846482505, 606366792, 606366792, 3284360861, 3284360861, 3772791771, 3772791771, 2391705863, 2391705863, 2678045221, 2678045221, 353713962, 353713962, 1650632388, 1650632388, 3435941763, 3435941763, 3351728789, 3351728789, 2324333839, 2324333839, 909531756, 909531756, 1970642922, 1970642922, 4210693615, 4210693615, 1768537042, 1768537042, 1701162954, 1701162954, 3402253711, 3402253711, 2880169549, 2880169549, 2189597983, 2189597983, 3991743681, 3991743681, 3705438115, 3705438115, 3941213647, 3941213647, 2711746649, 2711746649, 2273808917, 2273808917, 101059084, 101059084, 2543297077, 2543297077, 1061110142, 1061110142, 1364325282, 1364325282, 235803164, 235803164, 3065430391, 3065430391, 3166494563, 3166494563, 2105378810, 2105378810, 1819063512, 1819063512, 926374254, 926374254, 4075949567, 4075949567, 3486468741, 3486468741, 252645662, 252645662, 3452783745, 3452783745, 168435220, 168435220, 4227536621, 4227536621, 4025428677, 4025428677, 555836226, 555836226, 3250673817, 3250673817, 4294908645, 4294908645, 3368567691, 3368567691, 1398011302, 1398011302, 1667474886, 1667474886, 1128514950, 1128514950, 960056178, 960056178, 1785380564, 1785380564, 3789633753, 3789633753, 2475929149, 2475929149, 134748176, 134748176, 404236336, 404236336, 2829640523, 2829640523, 2897014595, 2897014595, 2155911963, 2155911963, 3503319995, 3503319995, 3537006015, 3537006015, 808472672, 808472672, 1330631070, 1330631070, 2021165296, 2021165296, 286339874, 286339874, 3469625735, 3469625735, 67374088, 67374088, 2644360225, 2644360225, 791638366, 791638366, 1515908788, 1515908788, 1482221744, 1482221744, 3890688725, 3890688725, 976899700, 976899700, 505291324, 505291324, 522133822, 522133822, 2795958615, 2795958615, 3267517855, 3267517855, 185277718, 185277718, 3132806511, 3132806511, 1920112356, 1920112356, 892690282, 892690282, 1802223062, 1802223062, 4143317495, 4143317495, 16843522, 16843522, 1313788572, 1313788572, 3553849021, 3553849021, 1263263126, 1263263126, 4177007595, 4177007595, 1414855848, 1414855848, 4008585671, 4008585671, 1195886990, 1195886990, 2206440989, 2206440989, 421079858, 421079858, 2307489801, 2307489801, 2964376443, 2964376443, 437923380, 437923380, 2240123921, 2240123921, 1852748508, 1852748508, 2610673197, 2610673197, 4160160501, 4160160501, 757954394, 757954394, 2223281939, 2223281939, 1499065266, 1499065266, 707427924, 707427924, 3638064043, 3638064043, 572679748, 572679748, 3840161747, 3840161747, 2913856577, 2913856577}}, {{1202630377, 3765465232, 3362022572, 899127202, 1101901292, 3825007647, 1445669757, 3218264685, 4092916743, 1470539505, 840505643, 739644986, 798661301, 260737669, 2142417613, 168101135, 1336584933, 100860677, 394692241, 1503764984, 2883115123, 3866325909, 3050821474, 4034427016, 3454790438, 1949973070, 874125870, 1841019862, 2218934982, 4026202645, 4068047243, 907746093, 2924959737, 2244988746, 1235855840, 1479289972, 4269768577, 1916352843, 3184776046, 999329963, 4160157185, 3967186586, 2454276571, 1033081774, 3688947771, 2588757463, 2983581028, 3630984372, 3722699582, 504303377, 672404540, 1202630377, 831886756, 2252555205, 2521517021, 1714631509, 3597364157, 2286175436, 3899946140, 268961816, 126783113, 3126681063, 941366308, 4202528135, 2108928974, 3992714006, 302582043, 1748251740, 235341577, 2345191491, 3354324521, 3429263018, 1874508501, 3622233649, 1604494077, 1135389935, 3294782118, 3160301282, 1403299063, 470683154, 1176707941, 3320835882, 1907733956, 227249030, 3496503480, 3858759450, 2387036105, 2857719295, 369822493, 3892248089, 3387549984, 461406363, 2211236943, 26054028, 2319795663, 2723238387, 1647391059, 773265209, 1681011286, 3488279077, 1412049534, 865375399, 1639824860, 571543859, 2816401017, 3588745010, 293963156, 932615841, 664706745, 3530123707, 1974974402, 4000806809, 2715671932, 67240454, 2311702848, 528646813, 1512910199, 4135287693, 4101667470, 563977660, 3791519004, 1580150641, 4126668546, 1546530418, 1537253627, 1303096294, 2420656344, 2479146071, 1202630377, 3765465232, 3362022572, 899127202, 1101901292, 3825007647, 1445669757, 3218264685, 4092916743, 1470539505, 840505643, 739644986, 798661301, 260737669, 2142417613, 168101135, 1336584933, 100860677, 394692241, 1503764984, 2883115123, 3866325909, 3050821474, 4034427016, 3454790438, 1949973070, 874125870, 1841019862, 2218934982, 4026202645, 4068047243, 907746093, 2924959737, 2244988746, 1235855840, 1479289972, 4269768577, 1916352843, 3184776046, 999329963, 4160157185, 3967186586, 2454276571, 1033081774, 3688947771, 2588757463, 2983581028, 3630984372, 3722699582, 504303377, 672404540, 1202630377, 831886756, 2252555205, 2521517021, 1714631509, 3597364157, 2286175436, 3899946140, 268961816, 126783113, 3126681063, 941366308, 4202528135, 2108928974, 3992714006, 302582043, 1748251740, 235341577, 2345191491, 3354324521, 3429263018, 1874508501, 3622233649, 1604494077, 1135389935, 3294782118, 3160301282, 1403299063, 470683154, 1176707941, 3320835882, 1907733956, 227249030, 3496503480, 3858759450, 2387036105, 2857719295, 369822493, 3892248089, 3387549984, 461406363, 2211236943, 26054028, 2319795663, 2723238387, 1647391059, 773265209, 1681011286, 3488279077, 1412049534, 865375399, 1639824860, 571543859, 2816401017, 3588745010, 293963156, 932615841, 664706745, 3530123707, 1974974402, 4000806809, 2715671932, 67240454, 2311702848, 528646813, 1512910199, 4135287693, 4101667470, 563977660, 3791519004, 1580150641, 4126668546, 1546530418, 1537253627, 1303096294, 2420656344, 2479146071}, {3913789102, 2430627952, 2898814052, 2721421207, 3963727277, 535035132, 2102799147, 1841287890, 133428468, 4049053350, 724703513, 975967766, 3039795866, 2232388234, 3447698098, 252314885, 3847203498, 84280067, 2434238086, 4166623649, 1940642008, 2514908019, 1656084439, 2297460856, 651029483, 1316239930, 775166490, 3597515707, 3330556482, 368048890, 2347923833, 758520603, 4188952407, 1250283471, 3762923945, 1951935532, 2180939647, 1265776953, 1857934291, 2872807568, 33027830, 2599188086, 3683797321, 2923271059, 1004265696, 3617213773, 1689376213, 3034082412, 1054729187, 287182607, 1009259540, 3913789102, 2754712981, 3313910595, 3717614411, 1432761139, 3184946027, 3431482436, 2632479860, 403703816, 2298973838, 3887750493, 607656988, 2281340285, 3464344499, 384695291, 454166793, 1550332980, 151914247, 1133234376, 700968686, 2865522278, 3580869306, 836232934, 4250903202, 4014189740, 2797888098, 3803995742, 4149453988, 303828494, 1699095331, 717615087, 3295786421, 2249034635, 3100665960, 451280895, 3381544775, 4289353045, 487983883, 434634494, 550103529, 2602270848, 1334037708, 2348912013, 3481945413, 4087501137, 1398944049, 959321879, 1449407026, 634383082, 2119445034, 2805175444, 3697393085, 857870609, 2041044702, 852879335, 2484176261, 2704774806, 3106381470, 3151128937, 3262494647, 2582542199, 2090982877, 100925954, 1082771913, 2636087938, 2002398509, 2381740923, 2398386810, 3156319645, 484572669, 1901997871, 49674231, 1918643758, 4217086112, 3863849899, 3633334344, 1469301956, 3913789102, 2430627952, 2898814052, 2721421207, 3963727277, 535035132, 2102799147, 1841287890, 133428468, 4049053350, 724703513, 975967766, 3039795866, 2232388234, 3447698098, 252314885, 3847203498, 84280067, 2434238086, 4166623649, 1940642008, 2514908019, 1656084439, 2297460856, 651029483, 1316239930, 775166490, 3597515707, 3330556482, 368048890, 2347923833, 758520603, 4188952407, 1250283471, 3762923945, 1951935532, 2180939647, 1265776953, 1857934291, 2872807568, 33027830, 2599188086, 3683797321, 2923271059, 1004265696, 3617213773, 1689376213, 3034082412, 1054729187, 287182607, 1009259540, 3913789102, 2754712981, 3313910595, 3717614411, 1432761139, 3184946027, 3431482436, 2632479860, 403703816, 2298973838, 3887750493, 607656988, 2281340285, 3464344499, 384695291, 454166793, 1550332980, 151914247, 1133234376, 700968686, 2865522278, 3580869306, 836232934, 4250903202, 4014189740, 2797888098, 3803995742, 4149453988, 303828494, 1699095331, 717615087, 3295786421, 2249034635, 3100665960, 451280895, 3381544775, 4289353045, 487983883, 434634494, 550103529, 2602270848, 1334037708, 2348912013, 3481945413, 4087501137, 1398944049, 959321879, 1449407026, 634383082, 2119445034, 2805175444, 3697393085, 857870609, 2041044702, 852879335, 2484176261, 2704774806, 3106381470, 3151128937, 3262494647, 2582542199, 2090982877, 100925954, 1082771913, 2636087938, 2002398509, 2381740923, 2398386810, 3156319645, 484572669, 1901997871, 49674231, 1918643758, 4217086112, 3863849899, 3633334344, 1469301956}, {2934523822, 1888542832, 1689045092, 2543990167, 2917941677, 4229948412, 729634347, 3530407890, 4094161908, 2800834470, 422261273, 372911126, 2595565466, 2323976074, 2999812018, 84871685, 2867154858, 50660867, 2257655686, 2717407649, 3631459288, 1939203699, 3613570519, 2022240376, 3945188843, 978220090, 439235610, 3151392187, 1120306242, 4195741690, 2039214713, 455947803, 1475980887, 3477767631, 2850048425, 745822252, 2139225727, 961245753, 3547250131, 2427141008, 4127324150, 1989864566, 1239126601, 2477669779, 3762019296, 1305975373, 3580146133, 1823791212, 3812548067, 252780047, 339486740, 2934523822, 2510565781, 1137018435, 1272813131, 861234739, 1807603307, 1154254916, 1956440180, 135794696, 2391345038, 1575467613, 472135708, 2106063485, 3016654259, 4212583931, 152769033, 878471220, 118033927, 3359869896, 3995715566, 1722469478, 3134549946, 3862026214, 2734514082, 2901361580, 1655096418, 1591917662, 2767672228, 236067854, 593839651, 4012557807, 3049550261, 2340818315, 1756942440, 4279952895, 1204391495, 1442818645, 186455563, 4263110654, 3911240169, 2157648768, 3427763148, 2374762893, 1171229253, 1374921297, 827548209, 389623319, 844522546, 3928346602, 712922154, 2493985684, 3185336765, 288563729, 3732514782, 3878868455, 2241073541, 2527147926, 2662934430, 1773916777, 3082974647, 2006576759, 3715932637, 33948674, 3376449993, 2191335298, 762796589, 2072901243, 2056189050, 2646352285, 4246528509, 795958831, 4144166391, 779246638, 2700827552, 2883997099, 1222152264, 3294073796, 2934523822, 1888542832, 1689045092, 2543990167, 2917941677, 4229948412, 729634347, 3530407890, 4094161908, 2800834470, 422261273, 372911126, 2595565466, 2323976074, 2999812018, 84871685, 2867154858, 50660867, 2257655686, 2717407649, 3631459288, 1939203699, 3613570519, 2022240376, 3945188843, 978220090, 439235610, 3151392187, 1120306242, 4195741690, 2039214713, 455947803, 1475980887, 3477767631, 2850048425, 745822252, 2139225727, 961245753, 3547250131, 2427141008, 4127324150, 1989864566, 1239126601, 2477669779, 3762019296, 1305975373, 3580146133, 1823791212, 3812548067, 252780047, 339486740, 2934523822, 2510565781, 1137018435, 1272813131, 861234739, 1807603307, 1154254916, 1956440180, 135794696, 2391345038, 1575467613, 472135708, 2106063485, 3016654259, 4212583931, 152769033, 878471220, 118033927, 3359869896, 3995715566, 1722469478, 3134549946, 3862026214, 2734514082, 2901361580, 1655096418, 1591917662, 2767672228, 236067854, 593839651, 4012557807, 3049550261, 2340818315, 1756942440, 4279952895, 1204391495, 1442818645, 186455563, 4263110654, 3911240169, 2157648768, 3427763148, 2374762893, 1171229253, 1374921297, 827548209, 389623319, 844522546, 3928346602, 712922154, 2493985684, 3185336765, 288563729, 3732514782, 3878868455, 2241073541, 2527147926, 2662934430, 1773916777, 3082974647, 2006576759, 3715932637, 33948674, 3376449993, 2191335298, 762796589, 2072901243, 2056189050, 2646352285, 4246528509, 795958831, 4144166391, 779246638, 2700827552, 2883997099, 1222152264, 3294073796}, {2930698567, 1886425312, 1684319432, 2543297077, 2913856577, 4244381667, 724270422, 3537006015, 4109633523, 2795958615, 421079858, 370555436, 2593830191, 2324333839, 2998062463, 84217610, 2863326543, 50529542, 2256965911, 2711746649, 3638064043, 1936954854, 3621216949, 2021165296, 3958056653, 976899700, 437923380, 3149649517, 1111672452, 4210693615, 2038008818, 454765878, 1465383342, 3486468741, 2846482505, 741110872, 2139062782, 960056178, 3553849021, 2425400123, 4143317495, 1987484396, 1229577106, 2475929149, 3772791771, 1296947098, 3587531953, 1819063512, 3823320797, 252645662, 336870440, 2930698567, 2509612081, 1128514950, 1263263126, 859002214, 1802223062, 1145359496, 1953799400, 134748176, 2391705863, 1566435258, 471606328, 2105378810, 3014905469, 4227536621, 151591698, 875846760, 117901582, 3368567691, 4008585671, 1718004428, 3132806511, 3873845719, 2728590687, 2897014595, 1650632388, 1583276732, 2762274643, 235803164, 589522246, 4025428677, 3048588401, 2341176845, 1751693520, 4294908645, 1195886990, 1431699370, 185277718, 4278065639, 3924369609, 2155911963, 3435941763, 2374863873, 1162203018, 1364325282, 825316194, 387397934, 842159716, 3941213647, 707427924, 2492770099, 3183336545, 286339874, 3739122087, 3890688725, 2240123921, 2526454071, 2661202215, 1768537042, 3082273397, 2004326894, 3722280097, 33687044, 3385409673, 2189597983, 757954394, 2071694838, 2054852340, 2644360225, 4261223649, 791638366, 4160160501, 774795868, 2694904667, 2880169549, 1212733584, 3301201811, 2930698567, 1886425312, 1684319432, 2543297077, 2913856577, 4244381667, 724270422, 3537006015, 4109633523, 2795958615, 421079858, 370555436, 2593830191, 2324333839, 2998062463, 84217610, 2863326543, 50529542, 2256965911, 2711746649, 3638064043, 1936954854, 3621216949, 2021165296, 3958056653, 976899700, 437923380, 3149649517, 1111672452, 4210693615, 2038008818, 454765878, 1465383342, 3486468741, 2846482505, 741110872, 2139062782, 960056178, 3553849021, 2425400123, 4143317495, 1987484396, 1229577106, 2475929149, 3772791771, 1296947098, 3587531953, 1819063512, 3823320797, 252645662, 336870440, 2930698567, 2509612081, 1128514950, 1263263126, 859002214, 1802223062, 1145359496, 1953799400, 134748176, 2391705863, 1566435258, 471606328, 2105378810, 3014905469, 4227536621, 151591698, 875846760, 117901582, 3368567691, 4008585671, 1718004428, 3132806511, 3873845719, 2728590687, 2897014595, 1650632388, 1583276732, 2762274643, 235803164, 589522246, 4025428677, 3048588401, 2341176845, 1751693520, 4294908645, 1195886990, 1431699370, 185277718, 4278065639, 3924369609, 2155911963, 3435941763, 2374863873, 1162203018, 1364325282, 825316194, 387397934, 842159716, 3941213647, 707427924, 2492770099, 3183336545, 286339874, 3739122087, 3890688725, 2240123921, 2526454071, 2661202215, 1768537042, 3082273397, 2004326894, 3722280097, 33687044, 3385409673, 2189597983, 757954394, 2071694838, 2054852340, 2644360225, 4261223649, 791638366, 4160160501, 774795868, 2694904667, 2880169549, 1212733584, 3301201811}} // [[[end]]] }; int main(int argc, char** argv) { // args: [table#] [parameter], prints space-separated indices into the table int ti = atoi(argv[1]); uint32_t target = atoll(argv[2]); if (ti == 0) { #pragma omp parallel for schedule(static, 64) for (int a = 0; a < 256; a++) { for (int b = 0; b < 256; b++) { for (int c = 0; c < 256; c++) { for (int d = 0; d < 256; d++) { uint32_t res = table[0][0][a] ^ table[0][1][b] ^ table[0][2][c] ^ table[0][3][d]; if (res == target) { printf("%d %d %d %d\n", a, b, c, d); //return 0; } } } } } } else if (ti == 1) { #pragma omp parallel for schedule(static) for (int a = 0; a < 256; a += 2) { for (int b = 0; b < 256; b += 2) { for (int c = 0; c < 256; c += 2) { for (int d = 0; d < 256; d += 2) { uint32_t res = table[1][0][a] ^ table[1][1][b] ^ table[1][2][c] ^ table[1][3][d]; if (res == target) { // [[[cog // import cog, itertools // for a,b,c,d in itertools.product([0, 1], repeat=4): // cog.outl(f'printf("%d %d %d %d\\n", a|{a}, b|{b}, c|{c}, d|{d});') // ]]] printf("%d %d %d %d\n", a|0, b|0, c|0, d|0); printf("%d %d %d %d\n", a|0, b|0, c|0, d|1); printf("%d %d %d %d\n", a|0, b|0, c|1, d|0); printf("%d %d %d %d\n", a|0, b|0, c|1, d|1); printf("%d %d %d %d\n", a|0, b|1, c|0, d|0); printf("%d %d %d %d\n", a|0, b|1, c|0, d|1); printf("%d %d %d %d\n", a|0, b|1, c|1, d|0); printf("%d %d %d %d\n", a|0, b|1, c|1, d|1); printf("%d %d %d %d\n", a|1, b|0, c|0, d|0); printf("%d %d %d %d\n", a|1, b|0, c|0, d|1); printf("%d %d %d %d\n", a|1, b|0, c|1, d|0); printf("%d %d %d %d\n", a|1, b|0, c|1, d|1); printf("%d %d %d %d\n", a|1, b|1, c|0, d|0); printf("%d %d %d %d\n", a|1, b|1, c|0, d|1); printf("%d %d %d %d\n", a|1, b|1, c|1, d|0); printf("%d %d %d %d\n", a|1, b|1, c|1, d|1); /// [[[end]]] //return 0; } } } } } } else if (ti == 2) { #pragma omp parallel for schedule(static) for (int a = 0; a < 128; a++) { for (int b = 0; b < 128; b++) { for (int c = 0; c < 128; c++) { for (int d = 0; d < 128; d++) { uint32_t res = table[2][0][a] ^ table[2][1][b] ^ table[2][2][c] ^ table[2][3][d]; if (res == target) { // [[[cog // import cog, itertools // for a,b,c,d in itertools.product([0, 128], repeat=4): // cog.outl(f'printf("%d %d %d %d\\n", a|{a}, b|{b}, c|{c}, d|{d});') // ]]] printf("%d %d %d %d\n", a|0, b|0, c|0, d|0); printf("%d %d %d %d\n", a|0, b|0, c|0, d|128); printf("%d %d %d %d\n", a|0, b|0, c|128, d|0); printf("%d %d %d %d\n", a|0, b|0, c|128, d|128); printf("%d %d %d %d\n", a|0, b|128, c|0, d|0); printf("%d %d %d %d\n", a|0, b|128, c|0, d|128); printf("%d %d %d %d\n", a|0, b|128, c|128, d|0); printf("%d %d %d %d\n", a|0, b|128, c|128, d|128); printf("%d %d %d %d\n", a|128, b|0, c|0, d|0); printf("%d %d %d %d\n", a|128, b|0, c|0, d|128); printf("%d %d %d %d\n", a|128, b|0, c|128, d|0); printf("%d %d %d %d\n", a|128, b|0, c|128, d|128); printf("%d %d %d %d\n", a|128, b|128, c|0, d|0); printf("%d %d %d %d\n", a|128, b|128, c|0, d|128); printf("%d %d %d %d\n", a|128, b|128, c|128, d|0); printf("%d %d %d %d\n", a|128, b|128, c|128, d|128); /// [[[end]]] //return 0; } } } } } } return 0; }
gemver.orio.par.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) #include "decl.h" double rtclock() { struct timezone tzp; struct timeval tp; int stat; gettimeofday (&tp, &tzp); return (tp.tv_sec + tp.tv_usec*1.0e-6); } int main() { init_input_vars(); double annot_t_start=0, annot_t_end=0, annot_t_total=0; int annot_i; for (annot_i=0; annot_i<REPS; annot_i++) { annot_t_start = rtclock(); #ifdef DYNAMIC int i,j; for (i=0; i<=n-1; i=i+1) { x[i]=0; w[i]=0; } { for (j=0; j<=n-1; j=j+1) { double scv_9, scv_10, scv_11; scv_9=u2[j]; scv_10=u1[j]; scv_11=y[j]; { for (i=0; i<=n-3; i=i+3) { double scv_1, scv_2, scv_3, scv_4, scv_5, scv_6; scv_1=x[(i+1)]; scv_2=B[j*n+i]; scv_3=x[(i+2)]; scv_4=B[j*n+i+2]; scv_5=B[j*n+i+1]; scv_6=x[i]; scv_2=scv_9*v2[i]+scv_10*v1[i]+A[j*n+i]; scv_5=scv_9*v2[(i+1)]+scv_10*v1[(i+1)]+A[j*n+i+1]; scv_4=scv_9*v2[(i+2)]+scv_10*v1[(i+2)]+A[j*n+i+2]; scv_6=scv_11*scv_2+scv_6; scv_1=scv_11*scv_5+scv_1; scv_3=scv_11*scv_4+scv_3; x[(i+1)]=scv_1; B[j*n+i]=scv_2; x[(i+2)]=scv_3; B[j*n+i+2]=scv_4; B[j*n+i+1]=scv_5; x[i]=scv_6; } for (; i<=n-1; i=i+1) { double scv_7, scv_8; scv_7=x[i]; scv_8=B[j*n+i]; scv_8=scv_9*v2[i]+scv_10*v1[i]+A[j*n+i]; scv_7=scv_11*scv_8+scv_7; x[i]=scv_7; B[j*n+i]=scv_8; } } } } { #pragma omp parallel for private(i) for (i=0; i<=n-1; i=i+1) { x[i]=b*x[i]+z[i]; } } { #pragma omp parallel for private(j,i) for (i=0; i<=n-6; i=i+6) { double scv_6, scv_7, scv_8, scv_9, scv_10, scv_11; scv_6=w[i]; scv_7=w[(i+1)]; scv_8=w[(i+5)]; scv_9=w[(i+4)]; scv_10=w[(i+3)]; scv_11=w[(i+2)]; register int cbv_1; cbv_1=n-4; #pragma ivdep #pragma vector always for (j=0; j<=cbv_1; j=j+4) { double scv_1, scv_2, scv_3, scv_4; scv_1=x[j]; scv_2=x[(j+3)]; scv_3=x[(j+2)]; scv_4=x[(j+1)]; scv_6=scv_6+B[i*n+j]*scv_1; scv_7=scv_7+B[(i+1)*n+j]*scv_1; scv_11=scv_11+B[(i+2)*n+j]*scv_1; scv_10=scv_10+B[(i+3)*n+j]*scv_1; scv_9=scv_9+B[(i+4)*n+j]*scv_1; scv_8=scv_8+B[(i+5)*n+j]*scv_1; scv_6=scv_6+B[i*n+j+1]*scv_4; scv_7=scv_7+B[(i+1)*n+j+1]*scv_4; scv_11=scv_11+B[(i+2)*n+j+1]*scv_4; scv_10=scv_10+B[(i+3)*n+j+1]*scv_4; scv_9=scv_9+B[(i+4)*n+j+1]*scv_4; scv_8=scv_8+B[(i+5)*n+j+1]*scv_4; scv_6=scv_6+B[i*n+j+2]*scv_3; scv_7=scv_7+B[(i+1)*n+j+2]*scv_3; scv_11=scv_11+B[(i+2)*n+j+2]*scv_3; scv_10=scv_10+B[(i+3)*n+j+2]*scv_3; scv_9=scv_9+B[(i+4)*n+j+2]*scv_3; scv_8=scv_8+B[(i+5)*n+j+2]*scv_3; scv_6=scv_6+B[i*n+j+3]*scv_2; scv_7=scv_7+B[(i+1)*n+j+3]*scv_2; scv_11=scv_11+B[(i+2)*n+j+3]*scv_2; scv_10=scv_10+B[(i+3)*n+j+3]*scv_2; scv_9=scv_9+B[(i+4)*n+j+3]*scv_2; scv_8=scv_8+B[(i+5)*n+j+3]*scv_2; } register int cbv_2; cbv_2=n-1; #pragma ivdep #pragma vector always for (; j<=cbv_2; j=j+1) { double scv_5; scv_5=x[j]; scv_6=scv_6+B[i*n+j]*scv_5; scv_7=scv_7+B[(i+1)*n+j]*scv_5; scv_11=scv_11+B[(i+2)*n+j]*scv_5; scv_10=scv_10+B[(i+3)*n+j]*scv_5; scv_9=scv_9+B[(i+4)*n+j]*scv_5; scv_8=scv_8+B[(i+5)*n+j]*scv_5; } scv_6=a*scv_6; scv_7=a*scv_7; scv_11=a*scv_11; scv_10=a*scv_10; scv_9=a*scv_9; scv_8=a*scv_8; w[i]=scv_6; w[(i+1)]=scv_7; w[(i+5)]=scv_8; w[(i+4)]=scv_9; w[(i+3)]=scv_10; w[(i+2)]=scv_11; } for (i=n-((n-1)%6)-1; i<=n-1; i=i+1) { double scv_12; scv_12=w[i]; { register int cbv_3; cbv_3=n-4; #pragma ivdep #pragma vector always for (j=0; j<=cbv_3; j=j+4) { scv_12=scv_12+B[i*n+j]*x[j]; scv_12=scv_12+B[i*n+j+1]*x[(j+1)]; scv_12=scv_12+B[i*n+j+2]*x[(j+2)]; scv_12=scv_12+B[i*n+j+3]*x[(j+3)]; } register int cbv_4; cbv_4=n-1; #pragma ivdep #pragma vector always for (; j<=cbv_4; j=j+1) { scv_12=scv_12+B[i*n+j]*x[j]; } } scv_12=a*scv_12; w[i]=scv_12; } } #else { int i,j,it,jt; for (i=0; i<=n-1; i=i+1) { x[i]=0; w[i]=0; } for (j=0; j<=n-1; j=j+1) { for (i=0; i<=n-1; i=i+1) { B[j][i]=u2[j]*v2[i]+u1[j]*v1[i]+A[j][i]; x[i]=y[j]*B[j][i]+x[i]; } } for (i=0; i<=n-1; i=i+1) { x[i]=b*x[i]+z[i]; } { #pragma omp parallel for private(i,j) for (i=0; i<=n-1; i=i+1) { double scv_1; scv_1=w[i]; for (j=0; j<=n-1; j=j+1) { scv_1=scv_1+B[i][j]*x[j]; } scv_1=a*scv_1; w[i]=scv_1; } } } #endif annot_t_end = rtclock(); annot_t_total += annot_t_end - annot_t_start; } annot_t_total = annot_t_total / REPS; #ifndef TEST printf("%f\n", annot_t_total); #else { int i, j; for (i=0; i<n; i++) { if (i%100==0) printf("\n"); printf("%f ",w[i]); } } #endif return ((int) w[0]); }
5409.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #define EXTRALARGE_DATASET #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "correlation.h" /* Array initialization. */ static void init_array (int m, int n, DATA_TYPE *float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n)) { int i, j; *float_n = 1.2; for (i = 0; i < m; i++) for (j = 0; j < n; j++) data[i][j] = ((DATA_TYPE) i*j) / 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 m, DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m)) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < m; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, symmat[i][j]); if ((i * m + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_correlation(int m, int n, DATA_TYPE float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n), DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m), DATA_TYPE POLYBENCH_1D(mean,M,m), DATA_TYPE POLYBENCH_1D(stddev,M,m)) { int i, j, j1, j2; DATA_TYPE eps = 0.1f; #define sqrt_of_array_cell(x,j) sqrt(x[j]) #pragma scop /* Determine mean of column vectors of input data matrix */ #pragma omp parallel private(i, j, j2) num_threads(4) { #pragma omp for schedule(dynamic, 8) for (j = 0; j < _PB_M; j++) { mean[j] = 0.0; for (i = 0; i < _PB_N; i++) mean[j] += data[i][j]; mean[j] /= float_n; } /* Determine standard deviations of column vectors of data matrix. */ #pragma omp for schedule(dynamic, 8) for (j = 0; j < _PB_M; j++) { stddev[j] = 0.0; for (i = 0; i < _PB_N; i++) stddev[j] += (data[i][j] - mean[j]) * (data[i][j] - mean[j]); stddev[j] /= float_n; stddev[j] = sqrt_of_array_cell(stddev, j); /* The following in an inelegant but usual way to handle near-zero std. dev. values, which below would cause a zero- divide. */ stddev[j] = stddev[j] <= eps ? 1.0 : stddev[j]; } /* Center and reduce the column vectors. */ #pragma omp for schedule(dynamic, 8) for (i = 0; i < _PB_N; i++) for (j = 0; j < _PB_M; j++) { data[i][j] -= mean[j]; data[i][j] /= sqrt(float_n) * stddev[j]; } /* Calculate the m * m correlation matrix. */ #pragma omp for schedule(dynamic, 8) for (j1 = 0; j1 < _PB_M-1; j1++) { symmat[j1][j1] = 1.0; for (j2 = j1+1; j2 < _PB_M; j2++) { symmat[j1][j2] = 0.0; for (i = 0; i < _PB_N; i++) symmat[j1][j2] += (data[i][j1] * data[i][j2]); symmat[j2][j1] = symmat[j1][j2]; } } } #pragma endscop symmat[_PB_M-1][_PB_M-1] = 1.0; } int main(int argc, char** argv) { /* Retrieve problem size. */ int n = N; int m = M; /* Variable declaration/allocation. */ DATA_TYPE float_n; POLYBENCH_2D_ARRAY_DECL(data,DATA_TYPE,M,N,m,n); POLYBENCH_2D_ARRAY_DECL(symmat,DATA_TYPE,M,M,m,m); POLYBENCH_1D_ARRAY_DECL(mean,DATA_TYPE,M,m); POLYBENCH_1D_ARRAY_DECL(stddev,DATA_TYPE,M,m); /* Initialize array(s). */ init_array (m, n, &float_n, POLYBENCH_ARRAY(data)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_correlation (m, n, float_n, POLYBENCH_ARRAY(data), POLYBENCH_ARRAY(symmat), POLYBENCH_ARRAY(mean), POLYBENCH_ARRAY(stddev)); /* 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(m, POLYBENCH_ARRAY(symmat))); /* Be clean. */ POLYBENCH_FREE_ARRAY(data); POLYBENCH_FREE_ARRAY(symmat); POLYBENCH_FREE_ARRAY(mean); POLYBENCH_FREE_ARRAY(stddev); return 0; }
LinkedCellsReferences.h
/** * @file LinkedCells.h * @date 05.04.2020 * @author lunaticcoding */ #pragma once #include "autopas/cells/ReferenceParticleCell.h" #include "autopas/containers/CellBasedParticleContainer.h" #include "autopas/containers/CellBlock3D.h" #include "autopas/containers/CompatibleTraversals.h" #include "autopas/containers/LoadEstimators.h" #include "autopas/containers/cellPairTraversals/BalancedTraversal.h" #include "autopas/containers/linkedCells/ParticleVector.h" #include "autopas/iterators/ParticleIterator.h" #include "autopas/iterators/RegionParticleIterator.h" #include "autopas/options/DataLayoutOption.h" #include "autopas/options/LoadEstimatorOption.h" #include "autopas/particles/OwnershipState.h" #include "autopas/utils/ArrayMath.h" #include "autopas/utils/ParticleCellHelpers.h" #include "autopas/utils/StringUtils.h" #include "autopas/utils/WrapOpenMP.h" #include "autopas/utils/inBox.h" namespace autopas { /** * LinkedCells class. * This class uses a list of neighboring cells to store the particles. * These cells dimensions are at least as large as the given cutoff radius, * therefore short-range interactions only need to be calculated between * particles in neighboring cells. * @tparam ParticleCell type of the ParticleCells that are used to store the particles * @tparam SoAArraysType type of the SoA, needed for verlet lists */ template <class Particle> class LinkedCellsReferences : public CellBasedParticleContainer<ReferenceParticleCell<Particle>> { public: /** * Type of the Particle. */ using ParticleType = Particle; /** * Type of the ParticleCell. */ using ReferenceCell = ReferenceParticleCell<Particle>; /** * Constructor of the LinkedCells class * @param boxMin * @param boxMax * @param cutoff * @param skin * @param cellSizeFactor cell size factor relative to cutoff * @param loadEstimator the load estimation algorithm for balanced traversals. * By default all applicable traversals are allowed. */ LinkedCellsReferences(const std::array<double, 3> boxMin, const std::array<double, 3> boxMax, const double cutoff, const double skin, const double cellSizeFactor = 1.0, LoadEstimatorOption loadEstimator = LoadEstimatorOption::squaredParticlesPerCell) : CellBasedParticleContainer<ReferenceCell>(boxMin, boxMax, cutoff, skin), _cellBlock(this->_cells, boxMin, boxMax, cutoff + skin, cellSizeFactor), _loadEstimator(loadEstimator) {} /** * @copydoc ParticleContainerInterface::getContainerType() */ [[nodiscard]] ContainerOption getContainerType() const override { return ContainerOption::linkedCellsReferences; } /** * @copydoc ParticleContainerInterface::getParticleCellTypeEnum() */ [[nodiscard]] CellType getParticleCellTypeEnum() override { return CellType::ReferenceParticleCell; } /** * @copydoc ParticleContainerInterface::addParticleImpl() */ void addParticleImpl(const ParticleType &p) override { ParticleType pCopy = p; addParticleLock.lock(); _particleList.push_back(pCopy); updateDirtyParticleReferences(); addParticleLock.unlock(); } /** * @copydoc ParticleContainerInterface::addHaloParticleImpl() */ void addHaloParticleImpl(const ParticleType &haloParticle) override { ParticleType pCopy = haloParticle; pCopy.setOwnershipState(OwnershipState::halo); addParticleLock.lock(); _particleList.push_back(pCopy); updateDirtyParticleReferences(); addParticleLock.unlock(); } /** * @copydoc ParticleContainerInterface::updateHaloParticle() */ bool updateHaloParticle(const ParticleType &haloParticle) override { ParticleType pCopy = haloParticle; pCopy.setOwnershipState(OwnershipState::halo); auto cells = _cellBlock.getNearbyHaloCells(pCopy.getR(), this->getSkin()); for (auto cellptr : cells) { bool updated = internal::checkParticleInCellAndUpdateByID(*cellptr, pCopy); if (updated) { return true; } } AutoPasLog(trace, "UpdateHaloParticle was not able to update particle: {}", pCopy.toString()); return false; } /** * @copydoc ParticleContainerInterface::deleteHaloParticles() */ void deleteHaloParticles() override { _particleList.clearHaloParticles(); _cellBlock.clearHaloCells(); } /** * Generates the load estimation function depending on _loadEstimator. * @return load estimator function object. */ BalancedTraversal::EstimatorFunction getLoadEstimatorFunction() { switch (this->_loadEstimator) { case LoadEstimatorOption::squaredParticlesPerCell: { return [&](const std::array<unsigned long, 3> &cellsPerDimension, const std::array<unsigned long, 3> &lowerCorner, const std::array<unsigned long, 3> &upperCorner) { return loadEstimators::squaredParticlesPerCell(this->_cells, cellsPerDimension, lowerCorner, upperCorner); }; } case LoadEstimatorOption::none: [[fallthrough]]; default: { return [&](const std::array<unsigned long, 3> &cellsPerDimension, const std::array<unsigned long, 3> &lowerCorner, const std::array<unsigned long, 3> &upperCorner) { return 1; }; } } } /** * @copydoc ParticleContainerInterface::rebuildNeighborLists() */ void rebuildNeighborLists(TraversalInterface *traversal) override { updateDirtyParticleReferences(); } /** * Updates all the References in the cells that are out of date. */ void updateDirtyParticleReferences() { if (_particleList.isDirty()) { if (_particleList.needsRebuild()) { for (auto &cell : this->_cells) { cell.clear(); } } for (auto it = _particleList.beginDirty(); it < _particleList.endDirty(); it++) { if (it->isDummy()) { continue; } ReferenceCell &cell = _cellBlock.getContainingCell(it->getR()); auto address = &(*it); cell.addParticleReference(address); } _particleList.markAsClean(); } } void iteratePairwise(TraversalInterface *traversal) override { // Check if traversal is allowed for this container and give it the data it needs. auto *traversalInterface = dynamic_cast<LCTraversalInterface<ReferenceCell> *>(traversal); auto *cellPairTraversal = dynamic_cast<CellPairTraversal<ReferenceCell> *>(traversal); if (auto *balancedTraversal = dynamic_cast<BalancedTraversal *>(traversal)) { balancedTraversal->setLoadEstimator(getLoadEstimatorFunction()); } if (traversalInterface && cellPairTraversal) { cellPairTraversal->setCellsToTraverse(this->_cells); } else { autopas::utils::ExceptionHandler::exception( "Trying to use a traversal of wrong type in LinkedCellsReferences::iteratePairwise. TraversalID: {}", traversal->getTraversalType()); } traversal->initTraversal(); traversal->traverseParticlePairs(); traversal->endTraversal(); } std::vector<ParticleType> updateContainer() override { this->deleteHaloParticles(); std::vector<ParticleType> invalidParticles; #ifdef AUTOPAS_OPENMP #pragma omp parallel #endif // AUTOPAS_OPENMP { // private for each thread! std::vector<ParticleType> myInvalidParticles, myInvalidNotOwnedParticles; #ifdef AUTOPAS_OPENMP #pragma omp for #endif // AUTOPAS_OPENMP for (size_t cellId = 0; cellId < this->getCells().size(); ++cellId) { // Delete dummy particles of each cell. this->getCells()[cellId].deleteDummyParticles(); // if empty if (not this->getCells()[cellId].isNotEmpty()) continue; auto [cellLowerCorner, cellUpperCorner] = this->getCellBlock().getCellBoundingBox(cellId); for (auto &&pIter = this->getCells()[cellId].begin(); pIter.isValid(); ++pIter) { // if not in cell if (utils::notInBox(pIter->getR(), cellLowerCorner, cellUpperCorner)) { myInvalidParticles.push_back(*pIter); internal::deleteParticle(pIter); } } } // implicit barrier here // the barrier is needed because iterators are not threadsafe w.r.t. addParticle() // this loop is executed for every thread and thus parallel. Don't use #pragma omp for here! for (auto &&p : myInvalidParticles) { // if not in halo if (utils::inBox(p.getR(), this->getBoxMin(), this->getBoxMax())) { this->template addParticle<false>(p); } else { myInvalidNotOwnedParticles.push_back(p); } } #ifdef AUTOPAS_OPENMP #pragma omp critical #endif { // merge private vectors to global one. invalidParticles.insert(invalidParticles.end(), myInvalidNotOwnedParticles.begin(), myInvalidNotOwnedParticles.end()); } } _particleList.deleteDummyParticles(); updateDirtyParticleReferences(); return invalidParticles; } /** * @copydoc ParticleContainerInterface::getTraversalSelectorInfo() */ [[nodiscard]] TraversalSelectorInfo getTraversalSelectorInfo() const override { return TraversalSelectorInfo(this->getCellBlock().getCellsPerDimensionWithHalo(), this->getInteractionLength(), this->getCellBlock().getCellLength(), 0); } ParticleIteratorWrapper<ParticleType, true> begin( IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override { return ParticleIteratorWrapper<ParticleType, true>( new internal::ParticleIterator<ParticleType, ReferenceCell, true>(&this->_cells, 0, &_cellBlock, behavior)); } ParticleIteratorWrapper<ParticleType, false> begin( IteratorBehavior behavior = IteratorBehavior::haloAndOwned) const override { return ParticleIteratorWrapper<ParticleType, false>( new internal::ParticleIterator<ParticleType, ReferenceCell, false>(&this->_cells, 0, &_cellBlock, behavior)); } ParticleIteratorWrapper<ParticleType, true> getRegionIterator( const std::array<double, 3> &lowerCorner, const std::array<double, 3> &higherCorner, IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override { // We increase the search region by skin, as particles can move over cell borders. auto startIndex3D = this->_cellBlock.get3DIndexOfPosition(utils::ArrayMath::subScalar(lowerCorner, this->getSkin())); auto stopIndex3D = this->_cellBlock.get3DIndexOfPosition(utils::ArrayMath::addScalar(higherCorner, this->getSkin())); size_t numCellsOfInterest = (stopIndex3D[0] - startIndex3D[0] + 1) * (stopIndex3D[1] - startIndex3D[1] + 1) * (stopIndex3D[2] - startIndex3D[2] + 1); std::vector<size_t> cellsOfInterest(numCellsOfInterest); int i = 0; for (size_t z = startIndex3D[2]; z <= stopIndex3D[2]; ++z) { for (size_t y = startIndex3D[1]; y <= stopIndex3D[1]; ++y) { for (size_t x = startIndex3D[0]; x <= stopIndex3D[0]; ++x) { cellsOfInterest[i++] = utils::ThreeDimensionalMapping::threeToOneD({x, y, z}, this->_cellBlock.getCellsPerDimensionWithHalo()); } } } return ParticleIteratorWrapper<ParticleType, true>( new internal::RegionParticleIterator<ParticleType, ReferenceCell, true>( &this->_cells, lowerCorner, higherCorner, cellsOfInterest, &_cellBlock, behavior)); } ParticleIteratorWrapper<ParticleType, false> getRegionIterator( const std::array<double, 3> &lowerCorner, const std::array<double, 3> &higherCorner, IteratorBehavior behavior = IteratorBehavior::haloAndOwned) const override { // We increase the search region by skin, as particles can move over cell borders. auto startIndex3D = this->_cellBlock.get3DIndexOfPosition(utils::ArrayMath::subScalar(lowerCorner, this->getSkin())); auto stopIndex3D = this->_cellBlock.get3DIndexOfPosition(utils::ArrayMath::addScalar(higherCorner, this->getSkin())); size_t numCellsOfInterest = (stopIndex3D[0] - startIndex3D[0] + 1) * (stopIndex3D[1] - startIndex3D[1] + 1) * (stopIndex3D[2] - startIndex3D[2] + 1); std::vector<size_t> cellsOfInterest(numCellsOfInterest); int i = 0; for (size_t z = startIndex3D[2]; z <= stopIndex3D[2]; ++z) { for (size_t y = startIndex3D[1]; y <= stopIndex3D[1]; ++y) { for (size_t x = startIndex3D[0]; x <= stopIndex3D[0]; ++x) { cellsOfInterest[i++] = utils::ThreeDimensionalMapping::threeToOneD({x, y, z}, this->_cellBlock.getCellsPerDimensionWithHalo()); } } } return ParticleIteratorWrapper<ParticleType, false>( new internal::RegionParticleIterator<ParticleType, ReferenceCell, false>( &this->_cells, lowerCorner, higherCorner, cellsOfInterest, &_cellBlock, behavior)); } /** * Get the cell block, not supposed to be used except by verlet lists * @return the cell block */ internal::CellBlock3D<ReferenceCell> &getCellBlock() { return _cellBlock; } /** * @copydoc getCellBlock() * @note const version */ const internal::CellBlock3D<ReferenceCell> &getCellBlock() const { return _cellBlock; } /** * Returns reference to the data of LinkedCellsReferences * @return the data */ std::vector<ReferenceCell> &getCells() { return this->_cells; } /** * @copydoc getCells() * @note const version */ const std::vector<ReferenceCell> &getCells() const { return this->_cells; } protected: /** * object that stores the actual Particles and keeps track of the references. */ ParticleVector<ParticleType> _particleList; /** * object to manage the block of cells. */ internal::CellBlock3D<ReferenceCell> _cellBlock; /** * load estimation algorithm for balanced traversals. */ autopas::LoadEstimatorOption _loadEstimator; /** * Workaround for adding particles in parallel -> https://github.com/AutoPas/AutoPas/issues/555 */ AutoPasLock addParticleLock; }; } // namespace autopas
matmul.c
#include <stdlib.h> #include <sys/time.h> #include <stdio.h> #include <omp.h> #ifndef _N_ #define _N_ 512 #endif //#define PRINT_RESULT int N = _N_; int M = _N_; int P = _N_; double my_timer () { struct timeval time; gettimeofday (&time, 0); return time.tv_sec + time.tv_usec / 1000000.0; } void MatrixMultiplication_openacc(float * a,float * b, float * c) { int i, j, k ; #pragma acc data copyout(a[0:(M*N)]), copyin(b[0:(M*P)],c[0:(P*N)]) { #pragma acc kernels loop independent gang for (i=0; i<M; i++){ #pragma acc loop worker for (j=0; j<N; j++) { float sum = 0.0 ; #pragma acc loop seq for (k=0; k<P; k++) { sum += b[i*P+k]*c[k*N+j] ; } a[i*N+j] = sum ; } } } #ifdef PRINT_RESULT for (i=0; i<4; i++){ printf("a[%d] = %f\n", i, a[i]); } #endif } void MatrixMultiplication_openmp(float * a,float * b, float * c) { int i, j, k ; int chunk = N/4; #pragma omp parallel shared(a,b,c,chunk) private(i,j,k) { #ifdef _OPENMP if(omp_get_thread_num() == 0) { printf("Number of OpenMP threads %d\n", omp_get_num_threads()); } #endif #pragma omp for for (i=0; i<M; i++){ for (j=0; j<N; j++) { float sum = 0.0 ; for (k=0; k<P; k++) sum += b[i*P+k]*c[k*N+j] ; a[i*N+j] = sum ; } } } } int main() { float *a, *b, *c; int i; double elapsed_time; a = (float *) malloc(M*N*sizeof(float)); b = (float *) malloc(M*P*sizeof(float)); c = (float *) malloc(P*N*sizeof(float)); for (i = 0; i < M*N; i++) { a[i] = (float) 0.0; } for (i = 0; i < M*P; i++) { b[i] = (float) i; } for (i = 0; i < P*N; i++) { c[i] = (float) 1.0; } elapsed_time = my_timer(); MatrixMultiplication_openmp(a,b,c); elapsed_time = my_timer() - elapsed_time; printf("CPU Elapsed time = %lf sec\n", elapsed_time); elapsed_time = my_timer(); MatrixMultiplication_openacc(a,b,c); elapsed_time = my_timer() - elapsed_time; printf("Accelerator Elapsed time = %lf sec\n", elapsed_time); free(a); free(b); free(c); return 0; }
GB_unaryop__lnot_fp64_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__lnot_fp64_bool // op(A') function: GB_tran__lnot_fp64_bool // C type: double // A type: bool // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ bool #define GB_CTYPE \ double // 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 != 0) ; // casting #define GB_CASTING(z, aij) \ double z = (double) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP64 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_bool ( double *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__lnot_fp64_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
convolution_pack4to1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_pack4to1_fp16s_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * 4; for (int k = 0; k < maxk; k++) { float32x4_t _val = vcvt_f32_f16(vld1_f16(sptr + space_ofs[k] * 4)); float32x4_t _w = vcvt_f32_f16(vld1_f16(kptr)); float32x4_t _s4 = vmulq_f32(_val, _w); sum += vaddvq_f32(_s4); // dot kptr += 4; } } sum = activation_ss(sum, activation_type, activation_params); outptr[j] = (__fp16)sum; } outptr += outw; } } } static void convolution_pack4to1_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * 4; for (int k = 0; k < maxk; k++) { float16x4_t _val = vld1_f16(sptr + space_ofs[k] * 4); float16x4_t _w = vld1_f16(kptr); float16x4_t _s4 = vmul_f16(_val, _w); sum += vaddvq_f32(vcvt_f32_f16(_s4)); // dot kptr += 4; } } sum = activation_ss(sum, activation_type, activation_params); outptr[j] = sum; } outptr += outw; } } }
string_graph.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <emmintrin.h> #include "string_graph.h" #include "index.h" inline INDEX_TYPE_T OCCx (u64 ** OCC_bitmap, INDEX_TYPE_T * OCC_sample, int nt, INDEX_TYPE_T pos) { INDEX_TYPE_T occ2 = 0; u64 occ_bitmap; int off; occ2 = OCC_sample[nt + pos / 64 * 5]; off = pos % 64; occ_bitmap = OCC_bitmap[nt][pos / 64]; occ_bitmap = occ_bitmap << (63 - off); occ2 += __builtin_popcountll (occ_bitmap); return occ2; } inline INDEX_TYPE_T OCCx_LT (u64 ** OCC_bitmap, INDEX_TYPE_T * OCC_sample, int nt, INDEX_TYPE_T pos) { INDEX_TYPE_T occ2 = 0; u64 occ_bitmap = 0; int off; int k; int pos0; pos0 = pos / 64; off = pos % 64; for (k = 0; k < nt; k++) { occ2 += OCC_sample[k + pos0 * 5]; occ_bitmap |= OCC_bitmap[k][pos0]; } occ_bitmap = occ_bitmap << (63 - off); occ2 += __builtin_popcountll (occ_bitmap); return occ2; } #define OCCfw(a, i) (OCCx(OCC_bitmap, OCC_sample, a, i)) #define OCCbw(a, i) (OCCx(OCC_bitmap_bw, OCC_sample_bw, a, i)) #define OCCfw_LT(a, i) (OCCx_LT(OCC_bitmap, OCC_sample, a, i)) #define OCCbw_LT(a, i) (OCCx_LT(OCC_bitmap_bw, OCC_sample_bw, a, i)) /* forward */ inline void search_1 (INDEX_TYPE_T * C, u64 ** OCC_bitmap, INDEX_TYPE_T * OCC_sample, char ch, INDEX_TYPE_T * l, INDEX_TYPE_T * u) { INDEX_TYPE_T occ2_l = 0; u64 occ_bitmap_l; int off_l; INDEX_TYPE_T occ2_u = 0; u64 occ_bitmap_u; int off_u; INDEX_TYPE_T vl = *l; INDEX_TYPE_T vu = *u + 1; occ2_l = OCC_sample[(int) ch + vl / 64 * 5]; off_l = vl % 64; occ_bitmap_l = OCC_bitmap[(int) ch][vl / 64]; occ_bitmap_l = occ_bitmap_l << (63 - off_l); occ2_l += __builtin_popcountll (occ_bitmap_l); occ2_u = OCC_sample[(int) ch + vu / 64 * 5]; off_u = vu % 64; occ_bitmap_u = OCC_bitmap[(int) ch][vu / 64]; occ_bitmap_u = occ_bitmap_u << (63 - off_u); occ2_u += __builtin_popcountll (occ_bitmap_u); *l = C[(int) ch] + occ2_l; *u = C[(int) ch] + occ2_u - 1; } /* forward and backward search */ inline void search_2 (INDEX_TYPE_T * C, u64 ** OCC_bitmap, INDEX_TYPE_T * OCC_sample, char ch, INDEX_TYPE_T * l, INDEX_TYPE_T * u, INDEX_TYPE_T * ll, INDEX_TYPE_T * uu) { INDEX_TYPE_T occ2_l = 0; u64 occ_bitmap_l; int off_l; INDEX_TYPE_T occ2_u = 0; u64 occ_bitmap_u; int off_u; INDEX_TYPE_T vl = *l; INDEX_TYPE_T vu = *u + 1; INDEX_TYPE_T occ2 = 0; u64 occ_bitmap_lt0 = 0; u64 occ_bitmap_lt1 = 0; int k;; off_l = vl % 64; off_u = vu % 64; for (k = 0; k < (int) ch; k++) { occ2 += OCC_sample[k + vu / 64 * 5]; occ_bitmap_lt0 |= OCC_bitmap[k][vu / 64]; occ2 -= OCC_sample[k + vl / 64 * 5]; occ_bitmap_lt1 |= OCC_bitmap[k][vl / 64]; } occ_bitmap_lt0 = occ_bitmap_lt0 << (63 - off_u); occ2 += __builtin_popcountll (occ_bitmap_lt0); occ_bitmap_lt1 = occ_bitmap_lt1 << (63 - off_l); occ2 -= __builtin_popcountll (occ_bitmap_lt1); *ll = *ll + occ2; occ2_l = OCC_sample[(int) ch + vl / 64 * 5]; occ_bitmap_l = OCC_bitmap[(int) ch][vl / 64]; occ_bitmap_l = occ_bitmap_l << (63 - off_l); occ2_l += __builtin_popcountll (occ_bitmap_l); occ2_u = OCC_sample[(int) ch + vu / 64 * 5]; occ_bitmap_u = OCC_bitmap[(int) ch][vu / 64]; occ_bitmap_u = occ_bitmap_u << (63 - off_u); occ2_u += __builtin_popcountll (occ_bitmap_u); *l = C[(int) ch] + occ2_l; *u = C[(int) ch] + occ2_u - 1; *uu = *ll + occ2_u - occ2_l - 1; } inline INDEX_TYPE_T search_3 (INDEX_TYPE_T * C, u64 ** OCC_bitmap, INDEX_TYPE_T * OCC_sample, INDEX_TYPE_T vl, INDEX_TYPE_T vu) { INDEX_TYPE_T occ2_l = 0; u64 occ_bitmap_l; int off_l; INDEX_TYPE_T occ2_u = 0; u64 occ_bitmap_u; int off_u; vu = vu + 1; occ2_l = OCC_sample[vl / 64 * 5]; off_l = vl % 64; occ_bitmap_l = OCC_bitmap[0][vl / 64]; occ_bitmap_l = occ_bitmap_l << (63 - off_l); occ2_l += __builtin_popcountll (occ_bitmap_l); occ2_u = OCC_sample[vu / 64 * 5]; off_u = vu % 64; occ_bitmap_u = OCC_bitmap[0][vu / 64]; occ_bitmap_u = occ_bitmap_u << (63 - off_u); occ2_u += __builtin_popcountll (occ_bitmap_u); return (occ2_u - occ2_l - 1); } // find overlaps static void find_intervals (INDEX_TYPE_T n, index_t * index, thread_resource_t * ts, int *overlaps_B, int *overlaps_F) { int i; int k; INDEX_TYPE_T l; INDEX_TYPE_T u; INDEX_TYPE_T ll = 0; INDEX_TYPE_T uu = 0; char ch; char *read; int olp_B; int olp_F; int size_fw = 0; int size_bw = 0; interval_t *I_fw = ts->I_fw; interval_t *I_bw = ts->I_bw;; interval_t *I_next = NULL; INDEX_TYPE_T tmp; u64 **OCC_bitmap = index->OCC_bitmap; u64 **OCC_bitmap_bw = index->OCC_bitmap_bw; INDEX_TYPE_T *OCC_sample = index->OCC_sample; INDEX_TYPE_T *OCC_sample_bw = index->OCC_sample_bw; INDEX_TYPE_T *C = index->C; int read_len = (int) (index->read_len); int min_overlap = (int) (index->min_overlap); INDEX_TYPE_T *interval_start = index->interval_start; INDEX_TYPE_T *interval_end = index->interval_end; u16 *interval_depth = index->interval_depth; INDEX_TYPE_T *interval_start_bw = index->interval_start_bw; INDEX_TYPE_T *interval_end_bw = index->interval_end_bw; u16 *interval_depth_bw = index->interval_depth_bw; olp_B = olp_F = 0; char *reads = index->reads; read = reads + n * read_len; // find F-B intervals l = interval_start[n]; u = l + interval_end[n] - 1; i = read_len - interval_depth[n] - 1; size_fw = 0; while (l < u && i > (read_len - min_overlap - 1)) { ch = read[i]; search_1 (C, OCC_bitmap, OCC_sample, ch, &l, &u); i = i - 1; } if (l < u) { ch = read[i + 1]; ll = C[(int) ch]; uu = C[(int) ch + 1] - 1; for (k = i + 2; k < read_len; k++) { ch = read[k]; search_1 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &ll, &uu); } } while (l < u && i >= 0) { tmp = search_3 (C, OCC_bitmap, OCC_sample, l, u); if (tmp >= 0) { I_next = &(I_fw[size_fw++]); assert (size_fw < read_len * 2); I_next->ll = ll; I_next->uu = ll + tmp; I_next->len = read_len - i - 1; I_next->type = FB; I_next->remain_size = tmp + 1; olp_F += tmp + 1; } ch = read[i]; search_2 (C, OCC_bitmap, OCC_sample, ch, &l, &u, &ll, &uu); i = i - 1; } // find F-F intervals ch = ntc_table[(int) (read[read_len - 1])]; l = C[(int) ch]; u = C[(int) ch + 1] - 1; i = read_len - 2; while (l <= u && i > (read_len - min_overlap - 1)) { ch = ntc_table[(int) (read[i])]; search_1 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &l, &u); i = i - 1; } if (l <= u) { ch = ntc_table[(int) read[i + 1]]; ll = C[(int) ch]; uu = C[(int) ch + 1] - 1; for (k = i + 2; k < read_len; k++) { ch = ntc_table[(int) read[k]]; search_1 (C, OCC_bitmap, OCC_sample, ch, &ll, &uu); } } while (l <= u && i >= 0) { tmp = search_3 (C, OCC_bitmap_bw, OCC_sample_bw, l, u); if (tmp >= 0) { I_next = &(I_fw[size_fw++]); assert (size_fw < read_len * 2); I_next->ll = ll; I_next->uu = ll + tmp; I_next->len = read_len - i - 1; I_next->type = FF; I_next->remain_size = tmp + 1; olp_F += tmp + 1; } ch = ntc_table[(int) (read[i])]; search_2 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &l, &u, &ll, &uu); i = i - 1; } // find B-F intervals l = interval_start_bw[n]; u = l + interval_end_bw[n] - 1; i = interval_depth_bw[n]; size_bw = 0; while (l < u && i < min_overlap) { ch = read[i]; search_1 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &l, &u); i = i + 1; } if (l < u) { ch = read[i - 1]; ll = C[(int) ch]; uu = C[(int) ch + 1] - 1; for (k = i - 2; k >= 0; k--) { ch = read[k]; search_1 (C, OCC_bitmap, OCC_sample, ch, &ll, &uu); } } while (l < u && i < read_len) { tmp = search_3 (C, OCC_bitmap_bw, OCC_sample_bw, l, u); if (tmp >= 0) { I_next = &(I_bw[size_bw++]); assert (size_bw < read_len * 2); I_next->ll = ll; I_next->uu = ll + tmp; I_next->len = i; I_next->type = BF; I_next->remain_size = tmp + 1; olp_B += tmp + 1; } ch = read[i]; search_2 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &l, &u, &ll, &uu); i = i + 1; } // find B-B intervals ch = ntc_table[(int) (read[0])]; l = C[(int) ch]; u = C[(int) ch + 1] - 1; i = 1; while (l <= u && i < min_overlap) { ch = ntc_table[(int) read[i]]; search_1 (C, OCC_bitmap, OCC_sample, ch, &l, &u); i = i + 1; } if (l <= u) { ch = ntc_table[(int) read[i - 1]]; ll = C[(int) ch]; uu = C[(int) ch + 1] - 1; for (k = i - 2; k >= 0; k--) { ch = ntc_table[(int) read[k]]; search_1 (C, OCC_bitmap_bw, OCC_sample_bw, ch, &ll, &uu); } } while (l <= u && i < read_len) { if (i >= min_overlap) { tmp = search_3 (C, OCC_bitmap, OCC_sample, l, u); if (tmp >= 0) { I_next = &(I_bw[size_bw++]); assert (size_bw < read_len * 2); I_next->ll = ll; I_next->uu = ll + tmp; I_next->len = i; I_next->type = BB; I_next->remain_size = tmp + 1; olp_B += tmp + 1; } } ch = ntc_table[(int) (read[i])]; search_2 (C, OCC_bitmap, OCC_sample, ch, &l, &u, &ll, &uu); i = i + 1; } ts->size_fw = size_fw; ts->size_bw = size_bw; ts->max_fw = 0; ts->max_fw = 0; *overlaps_B = olp_B; *overlaps_F = olp_F; } // remove forward transitive edges static void extract_fw_edges (string_graph_t * graph, INDEX_TYPE_T n, index_t * index, thread_resource_t * ts) { int i; INDEX_TYPE_T k; INDEX_TYPE_T ll; INDEX_TYPE_T uu; INDEX_TYPE_T lll; INDEX_TYPE_T uuu; int flag; int a; u16 max_len; int b; int size_Ia; interval_t *Ia; INDEX_TYPE_T overlap_read; int overlap_len; char type; int read_len = index->read_len; INDEX_TYPE_T *C = index->C; interval_t *I_F = ts->I_F; interval_t *I; short size_I; u64 **OCC_bitmap = index->OCC_bitmap; u64 **OCC_bitmap_bw = index->OCC_bitmap_bw; INDEX_TYPE_T *OCC_sample = index->OCC_sample; INDEX_TYPE_T *reads_index = index->reads_index; INDEX_TYPE_T *OCC_sample_bw = index->OCC_sample_bw; INDEX_TYPE_T *reads_index_bw = index->reads_index_bw; I = ts->I_fw + ts->pos_fw; size_I = ts->size_fw; flag = 0; overlap_len = read_len; type = FB; if (ts->max_fw + ts->level == read_len) { for (i = 0; i < size_I; i++) { ll = I[i].ll; uu = I[i].uu; overlap_len = I[i].len; type = I[i].type; if (overlap_len + ts->level != read_len) continue; if (type == FF) { lll = C[0] + OCCfw (0, ll); uuu = C[0] + OCCfw (0, uu + 1) - 1; // search_1 (C, OCC_bitmap, OCC_sample, 0, &ll, &uu); } else { lll = C[0] + OCCbw (0, ll); uuu = C[0] + OCCbw (0, uu + 1) - 1; // search_1 (C, OCC_bitmap_bw, OCC_sample_bw, 0, &ll, &uu); } if (lll <= uuu) { for (k = lll; k < uuu + 1; k++) { if (I[i].type == FF) { overlap_read = reads_index[k]; } else { overlap_read = reads_index_bw[k]; } flag = 1; if (overlap_read != n) { I_F[ts->size_I_F].ll = overlap_read; I_F[ts->size_I_F].remain_size = ts->max_trans; I_F[ts->size_I_F].len = overlap_len; I_F[ts->size_I_F].type = type; if (I_F[1].uu < ts->max_trans) { I_F[1].uu = ts->max_trans; } if (ts->size_I_F + 1 > 65535) { ERROR_EXIT ("assembly failed. Try a larger min overlap length.\n"); } ts->size_I_F = ts->size_I_F + 1; if (ts->size_I_F == I_F[0].uu) { I_F[0].uu = I_F[0].uu + read_len; ts->I_F = I_F = (interval_t *) realloc (I_F, sizeof (interval_t) * I_F[0].uu); assert (I_F != NULL); } #if defined(__INDEX_U32__) DPRINTF (5, "read %d add overlap type %d to read %d with len %d\n", n, type, overlap_read, overlap_len); #elif defined(__INDEX_U64__) DPRINTF (5, "read %lld add overlap type %d to read %lld with len %d\n", n, type, overlap_read, overlap_len); #else DPRINTF (5, "read %d add overlap type %d to read %d with len %d\n", n, type, overlap_read, overlap_len); #endif } } break; } } if (flag == 1) { return; } } Ia = I + size_I; ts->pos_fw = ts->pos_fw + size_I; for (a = 1; a < 5; a++) { size_Ia = 0; b = ntc_table[a]; max_len = 0; ts->max_trans = 0; for (i = 0; i < size_I; i++) { if (I[i].remain_size > 0) { ll = I[i].ll; uu = I[i].uu; if (I[i].type == FF) { search_1 (C, OCC_bitmap, OCC_sample, b, &ll, &uu); } else { search_1 (C, OCC_bitmap_bw, OCC_sample_bw, a, &ll, &uu); } I[i].remain_size = I[i].remain_size - (uu - ll + 1); if (ll <= uu) { Ia[size_Ia].ll = ll; Ia[size_Ia].uu = uu; Ia[size_Ia].len = I[i].len; Ia[size_Ia].type = I[i].type; Ia[size_Ia].remain_size = uu - ll + 1; ts->max_trans += uu - ll + 1; if (max_len < I[i].len) max_len = I[i].len; size_Ia++; assert (size_Ia + ts->size_fw + ts->pos_fw < read_len * 2 * read_len * 2); } } } if (size_Ia == 0) continue; ts->size_fw = size_Ia; ts->level++; ts->max_fw = max_len; extract_fw_edges (graph, n, index, ts); ts->level--; } ts->pos_fw = ts->pos_fw - size_I; } // remove backward transitive edges static void extract_bw_edges (string_graph_t * graph, INDEX_TYPE_T n, index_t * index, thread_resource_t * ts) { int i; INDEX_TYPE_T k; INDEX_TYPE_T ll; INDEX_TYPE_T uu; INDEX_TYPE_T lll; INDEX_TYPE_T uuu; int flag; int a; u16 max_len; int b; int size_Ia; interval_t *Ia; INDEX_TYPE_T overlap_read; int overlap_len; char type; int read_len = index->read_len; INDEX_TYPE_T *C = index->C; interval_t *I_B = ts->I_B; interval_t *I = ts->I_bw + ts->pos_bw; short size_I = ts->size_bw; u64 **OCC_bitmap = index->OCC_bitmap; u64 **OCC_bitmap_bw = index->OCC_bitmap_bw; INDEX_TYPE_T *OCC_sample = index->OCC_sample; INDEX_TYPE_T *reads_index = index->reads_index; INDEX_TYPE_T *OCC_sample_bw = index->OCC_sample_bw; INDEX_TYPE_T *reads_index_bw = index->reads_index_bw; I = ts->I_bw + ts->pos_bw; size_I = ts->size_bw; flag = 0; overlap_len = read_len; type = BB; if (ts->max_bw + ts->level == read_len) { for (i = 0; i < size_I; i++) { ll = I[i].ll; uu = I[i].uu; overlap_len = I[i].len; type = I[i].type; if (overlap_len + ts->level != read_len) continue; if (I[i].type == BB) { lll = C[0] + OCCbw (0, ll); uuu = C[0] + OCCbw (0, uu + 1) - 1; // search_1 (C, OCC_bitmap_bw, OCC_sample_bw, 0, &ll, &uu); } else { lll = C[0] + OCCfw (0, ll); uuu = C[0] + OCCfw (0, uu + 1) - 1; // search_1 (C, OCC_bitmap, OCC_sample, 0, &ll, &uu); } if (lll <= uuu) { overlap_len = I[i].len; type = I[i].type; for (k = lll; k < uuu + 1; k++) { if (I[i].type == BB) { overlap_read = reads_index_bw[k]; } else { overlap_read = reads_index[k]; } flag = 1; if (overlap_read != n) { I_B[ts->size_I_B].ll = overlap_read; I_B[ts->size_I_B].remain_size = ts->max_trans; I_B[ts->size_I_B].len = overlap_len; I_B[ts->size_I_B].type = type; if (I_B[1].uu < ts->max_trans) { I_B[1].uu = ts->max_trans; } if (ts->size_I_B + 1 > 65535) { ERROR_EXIT ("assembly failed. Try a larger min overlap length.\n"); } ts->size_I_B = ts->size_I_B + 1; if (ts->size_I_B == I_B[0].uu) { I_B[0].uu = I_B[0].uu + read_len; ts->I_B = I_B = (interval_t *) realloc (I_B, sizeof (interval_t) * I_B[0].uu); assert (I_B != NULL); } #if defined(__INDEX_U32__) DPRINTF (5, "read %d add overlap type %d to read %d with len %d\n", n, type, overlap_read, overlap_len); #elif defined(__INDEX_U64__) DPRINTF (5, "read %lld add overlap type %d to read %lld with len %d\n", n, type, overlap_read, overlap_len); #else DPRINTF (5, "read %d add overlap type %d to read %d with len %d\n", n, type, overlap_read, overlap_len); #endif } } break; } } if (flag == 1) { return; } } Ia = I + size_I; ts->pos_bw = ts->pos_bw + size_I; for (a = 1; a < 5; a++) { size_Ia = 0; b = ntc_table[a]; max_len = 0; ts->max_trans = 0; for (i = 0; i < size_I; i++) { if (I[i].remain_size > 0) { ll = I[i].ll; uu = I[i].uu; if (I[i].type == BB) { search_1 (C, OCC_bitmap_bw, OCC_sample_bw, a, &ll, &uu); } else { search_1 (C, OCC_bitmap, OCC_sample, b, &ll, &uu); } I[i].remain_size = I[i].remain_size - (uu - ll + 1); if (ll <= uu) { Ia[size_Ia].ll = ll; Ia[size_Ia].uu = uu; Ia[size_Ia].len = I[i].len; Ia[size_Ia].type = I[i].type; Ia[size_Ia].remain_size = uu - ll + 1; ts->max_trans += uu - ll + 1; if (max_len < I[i].len) max_len = I[i].len; size_Ia++; assert (size_Ia + ts->size_fw + ts->pos_fw < read_len * 2 * read_len * 2); } } } if (size_Ia == 0) continue; ts->size_bw = size_Ia; ts->level++; ts->max_bw = max_len; extract_bw_edges (graph, n, index, ts); ts->level--; } ts->pos_bw = ts->pos_bw - size_I; } string_graph_t * construct_string_graph (index_t * index) { #ifdef __TIMING__ struct timeval tv1, tv2; double time_pass; gettimeofday (&tv1, NULL); #endif DPRINTF (3, "Building overlap graph ... "); string_graph_t *graph; double overlap_len; INDEX_TYPE_T overlaps; graph = (string_graph_t *) malloc (sizeof (string_graph_t)); assert (graph != NULL); graph->nodes = (node_t *) malloc (index->num_reads * sizeof (node_t)); assert (graph->nodes); memset (graph->nodes, 0, index->num_reads * sizeof (node_t)); graph->num_reads = index->num_reads; graph->read_len = index->read_len; graph->min_overlap = index->min_overlap; overlaps = 0; overlap_len = 0; #ifdef DEBUG1 FILE *fp; FILE *fp1; fp = fopen ("overlaps.dat", "w+"); fp1 = fopen ("len.dat", "w+"); #endif #ifndef DEBUG1 #ifdef __OPENMP__ #pragma omp parallel default(none) shared(index, graph, stderr, overlaps, overlap_len) { #endif #endif thread_resource_t *ts = (thread_resource_t *) malloc (sizeof (thread_resource_t)); assert (ts != NULL); ts->I_fw = (interval_t *) malloc (sizeof (interval_t) * index->read_len * 2 * index->read_len * 2); ts->I_bw = (interval_t *) malloc (sizeof (interval_t) * index->read_len * 2 * index->read_len * 2); ts->I_F = (interval_t *) malloc (sizeof (interval_t) * index->read_len * 2); ts->I_B = (interval_t *) malloc (sizeof (interval_t) * index->read_len * 2); assert (ts->I_B != NULL); assert (ts->I_F != NULL); assert (ts->I_fw != NULL); assert (ts->I_bw != NULL); ts->I_F[0].uu = index->read_len * 2; ts->I_B[0].uu = index->read_len * 2; ts->I_B[1].uu = 0; ts->I_F[1].uu = 0; INDEX_TYPE_T i; #ifndef DEBUG1 #ifdef __OPENMP__ #pragma omp for schedule(dynamic, 1) reduction(+: overlaps) reduction(+: overlap_len) #endif #endif // parallel for each read for (i = 0; i < index->num_reads; i++) { int j; int onum; int olen; node_t *node; edge_t *new_edge; int overlaps_B; int overlaps_F; double ratio; path_q_t *path_q; path_t *path; ts->pos_fw = 0; ts->pos_bw = 0; ts->size_I_F = 0; ts->size_I_B = 0; onum = 0; olen = 0; // find overlapping candidates find_intervals (i, index, ts, &overlaps_B, &overlaps_F); // remove transitive edges ts->level = 0; if (overlaps_B != 0) extract_bw_edges (graph, i, index, ts); ts->level = 0; if (overlaps_F != 0) extract_fw_edges (graph, i, index, ts); // add node and edges node = &(graph->nodes[i]); node->max_B = node->num_B = ts->size_I_B; node->max_F = node->num_F = ts->size_I_F; node->status = DEFAULT; node->path_q = NULL; node->edges = (edge_t *) malloc ((ts->size_I_B + ts->size_I_F) * sizeof (edge_t)); assert (node->edges); olen = 0; onum = 0; // marked for bridge removal ratio = max(overlaps_B, overlaps_F) == 0 ? 0 : ((double)abs(overlaps_B - overlaps_F))/ max(overlaps_B, overlaps_F); if (ratio > 0.6) { node->marked = SUSPECT; } else { node->marked = 0; } // classify the nodes if (node->num_B != 0 || node->num_F != 0) { if (node->num_B == 1) { node->B_type = ONE; } else if (node->num_B > 1) { node->B_type = BRANCH; } else { node->B_type = ENDING; } if (node->num_F == 1) { node->F_type = ONE; } else if (node->num_F > 1) { node->F_type = BRANCH; } else { node->F_type = ENDING; } } else { node->B_type = node->F_type = ENDING; node->status = REMOVED; } #ifdef DEBUG1 fprintf (fp, "read %d: <%d %d> ", i, overlaps_B, overlaps_F); fprintf (fp1, "%d %d %d %lf %lf\n", i, overlaps_B, overlaps_F); #endif // malloc edges and paths if ((node->B_type == BRANCH && node->F_type != ENDING) || (node->F_type == BRANCH && node->B_type != ENDING)) { path_q = node->path_q = (path_q_t *) malloc (sizeof (path_q_t)); assert (path_q != NULL); path_q->max_B_endlen = 0; path_q->max_F_endlen = 0; path_q->max_B_len = 0; path_q->max_F_len = 0; path_q->path = (path_t *) malloc (sizeof (path_t) * (node->max_B + node->max_F)); path_q->max_F_trans = ts->I_F[1].uu; path_q->max_B_trans = ts->I_B[1].uu; assert (path_q->path != NULL); for (j = 0; j < node->max_B; j++) { new_edge = &(node->edges[j]); new_edge->dest = ts->I_B[j].ll; new_edge->overlap_len = ts->I_B[j].len; new_edge->type = ts->I_B[j].type; onum++; olen += new_edge->overlap_len; #ifdef DEBUG1 fprintf (fp, "(%d, ", new_edge->dest); fprintf (fp, "%d, ", new_edge->overlap_len); if (new_edge->type == BF) { fprintf (fp, "BF); "); } else { fprintf (fp, "BB); "); } #endif path = &(path_q->path[j]); path->end = new_edge->dest; path->hop = new_edge->dest; path->len = 1; path->end_len = graph->read_len - new_edge->overlap_len; path->bubble_len = 0; path->type = NONE; path->direction = (new_edge->type == BB ? 1 : 0); path->trans = ts->I_B[j].remain_size; } for (j = 0; j < node->max_F; j++) { new_edge = &(node->edges[j + node->max_B]); new_edge->dest = ts->I_F[j].ll; new_edge->overlap_len = ts->I_F[j].len; new_edge->type = ts->I_F[j].type; onum++; olen += new_edge->overlap_len; #ifdef DEBUG1 fprintf (fp, "(%d, ", new_edge->dest); fprintf (fp, "%d, ", new_edge->overlap_len); if (new_edge->type == FF) { fprintf (fp, "FF); "); } else { fprintf (fp, "FB); "); } #endif path = &(path_q->path[j + node->max_B]); path->end = new_edge->dest; path->hop = new_edge->dest; path->len = 1; path->end_len = graph->read_len - new_edge->overlap_len; path->bubble_len = 0; path->type = NONE; path->direction = (new_edge->type == FB ? 1 : 0); path->trans = ts->I_F[j].remain_size; } } else { for (j = 0; j < node->max_B; j++) { new_edge = &(node->edges[j]); new_edge->dest = ts->I_B[j].ll; new_edge->overlap_len = ts->I_B[j].len; new_edge->type = ts->I_B[j].type; onum++; olen += new_edge->overlap_len; #ifdef DEBUG1 fprintf (fp, "(%d, ", new_edge->dest); fprintf (fp, "%d, ", new_edge->overlap_len); if (new_edge->type == BF) { fprintf (fp, "BF); "); } else { fprintf (fp, "BB); "); } #endif } for (j = 0; j < node->max_F; j++) { new_edge = &(node->edges[j + node->max_B]); new_edge->dest = ts->I_F[j].ll; new_edge->overlap_len = ts->I_F[j].len; new_edge->type = ts->I_F[j].type; onum++; olen += new_edge->overlap_len; #ifdef DEBUG1 fprintf (fp, "(%d, ", new_edge->dest); fprintf (fp, "%d, ", new_edge->overlap_len); if (new_edge->type == FF) { fprintf (fp, "FF); "); } else { fprintf (fp, "FB); "); } #endif } } overlaps += onum; overlap_len += (double) olen; #ifdef DEBUG1 fprintf (fp, "end\n"); #endif } free (ts->I_bw); free (ts->I_fw); free (ts->I_B); free (ts->I_F); free (ts); #ifndef DEBUG1 #ifdef __OPENMP__ } #endif #endif #ifdef __TIMING__ gettimeofday (&tv2, NULL); time_pass = (tv2.tv_sec - tv1.tv_sec) * 1000.0 + (tv2.tv_usec - tv1.tv_usec) / 1000.0; DPRINTF (3, " takes %.3lf ms\n", time_pass); #endif #ifdef DEBUG1 fclose (fp); fclose (fp1); #endif graph->average_overlap = overlap_len / overlaps; DPRINTF (3, " average overlap length: %lf\n", graph->average_overlap); return graph; } void destroy_graph (string_graph_t * graph) { }
kmeans.c
/** @file kmeans.c ** @brief K-means - Declaration ** @author Andrea Vedaldi, David Novotny **/ /* Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. Copyright (C) 2013 Andrea Vedaldi and David Novotny. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ /** <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page kmeans K-means clustering @author Andrea Vedaldi @author David Novotny @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @ref kmeans.h implements a number of algorithm for **K-means quantization**: Lloyd @cite{lloyd82least}, an accelerated version by Elkan @cite{elkan03using}, and a large scale algorithm based on Approximate Nearest Neighbors (ANN). All algorithms support @c float or @c double data and can use the $l^1$ or the $l^2$ distance for clustering. Furthermore, all algorithms can take advantage of multiple CPU cores. Please see @subpage kmeans-fundamentals for a technical description of K-means and of the algorithms implemented here. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-starting Getting started <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The goal of K-means is to partition a dataset into $K$ &ldquo;compact&rdquo; clusters. The following example demonstrates using @ref kmeans.h in the C programming language to partition @c numData @c float vectors into compute @c numCenters clusters using Lloyd's algorithm: @code #include <vl/kmeans.h> double energy ; double * centers ; // Use float data and the L2 distance for clustering KMeans * kmeans = vl_kmeans_new (VLDistanceL2, VL_TYPE_FLOAT) ; // Use Lloyd algorithm vl_kmeans_set_algorithm (kmeans, VlKMeansLloyd) ; // Initialize the cluster centers by randomly sampling the data vl_kmeans_init_centers_with_rand_data (kmeans, data, dimension, numData, numCenters) ; // Run at most 100 iterations of cluster refinement using Lloyd algorithm vl_kmeans_set_max_num_iterations (kmeans, 100) ; vl_kmeans_refine_centers (kmeans, data, numData) ; // Obtain the energy of the solution energy = vl_kmeans_get_energy(kmeans) ; // Obtain the cluster centers centers = vl_kmeans_get_centers(kmeans) ; @endcode Once the centers have been obtained, new data points can be assigned to clusters by using the ::vl_kmeans_quantize function: @code vl_uint32 * assignments = vl_malloc(sizeof(vl_uint32) * numData) ; float * distances = vl_malloc(sizeof(float) * numData) ; vl_kmeans_quantize(kmeans, assignments, distances, data, numData) ; @endcode Alternatively, one can directly assign new pointers to the closest centers, without bothering with a ::VlKMeans object. There are several considerations that may impact the performance of KMeans. First, since K-means is usually based local optimization algorithm, the **initialization method** is important. The following initialization methods are supported: Method | Function | Description ---------------|-----------------------------------------|----------------------------------------------- Random samples | ::vl_kmeans_init_centers_with_rand_data | Random data points K-means++ | ::vl_kmeans_init_centers_plus_plus | Random selection biased towards diversity Custom | ::vl_kmeans_set_centers | Choose centers (useful to run quantization only) See @ref kmeans-init for further details. The initialization methods use a randomized selection of the data points; the random number generator init is controlled by ::vl_rand_init. The second important choice is the **optimization algorithm**. The following optimization algorithms are supported: Algorithm | Symbol | See | Description ------------|------------------|-------------------|----------------------------------------------- Lloyd | ::VlKMeansLloyd | @ref kmeans-lloyd | Alternate EM-style optimization Elkan | ::VlKMeansElkan | @ref kmeans-elkan | A speedup using triangular inequalities ANN | ::VlKMeansANN | @ref kmeans-ann | A speedup using approximated nearest neighbors See the relative sections for further details. These algorithm are iterative, and stop when either a **maximum number of iterations** (::vl_kmeans_set_max_num_iterations) is reached, or when the energy changes sufficiently slowly in one iteration (::vl_kmeans_set_min_energy_variation). All the three algorithms support multithreaded computations. The number of threads used is usually controlled globally by ::vl_set_num_threads. **/ /** <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page kmeans-fundamentals K-means fundamentals @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Given $n$ points $\bx_1,\dots,\bx_n \in \real^d$, the goal of K-means is find $K$ `centers` $\bc_1,\dots,\bc_m \in \real^d$ and `assignments` $q_1,\dots,q_n \in \{1,\dots,K\}$ of the points to the centers such that the sum of distances \[ E(\bc_1,\dots,\bc_k,q_1,\dots,q_n) = \sum_{i=1}^n \|\bx_i - \bc_{q_i} \|_p^p \] is minimized. $K$-means is obtained for the case $p=2$ ($l^2$ norm), because in this case the optimal centers are the means of the input vectors assigned to them. Here the generalization $p=1$ ($l^1$ norm) will also be considered. Up to normalization, the K-means objective $E$ is also the average reconstruction error if the original points are approximated with the cluster centers. Thus K-means is used not only to group the input points into cluster, but also to `quantize` their values. K-means is widely used in computer vision, for example in the construction of vocabularies of visual features (visual words). In these applications the number $n$ of points to cluster and/or the number $K$ of clusters is often large. Unfortunately, minimizing the objective $E$ is in general a difficult combinatorial problem, so locally optimal or approximated solutions are sought instead. The basic K-means algorithm alternate between re-estimating the centers and the assignments (@ref kmeans-lloyd). Combined with a good initialization strategy (@ref kmeans-init) and, potentially, by re-running the optimization from a number of randomized starting states, this algorithm may attain satisfactory solutions in practice. However, despite its simplicity, Lloyd's algorithm is often too slow. A good replacement is Elkan's algorithm (@ref kmeans-elkan), which uses the triangular inequality to cut down significantly the cost of Lloyd's algorithm. Since this algorithm is otherwise equivalent, it should often be preferred. For very large problems (millions of point to clusters and hundreds, thousands, or more clusters to find), even Elkan's algorithm is not sufficiently fast. In these cases, one can resort to a variant of Lloyd's algorithm that uses an approximated nearest neighbors routine (@ref kmeans-ann). <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-init Initialization methods <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> All the $K$-means algorithms considered here find locally optimal solutions; as such the way they are initialized is important. @ref kmeans.h supports the following initialization algorithms: @par Random data samples The simplest initialization method is to sample $K$ points at random from the input data and use them as initial values for the cluster centers. @par K-means++ @cite{arthur07k-means} proposes a randomized initialization of the centers which improves upon random selection. The first center $\bc_1$ is selected at random from the data points $\bx_1, \dots, \bx_n $ and the distance from this center to all points $\|\bx_i - \bc_1\|_p^p$ is computed. Then the second center $\bc_2$ is selected at random from the data points with probability proportional to the distance. The procedure is repeated to obtain the other centers by using the minimum distance to the centers collected so far. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-lloyd Lloyd's algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The most common K-means method is Lloyd's algorithm @cite{lloyd82least}. This algorithm is based on the observation that, while jointly optimizing clusters and assignment is difficult, optimizing one given the other is easy. Lloyd's algorithm alternates the steps: 1. **Quantization.** Each point $\bx_i$ is reassigned to the center $\bc_{q_j}$ closer to it. This requires finding for each point the closest among $K$ other points, which is potentially slow. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize its average distances to the points assigned to it. It is easy to show that the best center is the mean or median of the points, respectively if the $l^2$ or $l^1$ norm is considered. A naive implementation of the assignment step requires $O(dnK)$ operations, where $d$ is the dimensionality of the data, $n$ the number of data points, and $K$ the number of centers. Updating the centers is much cheaper: $O(dn)$ operations suffice to compute the $K$ means and a slightly higher cost is required for the medians. Clearly, the bottleneck is the assignment computation, and this is what the other K-means algorithm try to improve. During the iterations, it can happen that a cluster becomes empty. In this case, K-means automatically **&ldquo;restarts&rdquo; the cluster** center by selecting a training point at random. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-elkan Elkan's algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Elkan's algorithm @cite{elkan03using} is a variation of Lloyd alternate optimization algorithm (@ref kmeans-lloyd) that uses the triangular inequality to avoid many distance calculations when assigning points to clusters. While much faster than Lloyd, Elkan's method uses storage proportional to the umber of clusters by data points, which makes it unpractical for a very large number of clusters. The idea of this algorithm is that, if a center update does not move them much, then most of the point-to-center computations can be avoided when the point-to-center assignments are recomputed. To detect which distances need evaluation, the triangular inequality is used to lower and upper bound distances after a center update. Elkan algorithms uses two key observations. First, one has \[ \|\bx_i - \bc_{q_i}\|_p \leq \|\bc - \bc_{q_i}\|_p / 2 \quad\Rightarrow\quad \|\bx_i - \bc_{q_i}\|_p \leq \|\bx_i - \bc\|_p. \] Thus if the distance between $\bx_i$ and its current center $\bc_{q_i}$ is less than half the distance of the center $\bc_{q_i}$ to another center $\bc$, then $\bc$ can be skipped when the new assignment for $\bx_i$ is searched. Checking this requires keeping track of all the inter-center distances, but centers are typically a small fraction of the training data, so overall this can be a significant saving. In particular, if this condition is satisfied for all the centers $\bc \not= \bc_{q_i}$, the point $\bx_i$ can be skipped completely. Furthermore, the condition can be tested also based on an upper bound $UB_i$ of $\|\bx_i - \bc_{q_i}\|_p$. Second, if a center $\bc$ is updated to $\hat{\bc}$, then the new distance from $\bx$ to $\hat{\bc}$ is bounded from below and above by \[ \|\bx - \bc\|_p - \|bc - \hat\bc\|_p \leq \|\bx - \hat{\bc}\|_p \leq \|\bx - \hat{\bc}\|_p + \|\bc + \hat{\bc}\|_p. \] This allows to maintain an upper bound on the distance of $\bx_i$ to its current center $\bc_{q_i}$ and a lower bound to any other center $\bc$: @f{align*} UB_i & \leftarrow UB_i + \|\bc_{q_i} - \hat{\bc}_{q_i} \|_p \\ LB_i(\bc) & \leftarrow LB_i(\bc) - \|\bc -\hat \bc\|_p. @f} Thus the K-means algorithm becomes: 1. **Initialization.** Compute $LB_i(\bc) = \|\bx_i -\hat \bc\|_p$ for all points and centers. Find the current assignments $q_i$ and bounds $UB_i$ by finding the closest centers to each point: $UB_i = \min_{\bc} LB_i(\bc)$. 2. **Center estimation.** 1. Recompute all the centers based on the new means; call the updated version $\hat{\bc}$. 2. Update all the bounds based on the distance $\|\bc - \hat\bc\|_p$ as explained above. 3. Set $\bc \leftarrow \hat\bc$ for all the centers and go to the next iteration. 3. **Quantization.** 1. Skip any point $\bx_i$ such that $UB_i \leq \frac{1}{2} \|\bc_{q_i} - \bc\|_p$ for all centers $\bc \not= \bc_{q_i}$. 2. For each remaining point $\bx_i$ and center $\bc \not= \bc_{q_i}$: 1. Skip $\bc$ if \[ UB_i \leq \frac{1}{2} \| \bc_{q_i} - \bc \| \quad\text{or}\quad UB_i \leq LB_i(\bc). \] The first condition reflects the first observation above; the second uses the bounds to decide if $\bc$ can be closer than the current center $\bc_{q_i}$ to the point $\bx_i$. If the center cannot be skipped, continue as follows. 3. Skip $\bc$ if the condition above is satisfied after making the upper bound tight: \[ UB_i = LB_i(\bc_{q_i}) = \| \bx_i - \bc_{q_i} \|_p. \] Note that the latter calculation can be done only once for $\bx_i$. If the center cannot be skipped still, continue as follows. 4. Tighten the lower bound too: \[ LB_i(\bc) = \| \bx_i - \bc \|_p. \] At this point both $UB_i$ and $LB_i(\bc)$ are tight. If $LB_i < UB_i$, then the point $\bx_i$ should be reassigned to $\bc$. Update $q_i$ to the index of center $\bc$ and reset $UB_i = LB_i(\bc)$. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-ann ANN algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The *Approximate Nearest Neighbor* (ANN) K-means algorithm @cite{beis97shape} @cite{silpa-anan08optimised} @cite{muja09fast} is a variant of Lloyd's algorithm (@ref kmeans-lloyd) uses a best-bin-first randomized KD-tree algorithm to approximately (and quickly) find the closest cluster center to each point. The KD-tree implementation is based on @ref kdtree. The algorithm can be summarized as follows: 1. **Quantization.** Each point $\bx_i$ is reassigned to the center $\bc_{q_j}$ closer to it. This starts by indexing the $K$ centers by a KD-tree and then using the latter to quickly find the closest center for every training point. The search is approximated to further improve speed. This opens up the possibility that a data point may receive an assignment that is *worse* than the current one. This is avoided by checking that the new assignment estimated by using ANN is an improvement; otherwise the old assignment is kept. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize its average distances to the points assigned to it. It is easy to show that the best center is the mean or median of the points, respectively if the $l^2$ or $l^1$ norm is considered. The key is to trade-off carefully the speedup obtained by using the ANN algorithm and the loss in accuracy when retrieving neighbors. Due to the curse of dimensionality, KD-trees become less effective for higher dimensional data, so that the search cost, which in the best case is logarithmic with this data structure, may become effectively linear. This is somehow mitigated by the fact that new a new KD-tree is computed at each iteration, reducing the likelihood that points may get stuck with sub-optimal assignments. Experiments with the quantization of 128-dimensional SIFT features show that the ANN algorithm may use one quarter of the comparisons of Elkan's while retaining a similar solution accuracy. */ #include "kmeans.h" #include "generic.h" #include "mathop.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /* ================================================================ */ #ifndef VL_KMEANS_INSTANTIATING /** ------------------------------------------------------------------ ** @brief Reset state ** ** The function reset the state of the KMeans object. It deletes ** any stored centers, releasing the corresponding memory. This ** cancels the effect of seeding or setting the centers, but ** does not change the other configuration parameters. **/ void vl_kmeans_reset (VlKMeans * self) { self->numCenters = 0 ; self->dimension = 0 ; if (self->centers) vl_free(self->centers) ; if (self->centerDistances) vl_free(self->centerDistances) ; self->centers = NULL ; self->centerDistances = NULL ; } /** ------------------------------------------------------------------ ** @brief Create a new KMeans object ** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE) ** @param distance distance. ** @return new KMeans object instance. **/ VlKMeans * vl_kmeans_new (vl_type dataType, VlVectorComparisonType distance) { VlKMeans * self = vl_calloc(1, sizeof(VlKMeans)) ; self->algorithm = VlKMeansLloyd ; self->distance = distance ; self->dataType = dataType ; self->verbosity = 0 ; self->maxNumIterations = 100 ; self->minEnergyVariation = 1e-4 ; self->numRepetitions = 1 ; self->centers = NULL ; self->centerDistances = NULL ; self->numTrees = 3; self->maxNumComparisons = 100; vl_kmeans_reset (self) ; return self ; } /** ------------------------------------------------------------------ ** @brief Create a new KMeans object by copy ** @param kmeans KMeans object to copy. ** @return new copy. **/ VlKMeans * vl_kmeans_new_copy (VlKMeans const * kmeans) { VlKMeans * self = vl_malloc(sizeof(VlKMeans)) ; self->algorithm = kmeans->algorithm ; self->distance = kmeans->distance ; self->dataType = kmeans->dataType ; self->verbosity = kmeans->verbosity ; self->maxNumIterations = kmeans->maxNumIterations ; self->numRepetitions = kmeans->numRepetitions ; self->dimension = kmeans->dimension ; self->numCenters = kmeans->numCenters ; self->centers = NULL ; self->centerDistances = NULL ; self->numTrees = kmeans->numTrees; self->maxNumComparisons = kmeans->maxNumComparisons; if (kmeans->centers) { vl_size dataSize = vl_get_type_size(self->dataType) * self->dimension * self->numCenters ; self->centers = vl_malloc(dataSize) ; memcpy (self->centers, kmeans->centers, dataSize) ; } if (kmeans->centerDistances) { vl_size dataSize = vl_get_type_size(self->dataType) * self->numCenters * self->numCenters ; self->centerDistances = vl_malloc(dataSize) ; memcpy (self->centerDistances, kmeans->centerDistances, dataSize) ; } return self ; } /** ------------------------------------------------------------------ ** @brief Deletes a KMeans object ** @param self KMeans object instance. ** ** The function deletes the KMeans object instance created ** by ::vl_kmeans_new. **/ void vl_kmeans_delete (VlKMeans * self) { vl_kmeans_reset (self) ; vl_free (self) ; } /* an helper structure */ typedef struct _VlKMeansSortWrapper { vl_uint32 * permutation ; void const * data ; vl_size stride ; } VlKMeansSortWrapper ; /* ---------------------------------------------------------------- */ /* Instantiate shuffle algorithm */ #define VL_SHUFFLE_type vl_uindex #define VL_SHUFFLE_prefix _vl_kmeans #include "shuffle-def.h" /* #ifdef VL_KMEANS_INSTANTITATING */ #endif /* ================================================================ */ #ifdef VL_KMEANS_INSTANTIATING /* ---------------------------------------------------------------- */ /* Set centers */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_set_centers_, SFX) (VlKMeans * self, TYPE const * centers, vl_size dimension, vl_size numCenters) { self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; memcpy ((TYPE*)self->centers, centers, sizeof(TYPE) * dimension * numCenters) ; } /* ---------------------------------------------------------------- */ /* Random seeding */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_init_centers_with_rand_data_, SFX) (VlKMeans * self, TYPE const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex i, j, k ; VlRand * rand = vl_get_rand () ; self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; { vl_uindex * perm = vl_malloc (sizeof(vl_uindex) * numData) ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif TYPE * distances = vl_malloc (sizeof(TYPE) * numCenters) ; /* get a random permutation of the data point */ for (i = 0 ; i < numData ; ++i) perm[i] = i ; _vl_kmeans_shuffle (perm, numData, rand) ; for (k = 0, i = 0 ; k < numCenters ; ++ i) { /* compare the next data point to all centers collected so far to detect duplicates (if there are enough left) */ if (numCenters - k < numData - i) { vl_bool duplicateDetected = VL_FALSE ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distances, dimension, data + dimension * perm[i], 1, (TYPE*)self->centers, k, distFn) ; for (j = 0 ; j < k ; ++j) { duplicateDetected |= (distances[j] == 0) ; } if (duplicateDetected) continue ; } /* ok, it is not a duplicate so we can accept it! */ memcpy ((TYPE*)self->centers + dimension * k, data + dimension * perm[i], sizeof(TYPE) * dimension) ; k ++ ; } vl_free(distances) ; vl_free(perm) ; } } /* ---------------------------------------------------------------- */ /* kmeans++ seeding */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_init_centers_plus_plus_, SFX) (VlKMeans * self, TYPE const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex x, c ; VlRand * rand = vl_get_rand () ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; TYPE * minDistances = vl_malloc (sizeof(TYPE) * numData) ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; for (x = 0 ; x < numData ; ++x) { minDistances[x] = (TYPE) VL_INFINITY_D ; } /* select the first point at random */ x = vl_rand_uindex (rand, numData) ; c = 0 ; while (1) { TYPE energy = 0 ; TYPE acc = 0 ; TYPE thresh = (TYPE) vl_rand_real1 (rand) ; memcpy ((TYPE*)self->centers + c * dimension, data + x * dimension, sizeof(TYPE) * dimension) ; c ++ ; if (c == numCenters) break ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX) (distances, dimension, (TYPE*)self->centers + (c - 1) * dimension, 1, data, numData, distFn) ; for (x = 0 ; x < numData ; ++x) { minDistances[x] = VL_MIN(minDistances[x], distances[x]) ; energy += minDistances[x] ; } for (x = 0 ; x < numData - 1 ; ++x) { acc += minDistances[x] ; if (acc >= thresh * energy) break ; } } vl_free(distances) ; vl_free(minDistances) ; } /* ---------------------------------------------------------------- */ /* Quantization */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_quantize_, SFX) (VlKMeans * self, vl_uint32 * assignments, TYPE * distances, TYPE const * data, vl_size numData) { vl_index i ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif #ifdef _OPENMP #pragma omp parallel default(none) \ shared(self, distances, assignments, numData, distFn, data) \ num_threads(vl_get_max_threads()) #endif { /* vl_malloc cannot be used here if mapped to MATLAB malloc */ TYPE * distanceToCenters = malloc(sizeof(TYPE) * self->numCenters) ; #ifdef _OPENMP #pragma omp for #endif for (i = 0 ; i < (signed)numData ; ++i) { vl_uindex k ; TYPE bestDistance = (TYPE) VL_INFINITY_D ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distanceToCenters, self->dimension, data + self->dimension * i, 1, (TYPE*)self->centers, self->numCenters, distFn) ; for (k = 0 ; k < self->numCenters ; ++k) { if (distanceToCenters[k] < bestDistance) { bestDistance = distanceToCenters[k] ; assignments[i] = (vl_uint32)k ; } } if (distances) distances[i] = bestDistance ; } free(distanceToCenters) ; } } /* ---------------------------------------------------------------- */ /* ANN quantization */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_quantize_ann_, SFX) (VlKMeans * self, vl_uint32 * assignments, TYPE * distances, TYPE const * data, vl_size numData, vl_bool update) { #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif VlKDForest * forest = vl_kdforest_new(self->dataType,self->dimension,self->numTrees, self->distance) ; vl_kdforest_set_max_num_comparisons(forest,self->maxNumComparisons); vl_kdforest_set_thresholding_method(forest,VL_KDTREE_MEDIAN); vl_kdforest_build(forest,self->numCenters,self->centers); #ifdef _OPENMP #pragma omp parallel default(none) \ num_threads(vl_get_max_threads()) \ shared(self, forest, update, assignments, distances, data, numData, distFn) #endif { VlKDForestNeighbor neighbor ; VlKDForestSearcher * searcher ; vl_index x; #ifdef _OPENMP #pragma omp critical #endif searcher = vl_kdforest_new_searcher (forest) ; #ifdef _OPENMP #pragma omp for #endif for(x = 0 ; x < (signed)numData ; ++x) { vl_kdforestsearcher_query (searcher, &neighbor, 1, (TYPE const *) (data + x*self->dimension)); if (distances) { if(!update) { distances[x] = (TYPE) neighbor.distance; assignments[x] = (vl_uint32) neighbor.index ; } else { TYPE prevDist = (TYPE) distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension *assignments[x]); if (prevDist > (TYPE) neighbor.distance) { distances[x] = (TYPE) neighbor.distance ; assignments[x] = (vl_uint32) neighbor.index ; } else { distances[x] = prevDist ; } } } else { assignments[x] = (vl_uint32) neighbor.index ; } } /* end for */ } /* end of parallel region */ vl_kdforest_delete(forest); } /* ---------------------------------------------------------------- */ /* Helper functions */ /* ---------------------------------------------------------------- */ /* The sorting routine is used to find increasing permutation of each * data dimension. This is used to quickly find the median for l1 * distance clustering. */ VL_INLINE TYPE VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp) (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB) { return ((TYPE*)array->data) [array->permutation[indexA] * array->stride] - ((TYPE*)array->data) [array->permutation[indexB] * array->stride] ; } VL_INLINE void VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap) (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB) { vl_uint32 tmp = array->permutation[indexA] ; array->permutation[indexA] = array->permutation[indexB] ; array->permutation[indexB] = tmp ; } #define VL_QSORT_prefix VL_XCAT3(_vl_kmeans_, SFX, _qsort) #define VL_QSORT_array VlKMeansSortWrapper* #define VL_QSORT_cmp VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp) #define VL_QSORT_swap VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap) #include "qsort-def.h" static void VL_XCAT(_vl_kmeans_sort_data_helper_, SFX) (VlKMeans * self, vl_uint32 * permutations, TYPE const * data, vl_size numData) { vl_uindex d, x ; for (d = 0 ; d < self->dimension ; ++d) { VlKMeansSortWrapper array ; array.permutation = permutations + d * numData ; array.data = data + d ; array.stride = self->dimension ; for (x = 0 ; x < numData ; ++x) { array.permutation[x] = (vl_uint32)x ; } VL_XCAT3(_vl_kmeans_, SFX, _qsort_sort)(&array, numData) ; } } /* ---------------------------------------------------------------- */ /* Lloyd refinement */ /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size c, d, x, iteration ; double previousEnergy = VL_INFINITY_D ; double initialEnergy = VL_INFINITY_D ; double energy ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; VlRand * rand = vl_get_rand () ; vl_size totNumRestartedCenters = 0 ; vl_size numRestartedCenters = 0 ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } for (energy = VL_INFINITY_D, iteration = 0; 1 ; ++ iteration) { /* assign data to cluters */ VL_XCAT(_vl_kmeans_quantize_, SFX)(self, assignments, distances, data, numData) ; /* compute energy */ energy = 0 ; for (x = 0 ; x < numData ; ++x) energy += distances[x] ; if (self->verbosity) { VL_PRINTF("kmeans: Lloyd iter %d: energy = %g\n", iteration, energy) ; } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: Lloyd terminating because maximum number of iterations reached\n") ; } break ; } if (energy == previousEnergy) { if (self->verbosity) { VL_PRINTF("kmeans: Lloyd terminating because the algorithm fully converged\n") ; } break ; } if (iteration == 0) { initialEnergy = energy ; } else { double eps = (previousEnergy - energy) / (initialEnergy - energy) ; if (eps < self->minEnergyVariation) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ; } break ; } } /* begin next iteration */ previousEnergy = energy ; /* update clusters */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < numData ; ++x) { clusterMasses[assignments[x]] ++ ; } numRestartedCenters = 0 ; switch (self->distance) { case VlDistanceL2: memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < numData ; ++x) { TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { ((TYPE*)self->centers) [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } } break ; default: abort(); } /* done compute centers */ totNumRestartedCenters += numRestartedCenters ; if (self->verbosity && numRestartedCenters) { VL_PRINTF("kmeans: Lloyd iter %d: restarted %d centers\n", iteration, numRestartedCenters) ; } } /* next Lloyd iteration */ if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; return energy ; } static double VL_XCAT(_vl_kmeans_update_center_distances_, SFX) (VlKMeans * self) { #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif if (! self->centerDistances) { self->centerDistances = vl_malloc (sizeof(TYPE) * self->numCenters * self->numCenters) ; } VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(self->centerDistances, self->dimension, self->centers, self->numCenters, NULL, 0, distFn) ; return self->numCenters * (self->numCenters - 1) / 2 ; } static double VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size c, d, x, iteration ; double initialEnergy = VL_INFINITY_D ; double previousEnergy = VL_INFINITY_D ; double energy ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; VlRand * rand = vl_get_rand () ; vl_size totNumRestartedCenters = 0 ; vl_size numRestartedCenters = 0 ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } for (energy = VL_INFINITY_D, iteration = 0; 1 ; ++ iteration) { /* assign data to cluters */ VL_XCAT(_vl_kmeans_quantize_ann_, SFX)(self, assignments, distances, data, numData, iteration > 0) ; /* compute energy */ energy = 0 ; for (x = 0 ; x < numData ; ++x) energy += distances[x] ; if (self->verbosity) { VL_PRINTF("kmeans: ANN iter %d: energy = %g\n", iteration, energy) ; } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the maximum number of iterations has been reached\n") ; } break ; } if (energy == previousEnergy) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the algorithm fully converged\n") ; } break ; } if (iteration == 0) { initialEnergy = energy ; } else { double eps = (previousEnergy - energy) / (initialEnergy - energy) ; if (eps < self->minEnergyVariation) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ; } break ; } } /* begin next iteration */ previousEnergy = energy ; /* update clusters */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < numData ; ++x) { clusterMasses[assignments[x]] ++ ; } numRestartedCenters = 0 ; switch (self->distance) { case VlDistanceL2: memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < numData ; ++x) { TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { ((TYPE*)self->centers) [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } } break ; default: VL_PRINT("bad distance set: %d\n",self->distance); abort(); } /* done compute centers */ totNumRestartedCenters += numRestartedCenters ; if (self->verbosity && numRestartedCenters) { VL_PRINTF("kmeans: ANN iter %d: restarted %d centers\n", iteration, numRestartedCenters) ; } } if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; return energy ; } /* ---------------------------------------------------------------- */ /* Elkan refinement */ /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size d, iteration ; vl_index x ; vl_uint32 c, j ; vl_bool allDone ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; VlRand * rand = vl_get_rand () ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif TYPE * nextCenterDistances = vl_malloc (sizeof(TYPE) * self->numCenters) ; TYPE * pointToClosestCenterUB = vl_malloc (sizeof(TYPE) * numData) ; vl_bool * pointToClosestCenterUBIsStrict = vl_malloc (sizeof(vl_bool) * numData) ; TYPE * pointToCenterLB = vl_malloc (sizeof(TYPE) * numData * self->numCenters) ; TYPE * newCenters = vl_malloc(sizeof(TYPE) * self->dimension * self->numCenters) ; TYPE * centerToNewCenterDistances = vl_malloc (sizeof(TYPE) * self->numCenters) ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; double energy ; vl_size totDistanceComputationsToInit = 0 ; vl_size totDistanceComputationsToRefreshUB = 0 ; vl_size totDistanceComputationsToRefreshLB = 0 ; vl_size totDistanceComputationsToRefreshCenterDistances = 0 ; vl_size totDistanceComputationsToNewCenters = 0 ; vl_size totDistanceComputationsToFinalize = 0 ; vl_size totNumRestartedCenters = 0 ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Initialization */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* An iteration is: get_new_centers + reassign + get_energy. This counts as iteration 0, where get_new_centers is assumed to be performed before calling the train function by the initialization function */ /* update distances between centers */ totDistanceComputationsToInit += VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ; /* assigmen points to the initial centers and initialize bounds */ memset(pointToCenterLB, 0, sizeof(TYPE) * self->numCenters * numData) ; for (x = 0 ; x < (signed)numData ; ++x) { TYPE distance ; /* do the first center */ assignments[x] = 0 ; distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + 0) ; pointToClosestCenterUB[x] = distance ; pointToClosestCenterUBIsStrict[x] = VL_TRUE ; pointToCenterLB[0 + x * self->numCenters] = distance ; totDistanceComputationsToInit += 1 ; /* do other centers */ for (c = 1 ; c < self->numCenters ; ++c) { /* Can skip if the center assigned so far is twice as close as its distance to the center under consideration */ if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + assignments[x] * self->numCenters]) { continue ; } distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + c * self->dimension) ; pointToCenterLB[c + x * self->numCenters] = distance ; totDistanceComputationsToInit += 1 ; if (distance < pointToClosestCenterUB[x]) { pointToClosestCenterUB[x] = distance ; assignments[x] = c ; } } } /* compute UB on energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++x) { energy += pointToClosestCenterUB[x] ; } if (self->verbosity) { VL_PRINTF("kmeans: Elkan iter 0: energy = %g, dist. calc. = %d\n", energy, totDistanceComputationsToInit) ; } /* #define SANITY*/ #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies after initial assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f\n", cc, xx, a, b) ; } } } #endif /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Iterations */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ for (iteration = 1 ; 1; ++iteration) { vl_size numDistanceComputationsToRefreshUB = 0 ; vl_size numDistanceComputationsToRefreshLB = 0 ; vl_size numDistanceComputationsToRefreshCenterDistances = 0 ; vl_size numDistanceComputationsToNewCenters = 0 ; vl_size numRestartedCenters = 0 ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Compute new centers */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < (signed)numData ; ++x) { clusterMasses[assignments[x]] ++ ; } switch (self->distance) { case VlDistanceL2: memset(newCenters, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < (signed)numData ; ++x) { TYPE * cpt = newCenters + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = newCenters + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { /* restart the center */ vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < (signed)numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { newCenters [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = newCenters + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; default: abort(); } /* done compute centers */ /* compute the distance from the old centers to the new centers */ for (c = 0 ; c < self->numCenters ; ++c) { TYPE distance = distFn(self->dimension, newCenters + c * self->dimension, (TYPE*)self->centers + c * self->dimension) ; centerToNewCenterDistances[c] = distance ; numDistanceComputationsToNewCenters += 1 ; } /* make the new centers current */ { TYPE * tmp = self->centers ; self->centers = newCenters ; newCenters = tmp ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Reassign points to a centers */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Update distances between centers. */ numDistanceComputationsToRefreshCenterDistances += VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ; for (c = 0 ; c < self->numCenters ; ++c) { nextCenterDistances[c] = (TYPE) VL_INFINITY_D ; for (j = 0 ; j < self->numCenters ; ++j) { if (j == c) continue ; nextCenterDistances[c] = VL_MIN(nextCenterDistances[c], ((TYPE*)self->centerDistances) [j + c * self->numCenters]) ; } } /* Update upper bounds on point-to-closest-center distances based on the center variation. */ for (x = 0 ; x < (signed)numData ; ++x) { TYPE a = pointToClosestCenterUB[x] ; TYPE b = centerToNewCenterDistances[assignments[x]] ; if (self->distance == VlDistanceL1) { pointToClosestCenterUB[x] = a + b ; } else { #if (FLT == VL_TYPE_FLOAT) TYPE sqrtab = sqrtf (a * b) ; #else TYPE sqrtab = sqrt (a * b) ; #endif pointToClosestCenterUB[x] = a + b + 2.0 * sqrtab ; } pointToClosestCenterUBIsStrict[x] = VL_FALSE ; } /* Update lower bounds on point-to-center distances based on the center variation. */ #if defined(_OPENMP) #pragma omp parallel for default(shared) private(x,c) num_threads(vl_get_max_threads()) #endif for (x = 0 ; x < (signed)numData ; ++x) { for (c = 0 ; c < self->numCenters ; ++c) { TYPE a = pointToCenterLB[c + x * self->numCenters] ; TYPE b = centerToNewCenterDistances[c] ; if (a < b) { pointToCenterLB[c + x * self->numCenters] = 0 ; } else { if (self->distance == VlDistanceL1) { pointToCenterLB[c + x * self->numCenters] = a - b ; } else { #if (FLT == VL_TYPE_FLOAT) TYPE sqrtab = sqrtf (a * b) ; #else TYPE sqrtab = sqrt (a * b) ; #endif pointToCenterLB[c + x * self->numCenters] = a + b - 2.0 * sqrtab ; } } } } #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies before assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n", cc, xx, a, b, assignments[xx]) ; } } } #endif /* Scan the data and do the reassignments. Use the bounds to skip as many point-to-center distance calculations as possible. */ allDone = VL_TRUE ; #if defined(_OPENMP) #pragma omp parallel for \ default(none) \ shared(self,numData, \ pointToClosestCenterUB,pointToCenterLB, \ nextCenterDistances,pointToClosestCenterUBIsStrict, \ assignments,data,distFn,allDone) \ private(c,x) \ reduction(+:numDistanceComputationsToRefreshUB,numDistanceComputationsToRefreshLB) \ num_threads(vl_get_max_threads()) #endif for (x = 0 ; x < (signed)numData ; ++ x) { /* A point x sticks with its current center assignmets[x] the UB to d(x, c[assigmnets[x]]) is not larger than half the distance of c[assigments[x]] to any other center c. */ if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= nextCenterDistances[assignments[x]]) { continue ; } for (c = 0 ; c < self->numCenters ; ++c) { vl_uint32 cx = assignments[x] ; TYPE distance ; /* The point is not reassigned to a given center c if either: 0 - c is already the assigned center 1 - The UB of d(x, c[assignments[x]]) is smaller than half the distance of c[assigments[x]] to c, OR 2 - The UB of d(x, c[assignmets[x]]) is smaller than the LB of the distance of x to c. */ if (cx == c) { continue ; } if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + cx * self->numCenters]) { continue ; } if (pointToClosestCenterUB[x] <= pointToCenterLB [c + x * self->numCenters]) { continue ; } /* If the UB is loose, try recomputing it and test again */ if (! pointToClosestCenterUBIsStrict[x]) { distance = distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension * cx) ; pointToClosestCenterUB[x] = distance ; pointToClosestCenterUBIsStrict[x] = VL_TRUE ; pointToCenterLB[cx + x * self->numCenters] = distance ; numDistanceComputationsToRefreshUB += 1 ; if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + cx * self->numCenters]) { continue ; } if (pointToClosestCenterUB[x] <= pointToCenterLB [c + x * self->numCenters]) { continue ; } } /* Now the UB is strict (equal to d(x, assignments[x])), but we still could not exclude that x should be reassigned to c. We therefore compute the distance, update the LB, and check if a reassigmnet must be made */ distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + c * self->dimension) ; numDistanceComputationsToRefreshLB += 1 ; pointToCenterLB[c + x * self->numCenters] = distance ; if (distance < pointToClosestCenterUB[x]) { assignments[x] = c ; pointToClosestCenterUB[x] = distance ; allDone = VL_FALSE ; /* the UB strict flag is already set here */ } } /* assign center */ } /* next data point */ totDistanceComputationsToRefreshUB += numDistanceComputationsToRefreshUB ; totDistanceComputationsToRefreshLB += numDistanceComputationsToRefreshLB ; totDistanceComputationsToRefreshCenterDistances += numDistanceComputationsToRefreshCenterDistances ; totDistanceComputationsToNewCenters += numDistanceComputationsToNewCenters ; totNumRestartedCenters += numRestartedCenters ; #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies after assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n", cc, xx, a, b, assignments[xx]) ; } } } #endif /* compute UB on energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++x) { energy += pointToClosestCenterUB[x] ; } if (self->verbosity) { vl_size numDistanceComputations = numDistanceComputationsToRefreshUB + numDistanceComputationsToRefreshLB + numDistanceComputationsToRefreshCenterDistances + numDistanceComputationsToNewCenters ; VL_PRINTF("kmeans: Elkan iter %d: energy <= %g, dist. calc. = %d\n", iteration, energy, numDistanceComputations) ; if (numRestartedCenters) { VL_PRINTF("kmeans: Elkan iter %d: restarted %d centers\n", iteration, energy, numRestartedCenters) ; } if (self->verbosity > 1) { VL_PRINTF("kmeans: Elkan iter %d: total dist. calc. per type: " "UB: %.1f%% (%d), LB: %.1f%% (%d), " "intra_center: %.1f%% (%d), " "new_center: %.1f%% (%d)\n", iteration, 100.0 * numDistanceComputationsToRefreshUB / numDistanceComputations, numDistanceComputationsToRefreshUB, 100.0 *numDistanceComputationsToRefreshLB / numDistanceComputations, numDistanceComputationsToRefreshLB, 100.0 * numDistanceComputationsToRefreshCenterDistances / numDistanceComputations, numDistanceComputationsToRefreshCenterDistances, 100.0 * numDistanceComputationsToNewCenters / numDistanceComputations, numDistanceComputationsToNewCenters) ; } } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: Elkan terminating because maximum number of iterations reached\n") ; } break ; } if (allDone) { if (self->verbosity) { VL_PRINTF("kmeans: Elkan terminating because the algorithm fully converged\n") ; } break ; } } /* next Elkan iteration */ /* compute true energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++ x) { vl_uindex cx = assignments [x] ; energy += distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension * cx) ; totDistanceComputationsToFinalize += 1 ; } { vl_size totDistanceComputations = totDistanceComputationsToInit + totDistanceComputationsToRefreshUB + totDistanceComputationsToRefreshLB + totDistanceComputationsToRefreshCenterDistances + totDistanceComputationsToNewCenters + totDistanceComputationsToFinalize ; double saving = (double)totDistanceComputations / (iteration * self->numCenters * numData) ; if (self->verbosity) { VL_PRINTF("kmeans: Elkan: total dist. calc.: %d (%.2f %% of Lloyd)\n", totDistanceComputations, saving * 100.0) ; if (totNumRestartedCenters) { VL_PRINTF("kmeans: Elkan: there have been %d restarts\n", totNumRestartedCenters) ; } } if (self->verbosity > 1) { VL_PRINTF("kmeans: Elkan: total dist. calc. per type: " "init: %.1f%% (%d), UB: %.1f%% (%d), LB: %.1f%% (%d), " "intra_center: %.1f%% (%d), " "new_center: %.1f%% (%d), " "finalize: %.1f%% (%d)\n", 100.0 * totDistanceComputationsToInit / totDistanceComputations, totDistanceComputationsToInit, 100.0 * totDistanceComputationsToRefreshUB / totDistanceComputations, totDistanceComputationsToRefreshUB, 100.0 *totDistanceComputationsToRefreshLB / totDistanceComputations, totDistanceComputationsToRefreshLB, 100.0 * totDistanceComputationsToRefreshCenterDistances / totDistanceComputations, totDistanceComputationsToRefreshCenterDistances, 100.0 * totDistanceComputationsToNewCenters / totDistanceComputations, totDistanceComputationsToNewCenters, 100.0 * totDistanceComputationsToFinalize / totDistanceComputations, totDistanceComputationsToFinalize) ; } } if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; vl_free(nextCenterDistances) ; vl_free(pointToClosestCenterUB) ; vl_free(pointToClosestCenterUBIsStrict) ; vl_free(pointToCenterLB) ; vl_free(newCenters) ; vl_free(centerToNewCenterDistances) ; return energy ; } /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { switch (self->algorithm) { case VlKMeansLloyd: return VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX)(self, data, numData) ; break ; case VlKMeansElkan: return VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX)(self, data, numData) ; break ; case VlKMeansANN: return VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX)(self, data, numData) ; break ; default: abort() ; } } /* VL_KMEANS_INSTANTIATING */ #else #ifndef __DOXYGEN__ #define FLT VL_TYPE_FLOAT #define TYPE float #define SFX f #define VL_KMEANS_INSTANTIATING #include "kmeans.c" #define FLT VL_TYPE_DOUBLE #define TYPE double #define SFX d #define VL_KMEANS_INSTANTIATING #include "kmeans.c" #endif /* VL_KMEANS_INSTANTIATING */ #endif /* ================================================================ */ #ifndef VL_KMEANS_INSTANTIATING /** ------------------------------------------------------------------ ** @brief Set centers ** @param self KMeans object. ** @param centers centers to copy. ** @param dimension data dimension. ** @param numCenters number of centers. **/ void vl_kmeans_set_centers (VlKMeans * self, void const * centers, vl_size dimension, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_set_centers_f (self, (float const *)centers, dimension, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_set_centers_d (self, (double const *)centers, dimension, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief init centers by randomly sampling data ** @param self KMeans object. ** @param data data to sample from. ** @param dimension data dimension. ** @param numData nmber of data points. ** @param numCenters number of centers. ** ** The function inits the KMeans centers by randomly sampling ** the data @a data. **/ void vl_kmeans_init_centers_with_rand_data (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_init_centers_with_rand_data_f (self, (float const *)data, dimension, numData, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_init_centers_with_rand_data_d (self, (double const *)data, dimension, numData, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Seed centers by the KMeans++ algorithm ** @param self KMeans object. ** @param data data to sample from. ** @param dimension data dimension. ** @param numData nmber of data points. ** @param numCenters number of centers. **/ void vl_kmeans_init_centers_plus_plus (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_init_centers_plus_plus_f (self, (float const *)data, dimension, numData, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_init_centers_plus_plus_d (self, (double const *)data, dimension, numData, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Quantize data ** @param self KMeans object. ** @param assignments data to closest center assignments (output). ** @param distances data to closest center distance (output). ** @param data data to quantize. ** @param numData number of data points to quantize. **/ void vl_kmeans_quantize (VlKMeans * self, vl_uint32 * assignments, void * distances, void const * data, vl_size numData) { switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_quantize_f (self, assignments, distances, (float const *)data, numData) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_quantize_d (self, assignments, distances, (double const *)data, numData) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Quantize data using approximate nearest neighbours (ANN). ** @param self KMeans object. ** @param assignments data to centers assignments (output). ** @param distances data to closes center distance (output) ** @param data data to quantize. ** @param numData number of data points. ** @param update choose wether to update current assignments. ** ** The function uses an ANN procedure to compute the approximate ** nearest neighbours of the input data point. ** ** Setting @a update to ::VL_TRUE will cause the algorithm ** to *update existing assignments*. This means that each ** element of @a assignments and @a distances is updated ony if the ** ANN procedure can find a better assignment of the existing one. **/ void vl_kmeans_quantize_ann (VlKMeans * self, vl_uint32 * assignments, void * distances, void const * data, vl_size numData, vl_bool update) { switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_quantize_ann_f (self, assignments, distances, (float const *)data, numData, update) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_quantize_ann_d (self, assignments, distances, (double const *)data, numData, update) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Refine center locations. ** @param self KMeans object. ** @param data data to quantize. ** @param numData number of data points. ** @return K-means energy at the end of optimization. ** ** The function calls the underlying K-means quantization algorithm ** (@ref VlKMeansAlgorithm) to quantize the specified data @a data. ** The function assumes that the cluster centers have already ** been assigned by using one of the seeding functions, or by ** setting them. **/ double vl_kmeans_refine_centers (VlKMeans * self, void const * data, vl_size numData) { assert (self->centers) ; switch (self->dataType) { case VL_TYPE_FLOAT : return _vl_kmeans_refine_centers_f (self, (float const *)data, numData) ; case VL_TYPE_DOUBLE : return _vl_kmeans_refine_centers_d (self, (double const *)data, numData) ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Cluster data. ** @param self KMeans object. ** @param data data to quantize. ** @param dimension data dimension. ** @param numData number of data points. ** @param numCenters number of clusters. ** @return K-means energy at the end of optimization. ** ** The function initializes the centers by using the initialization ** algorithm set by ::vl_kmeans_set_initialization and refines them ** by the quantization algorithm set by ::vl_kmeans_set_algorithm. ** The process is repeated one or more times (see ** ::vl_kmeans_set_num_repetitions) and the resutl with smaller ** energy is retained. **/ double vl_kmeans_cluster (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex repetition ; double bestEnergy = VL_INFINITY_D ; void * bestCenters = NULL ; for (repetition = 0 ; repetition < self->numRepetitions ; ++ repetition) { double energy ; double timeRef ; if (self->verbosity) { VL_PRINTF("kmeans: repetition %d of %d\n", repetition + 1, self->numRepetitions) ; } timeRef = vl_get_cpu_time() ; switch (self->initialization) { case VlKMeansRandomSelection : vl_kmeans_init_centers_with_rand_data (self, data, dimension, numData, numCenters) ; break ; case VlKMeansPlusPlus : vl_kmeans_init_centers_plus_plus (self, data, dimension, numData, numCenters) ; break ; default: abort() ; } if (self->verbosity) { VL_PRINTF("kmeans: K-means initialized in %.2f s\n", vl_get_cpu_time() - timeRef) ; } timeRef = vl_get_cpu_time () ; energy = vl_kmeans_refine_centers (self, data, numData) ; if (self->verbosity) { VL_PRINTF("kmeans: K-means terminated in %.2f s with energy %g\n", vl_get_cpu_time() - timeRef, energy) ; } /* copy centers to output if current solution is optimal */ /* check repetition == 0 as well in case energy = NaN, which */ /* can happen if the data contain NaNs */ if (energy < bestEnergy || repetition == 0) { void * temp ; bestEnergy = energy ; if (bestCenters == NULL) { bestCenters = vl_malloc(vl_get_type_size(self->dataType) * self->dimension * self->numCenters) ; } /* swap buffers */ temp = bestCenters ; bestCenters = self->centers ; self->centers = temp ; } /* better energy */ } /* next repetition */ vl_free (self->centers) ; self->centers = bestCenters ; return bestEnergy ; } /* VL_KMEANS_INSTANTIATING */ #endif #undef SFX #undef TYPE #undef FLT #undef VL_KMEANS_INSTANTIATING
_prism.c
/* Generated by Cython 0.20.1 on Thu Jul 17 17:54:14 2014 */ #define PY_SSIZE_T_CLEAN #ifndef CYTHON_USE_PYLONG_INTERNALS #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 0 #else #include "pyconfig.h" #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 1 #else #define CYTHON_USE_PYLONG_INTERNALS 0 #endif #endif #endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02040000 #error Cython requires Python 2.4+. #else #define CYTHON_ABI "0_20_1" #include <stddef.h> /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if CYTHON_COMPILING_IN_PYPY #define Py_OptimizeFlag 0 #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ (PyErr_Format(PyExc_TypeError, \ "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ (PyObject*)0)) #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ !PyComplex_Check(o)) #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #define __Pyx_PyIndex_Check PyIndex_Check #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #if PY_VERSION_HEX < 0x02060000 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_VERSION_HEX < 0x02060000 #define Py_TPFLAGS_HAVE_VERSION_TAG 0 #endif #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) #define Py_TPFLAGS_IS_ABSTRACT 0 #endif #if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #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 #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_CheckExact PyString_CheckExact #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_DecodeEscape PyString_DecodeEscape #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_Size PyString_Size #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Repr PyString_Repr #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #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_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_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) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) #else #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) #else #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) #else #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is a quiet NaN. */ float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #define __PYX_HAVE__fatiando__gravmag___prism #define __PYX_HAVE_API__fatiando__gravmag___prism #include "math.h" #include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "omp.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ (sizeof(type) < sizeof(Py_ssize_t)) || \ (sizeof(type) > sizeof(Py_ssize_t) && \ likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX) && \ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ v == (type)PY_SSIZE_T_MIN))) || \ (sizeof(type) == sizeof(Py_ssize_t) && \ (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(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_FromUString(s) __Pyx_PyObject_FromString((char*)s) #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) #define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) #define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) #define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((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 u_end - u - 1; } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys = NULL; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); 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 == NULL) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (ascii_chars_b == NULL || strncmp(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_XDECREF(sys); Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return 0; bad: Py_XDECREF(sys); 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 = NULL; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; default_encoding_c = PyBytes_AS_STRING(default_encoding); __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(sys); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(sys); Py_XDECREF(default_encoding); return -1; } #endif #endif #ifdef __GNUC__ /* Test for GCC > 2.95 */ #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* __GNUC__ > 2 ... */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ > 2 ... */ #else /* __GNUC__ */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "_prism.pyx", "__init__.pxd", "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; /* for error messages only */ struct __Pyx_StructField_* fields; size_t size; /* sizeof(type) */ size_t arraysize[8]; /* length of array in each dimension */ int ndim; char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * 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; /* "fatiando/gravmag/_prism.pyx":16 * * DTYPE = numpy.float * ctypedef numpy.float_t DTYPE_T # <<<<<<<<<<<<<< * * cdef inline double safe_atan2(double y, double x) nogil: */ typedef __pyx_t_5numpy_float_t __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif /*--- Type declarations ---*/ /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; #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); /*proto*/ #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 /* CYTHON_REFNANNY */ #define __Pyx_XDECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_XDECREF(tmp); \ } while (0) #define __Pyx_DECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_DECREF(tmp); \ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*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); /*proto*/ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); /*proto*/ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*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 CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); #if CYTHON_CCOMPLEX #define __Pyx_c_eqf(a, b) ((a)==(b)) #define __Pyx_c_sumf(a, b) ((a)+(b)) #define __Pyx_c_difff(a, b) ((a)-(b)) #define __Pyx_c_prodf(a, b) ((a)*(b)) #define __Pyx_c_quotf(a, b) ((a)/(b)) #define __Pyx_c_negf(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zerof(z) ((z)==(float)0) #define __Pyx_c_conjf(z) (::std::conj(z)) #if 1 #define __Pyx_c_absf(z) (::std::abs(z)) #define __Pyx_c_powf(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zerof(z) ((z)==0) #define __Pyx_c_conjf(z) (conjf(z)) #if 1 #define __Pyx_c_absf(z) (cabsf(z)) #define __Pyx_c_powf(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); #if CYTHON_CCOMPLEX #define __Pyx_c_eq(a, b) ((a)==(b)) #define __Pyx_c_sum(a, b) ((a)+(b)) #define __Pyx_c_diff(a, b) ((a)-(b)) #define __Pyx_c_prod(a, b) ((a)*(b)) #define __Pyx_c_quot(a, b) ((a)/(b)) #define __Pyx_c_neg(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero(z) ((z)==(double)0) #define __Pyx_c_conj(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs(z) (::std::abs(z)) #define __Pyx_c_pow(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero(z) ((z)==0) #define __Pyx_c_conj(z) (conj(z)) #if 1 #define __Pyx_c_abs(z) (cabs(z)) #define __Pyx_c_pow(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ typedef struct { int code_line; PyCodeObject* code_object; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'libc.math' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'cython' */ /* Module declarations from 'openmp' */ /* Module declarations from 'fatiando.gravmag._prism' */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2(double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_safe_log(double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelpot(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelx(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernely(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelz(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxx(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelyy(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(double, double, double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelzz(double, double, double, double); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T = { "DTYPE_T", NULL, sizeof(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "fatiando.gravmag._prism" int __pyx_module_is_main_fatiando__gravmag___prism = 0; /* Implementation of 'fatiando.gravmag._prism' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_tf(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, double __pyx_v_fx, double __pyx_v_fy, double __pyx_v_fz, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_2bx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_4by(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_6bz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_8gx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_10gy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_12gz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_14gxx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_16gxy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_18gxz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_20gyy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_22gyz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_24gzz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* proto */ static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_26potential(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res); /* 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 char __pyx_k_B[] = "B"; static char __pyx_k_H[] = "H"; static char __pyx_k_I[] = "I"; static char __pyx_k_L[] = "L"; static char __pyx_k_O[] = "O"; static char __pyx_k_Q[] = "Q"; static char __pyx_k_b[] = "b"; static char __pyx_k_d[] = "d"; static char __pyx_k_f[] = "f"; static char __pyx_k_g[] = "g"; static char __pyx_k_h[] = "h"; static char __pyx_k_i[] = "i"; static char __pyx_k_j[] = "j"; static char __pyx_k_k[] = "k"; static char __pyx_k_l[] = "l"; static char __pyx_k_q[] = "q"; static char __pyx_k_r[] = "r"; static char __pyx_k_x[] = "x"; static char __pyx_k_y[] = "y"; static char __pyx_k_z[] = "z"; static char __pyx_k_Zd[] = "Zd"; static char __pyx_k_Zf[] = "Zf"; static char __pyx_k_Zg[] = "Zg"; static char __pyx_k_bx[] = "bx"; static char __pyx_k_by[] = "by"; static char __pyx_k_bz[] = "bz"; static char __pyx_k_dx[] = "dx"; static char __pyx_k_dy[] = "dy"; static char __pyx_k_dz[] = "dz"; static char __pyx_k_fx[] = "fx"; static char __pyx_k_fy[] = "fy"; static char __pyx_k_fz[] = "fz"; static char __pyx_k_gx[] = "gx"; static char __pyx_k_gy[] = "gy"; static char __pyx_k_gz[] = "gz"; static char __pyx_k_mx[] = "mx"; static char __pyx_k_my[] = "my"; static char __pyx_k_mz[] = "mz"; static char __pyx_k_tf[] = "tf"; static char __pyx_k_v1[] = "v1"; static char __pyx_k_v2[] = "v2"; static char __pyx_k_v3[] = "v3"; static char __pyx_k_v4[] = "v4"; static char __pyx_k_v5[] = "v5"; static char __pyx_k_v6[] = "v6"; static char __pyx_k_x1[] = "x1"; static char __pyx_k_x2[] = "x2"; static char __pyx_k_xp[] = "xp"; static char __pyx_k_y1[] = "y1"; static char __pyx_k_y2[] = "y2"; static char __pyx_k_yp[] = "yp"; static char __pyx_k_z1[] = "z1"; static char __pyx_k_z2[] = "z2"; static char __pyx_k_zp[] = "zp"; static char __pyx_k_gxx[] = "gxx"; static char __pyx_k_gxy[] = "gxy"; static char __pyx_k_gxz[] = "gxz"; static char __pyx_k_gyy[] = "gyy"; static char __pyx_k_gyz[] = "gyz"; static char __pyx_k_gzz[] = "gzz"; static char __pyx_k_res[] = "res"; static char __pyx_k_main[] = "__main__"; static char __pyx_k_size[] = "size"; static char __pyx_k_test[] = "__test__"; static char __pyx_k_tmp1[] = "tmp1"; static char __pyx_k_tmp2[] = "tmp2"; static char __pyx_k_DTYPE[] = "DTYPE"; static char __pyx_k_array[] = "array"; static char __pyx_k_dtype[] = "dtype"; static char __pyx_k_float[] = "float"; static char __pyx_k_numpy[] = "numpy"; static char __pyx_k_range[] = "range"; static char __pyx_k_import[] = "__import__"; static char __pyx_k_kernel[] = "kernel"; static char __pyx_k_density[] = "density"; static char __pyx_k_potential[] = "potential"; static char __pyx_k_ValueError[] = "ValueError"; static char __pyx_k_RuntimeError[] = "RuntimeError"; static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; static char __pyx_k_fatiando_gravmag__prism[] = "fatiando.gravmag._prism"; static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static char __pyx_k_home_leo_src_fatiando_fatiando[] = "/home/leo/src/fatiando/fatiando/gravmag/_prism.pyx"; static char __pyx_k_Cython_implementation_of_the_gr[] = "\nCython implementation of the gravity and magnetic fields of right rectangular\nprisms.\n"; static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_DTYPE; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_array; static PyObject *__pyx_n_s_bx; static PyObject *__pyx_n_s_by; static PyObject *__pyx_n_s_bz; static PyObject *__pyx_n_s_density; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_dx; static PyObject *__pyx_n_s_dy; static PyObject *__pyx_n_s_dz; static PyObject *__pyx_n_s_fatiando_gravmag__prism; static PyObject *__pyx_n_s_float; static PyObject *__pyx_n_s_fx; static PyObject *__pyx_n_s_fy; static PyObject *__pyx_n_s_fz; static PyObject *__pyx_n_s_gx; static PyObject *__pyx_n_s_gxx; static PyObject *__pyx_n_s_gxy; static PyObject *__pyx_n_s_gxz; static PyObject *__pyx_n_s_gy; static PyObject *__pyx_n_s_gyy; static PyObject *__pyx_n_s_gyz; static PyObject *__pyx_n_s_gz; static PyObject *__pyx_n_s_gzz; static PyObject *__pyx_kp_s_home_leo_src_fatiando_fatiando; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_j; static PyObject *__pyx_n_s_k; static PyObject *__pyx_n_s_kernel; static PyObject *__pyx_n_s_l; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mx; static PyObject *__pyx_n_s_my; static PyObject *__pyx_n_s_mz; 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_numpy; static PyObject *__pyx_n_s_potential; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_releasebuffer; static PyObject *__pyx_n_s_r; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_res; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_tf; static PyObject *__pyx_n_s_tmp1; static PyObject *__pyx_n_s_tmp2; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_v1; static PyObject *__pyx_n_s_v2; static PyObject *__pyx_n_s_v3; static PyObject *__pyx_n_s_v4; static PyObject *__pyx_n_s_v5; static PyObject *__pyx_n_s_v6; static PyObject *__pyx_n_s_x; static PyObject *__pyx_n_s_x1; static PyObject *__pyx_n_s_x2; static PyObject *__pyx_n_s_xp; static PyObject *__pyx_n_s_y; static PyObject *__pyx_n_s_y1; static PyObject *__pyx_n_s_y2; static PyObject *__pyx_n_s_yp; static PyObject *__pyx_n_s_z; static PyObject *__pyx_n_s_z1; static PyObject *__pyx_n_s_z2; static PyObject *__pyx_n_s_zp; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__9; static PyObject *__pyx_tuple__11; static PyObject *__pyx_tuple__13; static PyObject *__pyx_tuple__15; static PyObject *__pyx_tuple__17; static PyObject *__pyx_tuple__19; static PyObject *__pyx_tuple__21; static PyObject *__pyx_tuple__23; static PyObject *__pyx_tuple__25; static PyObject *__pyx_tuple__27; static PyObject *__pyx_tuple__29; static PyObject *__pyx_tuple__31; static PyObject *__pyx_tuple__33; static PyObject *__pyx_codeobj__8; static PyObject *__pyx_codeobj__10; static PyObject *__pyx_codeobj__12; static PyObject *__pyx_codeobj__14; static PyObject *__pyx_codeobj__16; static PyObject *__pyx_codeobj__18; static PyObject *__pyx_codeobj__20; static PyObject *__pyx_codeobj__22; static PyObject *__pyx_codeobj__24; static PyObject *__pyx_codeobj__26; static PyObject *__pyx_codeobj__28; static PyObject *__pyx_codeobj__30; static PyObject *__pyx_codeobj__32; static PyObject *__pyx_codeobj__34; /* "fatiando/gravmag/_prism.pyx":18 * ctypedef numpy.float_t DTYPE_T * * cdef inline double safe_atan2(double y, double x) nogil: # <<<<<<<<<<<<<< * cdef double res * if y == 0: */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2(double __pyx_v_y, double __pyx_v_x) { double __pyx_v_res; double __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "fatiando/gravmag/_prism.pyx":20 * cdef inline double safe_atan2(double y, double x) nogil: * cdef double res * if y == 0: # <<<<<<<<<<<<<< * res = 0 * elif (y > 0) and (x < 0): */ __pyx_t_1 = ((__pyx_v_y == 0.0) != 0); if (__pyx_t_1) { /* "fatiando/gravmag/_prism.pyx":21 * cdef double res * if y == 0: * res = 0 # <<<<<<<<<<<<<< * elif (y > 0) and (x < 0): * res = atan2(y, x) - 3.1415926535897931159979634685441851615906 */ __pyx_v_res = 0.0; goto __pyx_L3; } /* "fatiando/gravmag/_prism.pyx":22 * if y == 0: * res = 0 * elif (y > 0) and (x < 0): # <<<<<<<<<<<<<< * res = atan2(y, x) - 3.1415926535897931159979634685441851615906 * elif (y < 0) and (x < 0): */ __pyx_t_1 = ((__pyx_v_y > 0.0) != 0); if (__pyx_t_1) { __pyx_t_2 = ((__pyx_v_x < 0.0) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { /* "fatiando/gravmag/_prism.pyx":23 * res = 0 * elif (y > 0) and (x < 0): * res = atan2(y, x) - 3.1415926535897931159979634685441851615906 # <<<<<<<<<<<<<< * elif (y < 0) and (x < 0): * res = atan2(y, x) + 3.1415926535897931159979634685441851615906 */ __pyx_v_res = (atan2(__pyx_v_y, __pyx_v_x) - 3.1415926535897931159979634685441851615906); goto __pyx_L3; } /* "fatiando/gravmag/_prism.pyx":24 * elif (y > 0) and (x < 0): * res = atan2(y, x) - 3.1415926535897931159979634685441851615906 * elif (y < 0) and (x < 0): # <<<<<<<<<<<<<< * res = atan2(y, x) + 3.1415926535897931159979634685441851615906 * else: */ __pyx_t_3 = ((__pyx_v_y < 0.0) != 0); if (__pyx_t_3) { __pyx_t_1 = ((__pyx_v_x < 0.0) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { /* "fatiando/gravmag/_prism.pyx":25 * res = atan2(y, x) - 3.1415926535897931159979634685441851615906 * elif (y < 0) and (x < 0): * res = atan2(y, x) + 3.1415926535897931159979634685441851615906 # <<<<<<<<<<<<<< * else: * res = atan2(y, x) */ __pyx_v_res = (atan2(__pyx_v_y, __pyx_v_x) + 3.1415926535897931159979634685441851615906); goto __pyx_L3; } /*else*/ { /* "fatiando/gravmag/_prism.pyx":27 * res = atan2(y, x) + 3.1415926535897931159979634685441851615906 * else: * res = atan2(y, x) # <<<<<<<<<<<<<< * return res * */ __pyx_v_res = atan2(__pyx_v_y, __pyx_v_x); } __pyx_L3:; /* "fatiando/gravmag/_prism.pyx":28 * else: * res = atan2(y, x) * return res # <<<<<<<<<<<<<< * * cdef inline double safe_log(double x) nogil: */ __pyx_r = __pyx_v_res; goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":18 * ctypedef numpy.float_t DTYPE_T * * cdef inline double safe_atan2(double y, double x) nogil: # <<<<<<<<<<<<<< * cdef double res * if y == 0: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":30 * return res * * cdef inline double safe_log(double x) nogil: # <<<<<<<<<<<<<< * cdef double res * if x == 0: */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_safe_log(double __pyx_v_x) { double __pyx_v_res; double __pyx_r; int __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":32 * cdef inline double safe_log(double x) nogil: * cdef double res * if x == 0: # <<<<<<<<<<<<<< * res = 0 * else: */ __pyx_t_1 = ((__pyx_v_x == 0.0) != 0); if (__pyx_t_1) { /* "fatiando/gravmag/_prism.pyx":33 * cdef double res * if x == 0: * res = 0 # <<<<<<<<<<<<<< * else: * res = log(x) */ __pyx_v_res = 0.0; goto __pyx_L3; } /*else*/ { /* "fatiando/gravmag/_prism.pyx":35 * res = 0 * else: * res = log(x) # <<<<<<<<<<<<<< * return res * */ __pyx_v_res = log(__pyx_v_x); } __pyx_L3:; /* "fatiando/gravmag/_prism.pyx":36 * else: * res = log(x) * return res # <<<<<<<<<<<<<< * * cdef inline double kernelpot(double x, double y, double z, double r) nogil: */ __pyx_r = __pyx_v_res; goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":30 * return res * * cdef inline double safe_log(double x) nogil: # <<<<<<<<<<<<<< * cdef double res * if x == 0: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":38 * return res * * cdef inline double kernelpot(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return (x*y*safe_log(z + r) + y*z*safe_log(x + r) + x*z*safe_log(y + r) * - 0.5*x**2*safe_atan2(z*y, x*r) - 0.5*y**2*safe_atan2(z*x, y*r) */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelpot(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":41 * return (x*y*safe_log(z + r) + y*z*safe_log(x + r) + x*z*safe_log(y + r) * - 0.5*x**2*safe_atan2(z*y, x*r) - 0.5*y**2*safe_atan2(z*x, y*r) * - 0.5*z**2*safe_atan2(x*y, z*r)) # <<<<<<<<<<<<<< * * # Minus in gravity because Nagy et al (2000) give the formula for the gradient */ __pyx_r = (((((((__pyx_v_x * __pyx_v_y) * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_z + __pyx_v_r))) + ((__pyx_v_y * __pyx_v_z) * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_x + __pyx_v_r)))) + ((__pyx_v_x * __pyx_v_z) * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_y + __pyx_v_r)))) - ((0.5 * pow(__pyx_v_x, 2.0)) * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_z * __pyx_v_y), (__pyx_v_x * __pyx_v_r)))) - ((0.5 * pow(__pyx_v_y, 2.0)) * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_z * __pyx_v_x), (__pyx_v_y * __pyx_v_r)))) - ((0.5 * pow(__pyx_v_z, 2.0)) * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_x * __pyx_v_y), (__pyx_v_z * __pyx_v_r)))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":38 * return res * * cdef inline double kernelpot(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return (x*y*safe_log(z + r) + y*z*safe_log(x + r) + x*z*safe_log(y + r) * - 0.5*x**2*safe_atan2(z*y, x*r) - 0.5*y**2*safe_atan2(z*x, y*r) */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":45 * # Minus in gravity because Nagy et al (2000) give the formula for the gradient * # of the potential. Gravity is -grad(V). * cdef inline double kernelx(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(y*safe_log(z + r) + z*safe_log(y + r) - x*safe_atan2(z*y, x*r)) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelx(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":46 * # of the potential. Gravity is -grad(V). * cdef inline double kernelx(double x, double y, double z, double r) nogil: * return -(y*safe_log(z + r) + z*safe_log(y + r) - x*safe_atan2(z*y, x*r)) # <<<<<<<<<<<<<< * * cdef inline double kernely(double x, double y, double z, double r) nogil: */ __pyx_r = (-(((__pyx_v_y * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_z + __pyx_v_r))) + (__pyx_v_z * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_y + __pyx_v_r)))) - (__pyx_v_x * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_z * __pyx_v_y), (__pyx_v_x * __pyx_v_r))))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":45 * # Minus in gravity because Nagy et al (2000) give the formula for the gradient * # of the potential. Gravity is -grad(V). * cdef inline double kernelx(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(y*safe_log(z + r) + z*safe_log(y + r) - x*safe_atan2(z*y, x*r)) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":48 * return -(y*safe_log(z + r) + z*safe_log(y + r) - x*safe_atan2(z*y, x*r)) * * cdef inline double kernely(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(z*safe_log(x + r) + x*safe_log(z + r) - y*safe_atan2(x*z, y*r)) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernely(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":49 * * cdef inline double kernely(double x, double y, double z, double r) nogil: * return -(z*safe_log(x + r) + x*safe_log(z + r) - y*safe_atan2(x*z, y*r)) # <<<<<<<<<<<<<< * * cdef inline double kernelz(double x, double y, double z, double r) nogil: */ __pyx_r = (-(((__pyx_v_z * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_x + __pyx_v_r))) + (__pyx_v_x * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_z + __pyx_v_r)))) - (__pyx_v_y * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_x * __pyx_v_z), (__pyx_v_y * __pyx_v_r))))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":48 * return -(y*safe_log(z + r) + z*safe_log(y + r) - x*safe_atan2(z*y, x*r)) * * cdef inline double kernely(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(z*safe_log(x + r) + x*safe_log(z + r) - y*safe_atan2(x*z, y*r)) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":51 * return -(z*safe_log(x + r) + x*safe_log(z + r) - y*safe_atan2(x*z, y*r)) * * cdef inline double kernelz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(x*safe_log(y + r) + y*safe_log(x + r) - z*safe_atan2(x*y, z*r)) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelz(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":52 * * cdef inline double kernelz(double x, double y, double z, double r) nogil: * return -(x*safe_log(y + r) + y*safe_log(x + r) - z*safe_atan2(x*y, z*r)) # <<<<<<<<<<<<<< * * cdef inline double kernelxx(double x, double y, double z, double r) nogil: */ __pyx_r = (-(((__pyx_v_x * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_y + __pyx_v_r))) + (__pyx_v_y * __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_x + __pyx_v_r)))) - (__pyx_v_z * __pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_x * __pyx_v_y), (__pyx_v_z * __pyx_v_r))))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":51 * return -(z*safe_log(x + r) + x*safe_log(z + r) - y*safe_atan2(x*z, y*r)) * * cdef inline double kernelz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -(x*safe_log(y + r) + y*safe_log(x + r) - z*safe_atan2(x*y, z*r)) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":54 * return -(x*safe_log(y + r) + y*safe_log(x + r) - z*safe_atan2(x*y, z*r)) * * cdef inline double kernelxx(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(z*y, x*r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxx(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":55 * * cdef inline double kernelxx(double x, double y, double z, double r) nogil: * return -safe_atan2(z*y, x*r) # <<<<<<<<<<<<<< * * cdef inline double kernelxy(double x, double y, double z, double r) nogil: */ __pyx_r = (-__pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_z * __pyx_v_y), (__pyx_v_x * __pyx_v_r))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":54 * return -(x*safe_log(y + r) + y*safe_log(x + r) - z*safe_atan2(x*y, z*r)) * * cdef inline double kernelxx(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(z*y, x*r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":57 * return -safe_atan2(z*y, x*r) * * cdef inline double kernelxy(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(z + r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(CYTHON_UNUSED double __pyx_v_x, CYTHON_UNUSED double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":58 * * cdef inline double kernelxy(double x, double y, double z, double r) nogil: * return safe_log(z + r) # <<<<<<<<<<<<<< * * cdef inline double kernelxz(double x, double y, double z, double r) nogil: */ __pyx_r = __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_z + __pyx_v_r)); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":57 * return -safe_atan2(z*y, x*r) * * cdef inline double kernelxy(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(z + r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":60 * return safe_log(z + r) * * cdef inline double kernelxz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(y + r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(CYTHON_UNUSED double __pyx_v_x, double __pyx_v_y, CYTHON_UNUSED double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":61 * * cdef inline double kernelxz(double x, double y, double z, double r) nogil: * return safe_log(y + r) # <<<<<<<<<<<<<< * * cdef inline double kernelyy(double x, double y, double z, double r) nogil: */ __pyx_r = __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_y + __pyx_v_r)); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":60 * return safe_log(z + r) * * cdef inline double kernelxz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(y + r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":63 * return safe_log(y + r) * * cdef inline double kernelyy(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(z*x, y*r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelyy(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":64 * * cdef inline double kernelyy(double x, double y, double z, double r) nogil: * return -safe_atan2(z*x, y*r) # <<<<<<<<<<<<<< * * cdef inline double kernelyz(double x, double y, double z, double r) nogil: */ __pyx_r = (-__pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_z * __pyx_v_x), (__pyx_v_y * __pyx_v_r))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":63 * return safe_log(y + r) * * cdef inline double kernelyy(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(z*x, y*r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":66 * return -safe_atan2(z*x, y*r) * * cdef inline double kernelyz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(x + r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(double __pyx_v_x, CYTHON_UNUSED double __pyx_v_y, CYTHON_UNUSED double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":67 * * cdef inline double kernelyz(double x, double y, double z, double r) nogil: * return safe_log(x + r) # <<<<<<<<<<<<<< * * cdef inline double kernelzz(double x, double y, double z, double r) nogil: */ __pyx_r = __pyx_f_8fatiando_7gravmag_6_prism_safe_log((__pyx_v_x + __pyx_v_r)); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":66 * return -safe_atan2(z*x, y*r) * * cdef inline double kernelyz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return safe_log(x + r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":69 * return safe_log(x + r) * * cdef inline double kernelzz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(x*y, z*r) * */ static CYTHON_INLINE double __pyx_f_8fatiando_7gravmag_6_prism_kernelzz(double __pyx_v_x, double __pyx_v_y, double __pyx_v_z, double __pyx_v_r) { double __pyx_r; /* "fatiando/gravmag/_prism.pyx":70 * * cdef inline double kernelzz(double x, double y, double z, double r) nogil: * return -safe_atan2(x*y, z*r) # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_r = (-__pyx_f_8fatiando_7gravmag_6_prism_safe_atan2((__pyx_v_x * __pyx_v_y), (__pyx_v_z * __pyx_v_r))); goto __pyx_L0; /* "fatiando/gravmag/_prism.pyx":69 * return safe_log(x + r) * * cdef inline double kernelzz(double x, double y, double z, double r) nogil: # <<<<<<<<<<<<<< * return -safe_atan2(x*y, z*r) * */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":74 * @cython.wraparound(False) * @cython.boundscheck(False) * def tf(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_1tf(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_tf[] = "tf(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double mx, double my, double mz, double fx, double fy, double fz, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_1tf = {__Pyx_NAMESTR("tf"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_1tf, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_tf)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_1tf(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_mx; double __pyx_v_my; double __pyx_v_mz; double __pyx_v_fx; double __pyx_v_fy; double __pyx_v_fz; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("tf (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_mx,&__pyx_n_s_my,&__pyx_n_s_mz,&__pyx_n_s_fx,&__pyx_n_s_fy,&__pyx_n_s_fz,&__pyx_n_s_res,0}; PyObject* values[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mx)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_my)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mz)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fx)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 13: if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fy)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 14: if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fz)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 15: if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "tf") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 16) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); values[12] = PyTuple_GET_ITEM(__pyx_args, 12); values[13] = PyTuple_GET_ITEM(__pyx_args, 13); values[14] = PyTuple_GET_ITEM(__pyx_args, 14); values[15] = PyTuple_GET_ITEM(__pyx_args, 15); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mx = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_mx == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_my = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_my == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mz = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_mz == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_fx = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_fx == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_fy = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_fy == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_fz = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_fz == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[15]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("tf", 1, 16, 16, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.tf", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_tf(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_mx, __pyx_v_my, __pyx_v_mz, __pyx_v_fx, __pyx_v_fy, __pyx_v_fz, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_tf(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, double __pyx_v_fx, double __pyx_v_fy, double __pyx_v_fz, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v1; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v2; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v3; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v4; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v5; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v6; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_bx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_by; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_bz; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("tf", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":83 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, v1, v2, v3, v4, v5, v6, bx, by, bz, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":84 * cdef DTYPE_T kernel, r, v1, v2, v3, v4, v5, v6, bx, by, bz, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":85 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":86 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":87 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":88 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_r) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_v4) lastprivate(__pyx_v_i) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_by) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_v6) lastprivate(__pyx_v_v5) lastprivate(__pyx_v_v2) lastprivate(__pyx_v_v1) lastprivate(__pyx_v_k) lastprivate(__pyx_v_v3) lastprivate(__pyx_v_bx) lastprivate(__pyx_v_j) lastprivate(__pyx_v_bz) lastprivate(__pyx_v_kernel) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v4 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_by = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v6 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v5 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v1 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_v3 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_bx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_bz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":90 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":91 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":92 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":93 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":94 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":95 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":96 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":97 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) # <<<<<<<<<<<<<< * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) */ __pyx_v_v1 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxx(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":98 * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) # <<<<<<<<<<<<<< * v3 = kernelxz(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) */ __pyx_v_v2 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":99 * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) # <<<<<<<<<<<<<< * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) */ __pyx_v_v3 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":100 * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) # <<<<<<<<<<<<<< * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) */ __pyx_v_v4 = __pyx_f_8fatiando_7gravmag_6_prism_kernelyy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":101 * v3 = kernelxz(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) # <<<<<<<<<<<<<< * v6 = kernelzz(dx, dy, dz, r) * bx = (v1*mx + v2*my + v3*mz) */ __pyx_v_v5 = __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":102 * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) # <<<<<<<<<<<<<< * bx = (v1*mx + v2*my + v3*mz) * by = (v2*mx + v4*my + v5*mz) */ __pyx_v_v6 = __pyx_f_8fatiando_7gravmag_6_prism_kernelzz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":103 * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) * bx = (v1*mx + v2*my + v3*mz) # <<<<<<<<<<<<<< * by = (v2*mx + v4*my + v5*mz) * bz = (v3*mx + v5*my + v6*mz) */ __pyx_v_bx = (((__pyx_v_v1 * __pyx_v_mx) + (__pyx_v_v2 * __pyx_v_my)) + (__pyx_v_v3 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":104 * v6 = kernelzz(dx, dy, dz, r) * bx = (v1*mx + v2*my + v3*mz) * by = (v2*mx + v4*my + v5*mz) # <<<<<<<<<<<<<< * bz = (v3*mx + v5*my + v6*mz) * kernel = fx*bx + fy*by + fz*bz */ __pyx_v_by = (((__pyx_v_v2 * __pyx_v_mx) + (__pyx_v_v4 * __pyx_v_my)) + (__pyx_v_v5 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":105 * bx = (v1*mx + v2*my + v3*mz) * by = (v2*mx + v4*my + v5*mz) * bz = (v3*mx + v5*my + v6*mz) # <<<<<<<<<<<<<< * kernel = fx*bx + fy*by + fz*bz * res[l] += ((-1.)**(i + j + k))*kernel */ __pyx_v_bz = (((__pyx_v_v3 * __pyx_v_mx) + (__pyx_v_v5 * __pyx_v_my)) + (__pyx_v_v6 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":106 * by = (v2*mx + v4*my + v5*mz) * bz = (v3*mx + v5*my + v6*mz) * kernel = fx*bx + fy*by + fz*bz # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel * */ __pyx_v_kernel = (((__pyx_v_fx * __pyx_v_bx) + (__pyx_v_fy * __pyx_v_by)) + (__pyx_v_fz * __pyx_v_bz)); /* "fatiando/gravmag/_prism.pyx":107 * bz = (v3*mx + v5*my + v6*mz) * kernel = fx*bx + fy*by + fz*bz * res[l] += ((-1.)**(i + j + k))*kernel # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += (pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":87 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":74 * @cython.wraparound(False) * @cython.boundscheck(False) * def tf(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.tf", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":111 * @cython.wraparound(False) * @cython.boundscheck(False) * def bx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_3bx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_2bx[] = "bx(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double mx, double my, double mz, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_3bx = {__Pyx_NAMESTR("bx"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_3bx, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_2bx)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_3bx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_mx; double __pyx_v_my; double __pyx_v_mz; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("bx (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_mx,&__pyx_n_s_my,&__pyx_n_s_mz,&__pyx_n_s_res,0}; PyObject* values[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mx)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_my)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mz)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "bx") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 13) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); values[12] = PyTuple_GET_ITEM(__pyx_args, 12); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mx = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_mx == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_my = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_my == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mz = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_mz == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[12]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("bx", 1, 13, 13, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.bx", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_2bx(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_mx, __pyx_v_my, __pyx_v_mz, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_2bx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v1; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v2; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v3; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("bx", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":120 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, v1, v2, v3, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":121 * cdef DTYPE_T kernel, r, v1, v2, v3, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":122 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":123 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":124 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":125 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_k) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_v1) lastprivate(__pyx_v_r) lastprivate(__pyx_v_j) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_i) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_v3) lastprivate(__pyx_v_v2) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_dz) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_v1 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v3 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":127 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":128 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":129 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":130 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":131 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":132 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":133 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":134 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) # <<<<<<<<<<<<<< * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) */ __pyx_v_v1 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxx(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":135 * r = sqrt(dx**2 + dy**2 + dz**2) * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) # <<<<<<<<<<<<<< * v3 = kernelxz(dx, dy, dz, r) * kernel = (v1*mx + v2*my + v3*mz) */ __pyx_v_v2 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":136 * v1 = kernelxx(dx, dy, dz, r) * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) # <<<<<<<<<<<<<< * kernel = (v1*mx + v2*my + v3*mz) * res[l] += ((-1.)**(i + j + k))*kernel */ __pyx_v_v3 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":137 * v2 = kernelxy(dx, dy, dz, r) * v3 = kernelxz(dx, dy, dz, r) * kernel = (v1*mx + v2*my + v3*mz) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel * */ __pyx_v_kernel = (((__pyx_v_v1 * __pyx_v_mx) + (__pyx_v_v2 * __pyx_v_my)) + (__pyx_v_v3 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":138 * v3 = kernelxz(dx, dy, dz, r) * kernel = (v1*mx + v2*my + v3*mz) * res[l] += ((-1.)**(i + j + k))*kernel # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += (pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":124 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":111 * @cython.wraparound(False) * @cython.boundscheck(False) * def bx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.bx", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":142 * @cython.wraparound(False) * @cython.boundscheck(False) * def by(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_5by(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_4by[] = "by(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double mx, double my, double mz, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_5by = {__Pyx_NAMESTR("by"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_5by, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_4by)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_5by(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_mx; double __pyx_v_my; double __pyx_v_mz; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("by (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_mx,&__pyx_n_s_my,&__pyx_n_s_mz,&__pyx_n_s_res,0}; PyObject* values[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mx)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_my)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mz)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "by") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 13) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); values[12] = PyTuple_GET_ITEM(__pyx_args, 12); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mx = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_mx == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_my = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_my == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mz = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_mz == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[12]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("by", 1, 13, 13, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.by", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_4by(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_mx, __pyx_v_my, __pyx_v_mz, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_4by(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v2; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v4; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v5; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("by", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":151 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, v2, v4, v5, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":152 * cdef DTYPE_T kernel, r, v2, v4, v5, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":153 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":154 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":155 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":156 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_k) lastprivate(__pyx_v_j) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_i) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_v4) lastprivate(__pyx_v_v2) lastprivate(__pyx_v_v5) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v4 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v5 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":158 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":159 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":160 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":161 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":162 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":163 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * v2 = kernelxy(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":164 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * v2 = kernelxy(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":165 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * v2 = kernelxy(dx, dy, dz, r) # <<<<<<<<<<<<<< * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) */ __pyx_v_v2 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":166 * r = sqrt(dx**2 + dy**2 + dz**2) * v2 = kernelxy(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) # <<<<<<<<<<<<<< * v5 = kernelyz(dx, dy, dz, r) * kernel = (v2*mx + v4*my + v5*mz) */ __pyx_v_v4 = __pyx_f_8fatiando_7gravmag_6_prism_kernelyy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":167 * v2 = kernelxy(dx, dy, dz, r) * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) # <<<<<<<<<<<<<< * kernel = (v2*mx + v4*my + v5*mz) * res[l] += ((-1.)**(i + j + k))*kernel */ __pyx_v_v5 = __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":168 * v4 = kernelyy(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) * kernel = (v2*mx + v4*my + v5*mz) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel * */ __pyx_v_kernel = (((__pyx_v_v2 * __pyx_v_mx) + (__pyx_v_v4 * __pyx_v_my)) + (__pyx_v_v5 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":169 * v5 = kernelyz(dx, dy, dz, r) * kernel = (v2*mx + v4*my + v5*mz) * res[l] += ((-1.)**(i + j + k))*kernel # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += (pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":155 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":142 * @cython.wraparound(False) * @cython.boundscheck(False) * def by(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.by", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":173 * @cython.wraparound(False) * @cython.boundscheck(False) * def bz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_7bz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_6bz[] = "bz(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double mx, double my, double mz, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_7bz = {__Pyx_NAMESTR("bz"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_7bz, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_6bz)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_7bz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_mx; double __pyx_v_my; double __pyx_v_mz; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("bz (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_mx,&__pyx_n_s_my,&__pyx_n_s_mz,&__pyx_n_s_res,0}; PyObject* values[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mx)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_my)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mz)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "bz") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 13) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); values[12] = PyTuple_GET_ITEM(__pyx_args, 12); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mx = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_mx == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_my = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_my == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_mz = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_mz == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[12]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("bz", 1, 13, 13, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.bz", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_6bz(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_mx, __pyx_v_my, __pyx_v_mz, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_6bz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_mx, double __pyx_v_my, double __pyx_v_mz, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v3; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v5; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_v6; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("bz", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":182 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, v3, v5, v6, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":183 * cdef DTYPE_T kernel, r, v3, v5, v6, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":184 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":185 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":186 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":187 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_v3) lastprivate(__pyx_v_j) lastprivate(__pyx_v_v5) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_v6) lastprivate(__pyx_v_i) lastprivate(__pyx_v_k) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_r) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v3 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_v5 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_v6 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":189 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":190 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":191 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":192 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":193 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":194 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * v3 = kernelxz(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":195 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * v3 = kernelxz(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":196 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * v3 = kernelxz(dx, dy, dz, r) # <<<<<<<<<<<<<< * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) */ __pyx_v_v3 = __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":197 * r = sqrt(dx**2 + dy**2 + dz**2) * v3 = kernelxz(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) # <<<<<<<<<<<<<< * v6 = kernelzz(dx, dy, dz, r) * kernel = (v3*mx + v5*my + v6*mz) */ __pyx_v_v5 = __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":198 * v3 = kernelxz(dx, dy, dz, r) * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) # <<<<<<<<<<<<<< * kernel = (v3*mx + v5*my + v6*mz) * res[l] += ((-1.)**(i + j + k))*kernel */ __pyx_v_v6 = __pyx_f_8fatiando_7gravmag_6_prism_kernelzz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":199 * v5 = kernelyz(dx, dy, dz, r) * v6 = kernelzz(dx, dy, dz, r) * kernel = (v3*mx + v5*my + v6*mz) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel * */ __pyx_v_kernel = (((__pyx_v_v3 * __pyx_v_mx) + (__pyx_v_v5 * __pyx_v_my)) + (__pyx_v_v6 * __pyx_v_mz)); /* "fatiando/gravmag/_prism.pyx":200 * v6 = kernelzz(dx, dy, dz, r) * kernel = (v3*mx + v5*my + v6*mz) * res[l] += ((-1.)**(i + j + k))*kernel # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += (pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":186 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":173 * @cython.wraparound(False) * @cython.boundscheck(False) * def bz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.bz", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":204 * @cython.wraparound(False) * @cython.boundscheck(False) * def gx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_9gx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_8gx[] = "gx(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_9gx = {__Pyx_NAMESTR("gx"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_9gx, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_8gx)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_9gx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gx (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gx") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gx", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gx", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_8gx(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_8gx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gx", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":213 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":214 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":215 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":216 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":217 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":218 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_i) lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_k) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_j) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); /* "fatiando/gravmag/_prism.pyx":220 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":221 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":222 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":223 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":224 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":225 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelx(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":226 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelx(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":227 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelx(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelx(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":228 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelx(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":217 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":204 * @cython.wraparound(False) * @cython.boundscheck(False) * def gx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gx", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":232 * @cython.wraparound(False) * @cython.boundscheck(False) * def gy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_11gy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_10gy[] = "gy(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_11gy = {__Pyx_NAMESTR("gy"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_11gy, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_10gy)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_11gy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gy (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gy") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gy", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gy", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_10gy(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_10gy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gy", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":241 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":242 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":243 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":244 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":245 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":246 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_j) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_i) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_k) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); /* "fatiando/gravmag/_prism.pyx":248 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":249 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":250 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":251 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":252 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":253 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernely(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":254 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernely(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":255 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernely(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernely(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":256 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernely(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":245 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":232 * @cython.wraparound(False) * @cython.boundscheck(False) * def gy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":260 * @cython.wraparound(False) * @cython.boundscheck(False) * def gz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_13gz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_12gz[] = "gz(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_13gz = {__Pyx_NAMESTR("gz"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_13gz, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_12gz)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_13gz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gz (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gz") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gz", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gz", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 265; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_12gz(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_12gz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gz", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":269 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":270 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":271 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":272 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":273 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":274 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_k) lastprivate(__pyx_v_i) lastprivate(__pyx_v_j) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); /* "fatiando/gravmag/_prism.pyx":276 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":277 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":278 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":279 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":280 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":281 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelz(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":282 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":283 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelz(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":284 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":273 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":260 * @cython.wraparound(False) * @cython.boundscheck(False) * def gz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gz", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":288 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_15gxx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_14gxx[] = "gxx(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_15gxx = {__Pyx_NAMESTR("gxx"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_15gxx, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_14gxx)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_15gxx(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gxx (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gxx") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gxx", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gxx", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_14gxx(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_14gxx(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gxx", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":297 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":298 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":299 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":300 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":301 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":302 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_i) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_j) lastprivate(__pyx_v_r) lastprivate(__pyx_v_k) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_kernel) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":304 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":305 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":306 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":307 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":308 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":309 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxx(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":310 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelxx(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":311 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxx(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelxx(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":312 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxx(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":301 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":288 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gxx", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":316 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_17gxy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_16gxy[] = "gxy(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_17gxy = {__Pyx_NAMESTR("gxy"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_17gxy, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_16gxy)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_17gxy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gxy (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gxy") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gxy", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gxy", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_16gxy(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_16gxy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp1; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp2; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; int __pyx_t_23; int __pyx_t_24; int __pyx_t_25; int __pyx_t_26; unsigned int __pyx_t_27; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gxy", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":325 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":326 * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":327 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":328 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":329 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":330 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_26, __pyx_t_18, __pyx_t_23, __pyx_t_25, __pyx_t_20, __pyx_t_27, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_24, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_j) lastprivate(__pyx_v_tmp1) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_i) lastprivate(__pyx_v_dx) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_tmp2) lastprivate(__pyx_v_k) lastprivate(__pyx_v_r) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_tmp1 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_tmp2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":332 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":333 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":334 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":335 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":336 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * if dx == 0 and dy == 0 and dz < 0: */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":337 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * if dx == 0 and dy == 0 and dz < 0: * tmp1 = 0.00001*(x2 - x1) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":338 * for i in range(2): * dx = x[i] - xp[l] * if dx == 0 and dy == 0 and dz < 0: # <<<<<<<<<<<<<< * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(y2 - y1) */ __pyx_t_23 = ((__pyx_v_dx == 0.0) != 0); if (__pyx_t_23) { __pyx_t_24 = ((__pyx_v_dy == 0.0) != 0); if (__pyx_t_24) { __pyx_t_25 = ((__pyx_v_dz < 0.0) != 0); __pyx_t_26 = __pyx_t_25; } else { __pyx_t_26 = __pyx_t_24; } __pyx_t_24 = __pyx_t_26; } else { __pyx_t_24 = __pyx_t_23; } if (__pyx_t_24) { /* "fatiando/gravmag/_prism.pyx":339 * dx = x[i] - xp[l] * if dx == 0 and dy == 0 and dz < 0: * tmp1 = 0.00001*(x2 - x1) # <<<<<<<<<<<<<< * tmp2 = 0.00001*(y2 - y1) * r = sqrt(tmp1**2 + tmp2**2 + dz**2) */ __pyx_v_tmp1 = (0.00001 * (__pyx_v_x2 - __pyx_v_x1)); /* "fatiando/gravmag/_prism.pyx":340 * if dx == 0 and dy == 0 and dz < 0: * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(y2 - y1) # <<<<<<<<<<<<<< * r = sqrt(tmp1**2 + tmp2**2 + dz**2) * else: */ __pyx_v_tmp2 = (0.00001 * (__pyx_v_y2 - __pyx_v_y1)); /* "fatiando/gravmag/_prism.pyx":341 * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(y2 - y1) * r = sqrt(tmp1**2 + tmp2**2 + dz**2) # <<<<<<<<<<<<<< * else: * r = sqrt(dx**2 + dy**2 + dz**2) */ __pyx_v_r = sqrt(((pow(__pyx_v_tmp1, 2.0) + pow(__pyx_v_tmp2, 2.0)) + pow(__pyx_v_dz, 2.0))); goto __pyx_L16; } /*else*/ { /* "fatiando/gravmag/_prism.pyx":343 * r = sqrt(tmp1**2 + tmp2**2 + dz**2) * else: * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelxy(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); } __pyx_L16:; /* "fatiando/gravmag/_prism.pyx":344 * else: * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxy(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelxy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":345 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxy(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_27 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":329 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":316 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gxy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":349 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_19gxz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_18gxz[] = "gxz(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_19gxz = {__Pyx_NAMESTR("gxz"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_19gxz, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_18gxz)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_19gxz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gxz (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gxz") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gxz", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gxz", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_18gxz(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_18gxz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp1; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp2; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; int __pyx_t_23; int __pyx_t_24; int __pyx_t_25; int __pyx_t_26; unsigned int __pyx_t_27; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gxz", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":358 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":359 * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":360 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":361 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":362 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":363 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_26, __pyx_t_18, __pyx_t_23, __pyx_t_25, __pyx_t_20, __pyx_t_27, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_24, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_i) lastprivate(__pyx_v_r) lastprivate(__pyx_v_tmp1) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_k) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_dx) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_tmp2) lastprivate(__pyx_v_j) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_tmp1 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_tmp2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_j = ((unsigned int)0xbad0bad0); /* "fatiando/gravmag/_prism.pyx":365 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":366 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":367 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":368 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":369 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * if dx == 0 and dz == 0 and dy < 0: */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":370 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * if dx == 0 and dz == 0 and dy < 0: * tmp1 = 0.00001*(x2 - x1) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":371 * for i in range(2): * dx = x[i] - xp[l] * if dx == 0 and dz == 0 and dy < 0: # <<<<<<<<<<<<<< * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(z2 - z1) */ __pyx_t_23 = ((__pyx_v_dx == 0.0) != 0); if (__pyx_t_23) { __pyx_t_24 = ((__pyx_v_dz == 0.0) != 0); if (__pyx_t_24) { __pyx_t_25 = ((__pyx_v_dy < 0.0) != 0); __pyx_t_26 = __pyx_t_25; } else { __pyx_t_26 = __pyx_t_24; } __pyx_t_24 = __pyx_t_26; } else { __pyx_t_24 = __pyx_t_23; } if (__pyx_t_24) { /* "fatiando/gravmag/_prism.pyx":372 * dx = x[i] - xp[l] * if dx == 0 and dz == 0 and dy < 0: * tmp1 = 0.00001*(x2 - x1) # <<<<<<<<<<<<<< * tmp2 = 0.00001*(z2 - z1) * r = sqrt(tmp1**2 + tmp2**2 + dy**2) */ __pyx_v_tmp1 = (0.00001 * (__pyx_v_x2 - __pyx_v_x1)); /* "fatiando/gravmag/_prism.pyx":373 * if dx == 0 and dz == 0 and dy < 0: * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(z2 - z1) # <<<<<<<<<<<<<< * r = sqrt(tmp1**2 + tmp2**2 + dy**2) * else: */ __pyx_v_tmp2 = (0.00001 * (__pyx_v_z2 - __pyx_v_z1)); /* "fatiando/gravmag/_prism.pyx":374 * tmp1 = 0.00001*(x2 - x1) * tmp2 = 0.00001*(z2 - z1) * r = sqrt(tmp1**2 + tmp2**2 + dy**2) # <<<<<<<<<<<<<< * else: * r = sqrt(dx**2 + dy**2 + dz**2) */ __pyx_v_r = sqrt(((pow(__pyx_v_tmp1, 2.0) + pow(__pyx_v_tmp2, 2.0)) + pow(__pyx_v_dy, 2.0))); goto __pyx_L16; } /*else*/ { /* "fatiando/gravmag/_prism.pyx":376 * r = sqrt(tmp1**2 + tmp2**2 + dy**2) * else: * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelxz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); } __pyx_L16:; /* "fatiando/gravmag/_prism.pyx":377 * else: * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxz(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelxz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":378 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelxz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_27 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":362 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":349 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gxz", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":382 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_21gyy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_20gyy[] = "gyy(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_21gyy = {__Pyx_NAMESTR("gyy"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_21gyy, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_20gyy)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_21gyy(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gyy (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gyy") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gyy", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gyy", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_20gyy(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_20gyy(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gyy", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":391 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":392 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":393 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":394 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":395 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":396 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_dy) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_i) lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_k) lastprivate(__pyx_v_j) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_dz) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":398 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":399 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":400 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":401 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":402 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":403 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelyy(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":404 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelyy(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":405 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelyy(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelyy(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":406 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelyy(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":395 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":382 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gyy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":410 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_23gyz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_22gyz[] = "gyz(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_23gyz = {__Pyx_NAMESTR("gyz"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_23gyz, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_22gyz)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_23gyz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gyz (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gyz") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gyz", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gyz", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 412; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_22gyz(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_22gyz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp1; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_tmp2; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; int __pyx_t_23; int __pyx_t_24; int __pyx_t_25; int __pyx_t_26; unsigned int __pyx_t_27; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gyz", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":419 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 419; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":420 * cdef DTYPE_T kernel, r, dx, dy, dz, tmp1, tmp2 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":421 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":422 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":423 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":424 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_26, __pyx_t_18, __pyx_t_23, __pyx_t_25, __pyx_t_20, __pyx_t_27, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_24, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_tmp1) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_i) lastprivate(__pyx_v_r) lastprivate(__pyx_v_tmp2) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_k) lastprivate(__pyx_v_j) lastprivate(__pyx_v_kernel) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_tmp1 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_tmp2 = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":426 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":427 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":428 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":429 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":430 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * if dy == 0 and dz == 0 and dx < 0: */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":431 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * if dy == 0 and dz == 0 and dx < 0: * tmp1 = 0.00001*(y2 - y1) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":432 * for i in range(2): * dx = x[i] - xp[l] * if dy == 0 and dz == 0 and dx < 0: # <<<<<<<<<<<<<< * tmp1 = 0.00001*(y2 - y1) * tmp2 = 0.00001*(z2 - z1) */ __pyx_t_23 = ((__pyx_v_dy == 0.0) != 0); if (__pyx_t_23) { __pyx_t_24 = ((__pyx_v_dz == 0.0) != 0); if (__pyx_t_24) { __pyx_t_25 = ((__pyx_v_dx < 0.0) != 0); __pyx_t_26 = __pyx_t_25; } else { __pyx_t_26 = __pyx_t_24; } __pyx_t_24 = __pyx_t_26; } else { __pyx_t_24 = __pyx_t_23; } if (__pyx_t_24) { /* "fatiando/gravmag/_prism.pyx":433 * dx = x[i] - xp[l] * if dy == 0 and dz == 0 and dx < 0: * tmp1 = 0.00001*(y2 - y1) # <<<<<<<<<<<<<< * tmp2 = 0.00001*(z2 - z1) * r = sqrt(tmp1**2 + tmp2**2 + dx**2) */ __pyx_v_tmp1 = (0.00001 * (__pyx_v_y2 - __pyx_v_y1)); /* "fatiando/gravmag/_prism.pyx":434 * if dy == 0 and dz == 0 and dx < 0: * tmp1 = 0.00001*(y2 - y1) * tmp2 = 0.00001*(z2 - z1) # <<<<<<<<<<<<<< * r = sqrt(tmp1**2 + tmp2**2 + dx**2) * else: */ __pyx_v_tmp2 = (0.00001 * (__pyx_v_z2 - __pyx_v_z1)); /* "fatiando/gravmag/_prism.pyx":435 * tmp1 = 0.00001*(y2 - y1) * tmp2 = 0.00001*(z2 - z1) * r = sqrt(tmp1**2 + tmp2**2 + dx**2) # <<<<<<<<<<<<<< * else: * r = sqrt(dx**2 + dy**2 + dz**2) */ __pyx_v_r = sqrt(((pow(__pyx_v_tmp1, 2.0) + pow(__pyx_v_tmp2, 2.0)) + pow(__pyx_v_dx, 2.0))); goto __pyx_L16; } /*else*/ { /* "fatiando/gravmag/_prism.pyx":437 * r = sqrt(tmp1**2 + tmp2**2 + dx**2) * else: * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelyz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); } __pyx_L16:; /* "fatiando/gravmag/_prism.pyx":438 * else: * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelyz(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelyz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":439 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelyz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_27 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":423 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":410 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gyz", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":443 * @cython.wraparound(False) * @cython.boundscheck(False) * def gzz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_25gzz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_24gzz[] = "gzz(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_25gzz = {__Pyx_NAMESTR("gzz"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_25gzz, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_24gzz)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_25gzz(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("gzz (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gzz") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("gzz", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.gzz", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_24gzz(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_24gzz(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("gzz", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":452 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":453 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":454 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":455 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":456 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":457 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_k) lastprivate(__pyx_v_j) lastprivate(__pyx_v_dz) lastprivate(__pyx_v_i) lastprivate(__pyx_v_dy) lastprivate(__pyx_v_dx) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); /* "fatiando/gravmag/_prism.pyx":459 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":460 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":461 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":462 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":463 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":464 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelzz(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":465 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelzz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":466 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelzz(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density * */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelzz(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":467 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelzz(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< * * @cython.wraparound(False) */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":456 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":443 * @cython.wraparound(False) * @cython.boundscheck(False) * def gzz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.gzz", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "fatiando/gravmag/_prism.pyx":471 * @cython.wraparound(False) * @cython.boundscheck(False) * def potential(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* Python wrapper */ static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_27potential(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_8fatiando_7gravmag_6_prism_26potential[] = "potential(ndarray xp, ndarray yp, ndarray zp, double x1, double x2, double y1, double y2, double z1, double z2, double density, ndarray res)"; static PyMethodDef __pyx_mdef_8fatiando_7gravmag_6_prism_27potential = {__Pyx_NAMESTR("potential"), (PyCFunction)__pyx_pw_8fatiando_7gravmag_6_prism_27potential, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_8fatiando_7gravmag_6_prism_26potential)}; static PyObject *__pyx_pw_8fatiando_7gravmag_6_prism_27potential(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_xp = 0; PyArrayObject *__pyx_v_yp = 0; PyArrayObject *__pyx_v_zp = 0; double __pyx_v_x1; double __pyx_v_x2; double __pyx_v_y1; double __pyx_v_y2; double __pyx_v_z1; double __pyx_v_z2; double __pyx_v_density; PyArrayObject *__pyx_v_res = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("potential (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xp,&__pyx_n_s_yp,&__pyx_n_s_zp,&__pyx_n_s_x1,&__pyx_n_s_x2,&__pyx_n_s_y1,&__pyx_n_s_y2,&__pyx_n_s_z1,&__pyx_n_s_z2,&__pyx_n_s_density,&__pyx_n_s_res,0}; PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xp)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_yp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_zp)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z1)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z2)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_density)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_res)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "potential") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } __pyx_v_xp = ((PyArrayObject *)values[0]); __pyx_v_yp = ((PyArrayObject *)values[1]); __pyx_v_zp = ((PyArrayObject *)values[2]); __pyx_v_x1 = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_x1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x2 = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_x2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y1 = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_y1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y2 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_y2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z1 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_z1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z2 = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_z2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_density = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_res = ((PyArrayObject *)values[10]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("potential", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("fatiando.gravmag._prism.potential", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_xp), __pyx_ptype_5numpy_ndarray, 0, "xp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_yp), __pyx_ptype_5numpy_ndarray, 0, "yp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_zp), __pyx_ptype_5numpy_ndarray, 0, "zp", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 0, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_8fatiando_7gravmag_6_prism_26potential(__pyx_self, __pyx_v_xp, __pyx_v_yp, __pyx_v_zp, __pyx_v_x1, __pyx_v_x2, __pyx_v_y1, __pyx_v_y2, __pyx_v_z1, __pyx_v_z2, __pyx_v_density, __pyx_v_res); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8fatiando_7gravmag_6_prism_26potential(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_xp, PyArrayObject *__pyx_v_yp, PyArrayObject *__pyx_v_zp, double __pyx_v_x1, double __pyx_v_x2, double __pyx_v_y1, double __pyx_v_y2, double __pyx_v_z1, double __pyx_v_z2, double __pyx_v_density, PyArrayObject *__pyx_v_res) { unsigned int __pyx_v_l; CYTHON_UNUSED unsigned int __pyx_v_size; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_kernel; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_r; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dx; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dy; __pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T __pyx_v_dz; __Pyx_LocalBuf_ND __pyx_pybuffernd_res; __Pyx_Buffer __pyx_pybuffer_res; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_xp; __Pyx_Buffer __pyx_pybuffer_xp; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_yp; __Pyx_Buffer __pyx_pybuffer_yp; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_zp; __Pyx_Buffer __pyx_pybuffer_zp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; unsigned int __pyx_t_11; unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; unsigned int __pyx_t_15; unsigned int __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; unsigned int __pyx_t_19; unsigned int __pyx_t_20; unsigned int __pyx_t_21; unsigned int __pyx_t_22; unsigned int __pyx_t_23; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("potential", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_xp.pybuffer.buf = NULL; __pyx_pybuffer_xp.refcount = 0; __pyx_pybuffernd_xp.data = NULL; __pyx_pybuffernd_xp.rcbuffer = &__pyx_pybuffer_xp; __pyx_pybuffer_yp.pybuffer.buf = NULL; __pyx_pybuffer_yp.refcount = 0; __pyx_pybuffernd_yp.data = NULL; __pyx_pybuffernd_yp.rcbuffer = &__pyx_pybuffer_yp; __pyx_pybuffer_zp.pybuffer.buf = NULL; __pyx_pybuffer_zp.refcount = 0; __pyx_pybuffernd_zp.data = NULL; __pyx_pybuffernd_zp.rcbuffer = &__pyx_pybuffer_zp; __pyx_pybuffer_res.pybuffer.buf = NULL; __pyx_pybuffer_res.refcount = 0; __pyx_pybuffernd_res.data = NULL; __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_xp.rcbuffer->pybuffer, (PyObject*)__pyx_v_xp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_xp.diminfo[0].strides = __pyx_pybuffernd_xp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_xp.diminfo[0].shape = __pyx_pybuffernd_xp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_yp.rcbuffer->pybuffer, (PyObject*)__pyx_v_yp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_yp.diminfo[0].strides = __pyx_pybuffernd_yp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_yp.diminfo[0].shape = __pyx_pybuffernd_yp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_zp.rcbuffer->pybuffer, (PyObject*)__pyx_v_zp, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_zp.diminfo[0].strides = __pyx_pybuffernd_zp.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_zp.diminfo[0].shape = __pyx_pybuffernd_zp.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; /* "fatiando/gravmag/_prism.pyx":480 * cdef numpy.ndarray[DTYPE_T, ndim=1] x, y, z * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) # <<<<<<<<<<<<<< * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_xp)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_size = __pyx_t_1; /* "fatiando/gravmag/_prism.pyx":481 * cdef DTYPE_T kernel, r, dx, dy, dz * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) # <<<<<<<<<<<<<< * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_x1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 481; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_x = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":482 * size = len(xp) * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) # <<<<<<<<<<<<<< * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_y1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_y = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":483 * x = numpy.array([x2, x1], dtype=DTYPE) * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) # <<<<<<<<<<<<<< * with nogil: * for l in prange(size): */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyFloat_FromDouble(__pyx_v_z2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyFloat_FromDouble(__pyx_v_z1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyList_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_nn___pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_z = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":484 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "fatiando/gravmag/_prism.pyx":485 * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: * for l in prange(size): # <<<<<<<<<<<<<< * # Evaluate the integration limits * for k in range(2): */ __pyx_t_11 = __pyx_v_size; 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_13 = (__pyx_t_11 - 0) / 1; if (__pyx_t_13 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_18, __pyx_t_20, __pyx_t_17, __pyx_t_16, __pyx_t_21, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_15) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_dz) lastprivate(__pyx_v_dy) firstprivate(__pyx_v_l) lastprivate(__pyx_v_l) lastprivate(__pyx_v_i) lastprivate(__pyx_v_r) lastprivate(__pyx_v_kernel) lastprivate(__pyx_v_dx) lastprivate(__pyx_v_k) lastprivate(__pyx_v_j) #endif /* _OPENMP */ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_13; __pyx_t_12++){ { __pyx_v_l = 0 + 1 * __pyx_t_12; /* Initialize private variables to invalid values */ __pyx_v_dz = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dy = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_i = ((unsigned int)0xbad0bad0); __pyx_v_r = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_kernel = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_dx = ((__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T)__PYX_NAN()); __pyx_v_k = ((unsigned int)0xbad0bad0); __pyx_v_j = ((unsigned int)0xbad0bad0); /* "fatiando/gravmag/_prism.pyx":487 * for l in prange(size): * # Evaluate the integration limits * for k in range(2): # <<<<<<<<<<<<<< * dz = z[k] - zp[l] * for j in range(2): */ for (__pyx_t_14 = 0; __pyx_t_14 < 2; __pyx_t_14+=1) { __pyx_v_k = __pyx_t_14; /* "fatiando/gravmag/_prism.pyx":488 * # Evaluate the integration limits * for k in range(2): * dz = z[k] - zp[l] # <<<<<<<<<<<<<< * for j in range(2): * dy = y[j] - yp[l] */ __pyx_t_15 = __pyx_v_k; __pyx_t_16 = __pyx_v_l; __pyx_v_dz = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_z.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_zp.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_zp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":489 * for k in range(2): * dz = z[k] - zp[l] * for j in range(2): # <<<<<<<<<<<<<< * dy = y[j] - yp[l] * for i in range(2): */ for (__pyx_t_17 = 0; __pyx_t_17 < 2; __pyx_t_17+=1) { __pyx_v_j = __pyx_t_17; /* "fatiando/gravmag/_prism.pyx":490 * dz = z[k] - zp[l] * for j in range(2): * dy = y[j] - yp[l] # <<<<<<<<<<<<<< * for i in range(2): * dx = x[i] - xp[l] */ __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_l; __pyx_v_dy = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_yp.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_yp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":491 * for j in range(2): * dy = y[j] - yp[l] * for i in range(2): # <<<<<<<<<<<<<< * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) */ for (__pyx_t_20 = 0; __pyx_t_20 < 2; __pyx_t_20+=1) { __pyx_v_i = __pyx_t_20; /* "fatiando/gravmag/_prism.pyx":492 * dy = y[j] - yp[l] * for i in range(2): * dx = x[i] - xp[l] # <<<<<<<<<<<<<< * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelpot(dx, dy, dz, r) */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_l; __pyx_v_dx = ((*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_x.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_xp.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_xp.diminfo[0].strides))); /* "fatiando/gravmag/_prism.pyx":493 * for i in range(2): * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) # <<<<<<<<<<<<<< * kernel = kernelpot(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_r = sqrt(((pow(__pyx_v_dx, 2.0) + pow(__pyx_v_dy, 2.0)) + pow(__pyx_v_dz, 2.0))); /* "fatiando/gravmag/_prism.pyx":494 * dx = x[i] - xp[l] * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelpot(dx, dy, dz, r) # <<<<<<<<<<<<<< * res[l] += ((-1.)**(i + j + k))*kernel*density */ __pyx_v_kernel = __pyx_f_8fatiando_7gravmag_6_prism_kernelpot(__pyx_v_dx, __pyx_v_dy, __pyx_v_dz, __pyx_v_r); /* "fatiando/gravmag/_prism.pyx":495 * r = sqrt(dx**2 + dy**2 + dz**2) * kernel = kernelpot(dx, dy, dz, r) * res[l] += ((-1.)**(i + j + k))*kernel*density # <<<<<<<<<<<<<< */ __pyx_t_23 = __pyx_v_l; *__Pyx_BufPtrStrided1d(__pyx_t_8fatiando_7gravmag_6_prism_DTYPE_T *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_res.diminfo[0].strides) += ((pow(-1., ((double)((__pyx_v_i + __pyx_v_j) + __pyx_v_k))) * __pyx_v_kernel) * __pyx_v_density); } } } } } } } } #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 } /* "fatiando/gravmag/_prism.pyx":484 * y = numpy.array([y2, y1], dtype=DTYPE) * z = numpy.array([z2, z1], dtype=DTYPE) * with nogil: # <<<<<<<<<<<<<< * for l in prange(size): * # Evaluate the integration limits */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "fatiando/gravmag/_prism.pyx":471 * @cython.wraparound(False) * @cython.boundscheck(False) * def potential(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("fatiando.gravmag._prism.potential", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_xp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_yp.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_zp.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_x); __Pyx_XDECREF((PyObject *)__pyx_v_y); __Pyx_XDECREF((PyObject *)__pyx_v_z); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 * # 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; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 * # 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 * * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 * 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 * 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 * 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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; goto __pyx_L4; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ __pyx_v_copy_shape = 0; } __pyx_L4:; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 * 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_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * * 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_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * 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_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * 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_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * * 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_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * 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_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * 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_2 = (__pyx_v_copy_shape != 0); if (__pyx_t_2) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * # 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))); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 * # 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * 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_5 = __pyx_v_ndim; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * 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]); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } goto __pyx_L7; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * 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_L7:; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * 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)); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef list stack */ __pyx_v_f = NULL; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_4); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); __pyx_t_4 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * 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) { __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; goto __pyx_L10; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L10:; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * 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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_5 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_5; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * 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_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * 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_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; } __pyx_t_1 = __pyx_t_7; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * 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_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ switch (__pyx_v_t) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ case NPY_BYTE: __pyx_v_f = __pyx_k_b; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = __pyx_k_B; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = __pyx_k_h; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = __pyx_k_H; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = __pyx_k_i; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = __pyx_k_I; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = __pyx_k_l; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = __pyx_k_L; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = __pyx_k_q; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = __pyx_k_Q; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = __pyx_k_f; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = __pyx_k_d; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k_g; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = __pyx_k_Zf; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = __pyx_k_Zd; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k_Zg; break; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = __pyx_k_O; break; default: /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} break; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * 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]) = '^'; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * 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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * 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'; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 * # 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_4); __Pyx_XDECREF(__pyx_t_8); __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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 * 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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * * 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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); goto __pyx_L3; } __pyx_L3:; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * 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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); goto __pyx_L4; } __pyx_L4:; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 * 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(); } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * 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; int __pyx_t_8; int __pyx_t_9; long __pyx_t_10; char *__pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-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_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-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_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-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_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-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_6 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_6) { __pyx_t_7 = (__pyx_v_little_endian != 0); } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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_6 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_6) { __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; } __pyx_t_6 = __pyx_t_9; } else { __pyx_t_6 = __pyx_t_7; } if (__pyx_t_6) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-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_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "/home/leo/bin/anaconda/lib/python2.7/site-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]) = 120; /* "/home/leo/bin/anaconda/lib/python2.7/site-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); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); /* "/home/leo/bin/anaconda/lib/python2.7/site-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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-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: */ __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; /* "/home/leo/bin/anaconda/lib/python2.7/site-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); goto __pyx_L9; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-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 * */ __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-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; /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * 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; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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); /* "/home/leo/bin/anaconda/lib/python2.7/site-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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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; goto __pyx_L3; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-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) */ Py_INCREF(__pyx_v_base); /* "/home/leo/bin/anaconda/lib/python2.7/site-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:; /* "/home/leo/bin/anaconda/lib/python2.7/site-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); /* "/home/leo/bin/anaconda/lib/python2.7/site-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; /* "/home/leo/bin/anaconda/lib/python2.7/site-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(); } /* "/home/leo/bin/anaconda/lib/python2.7/site-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); /* "/home/leo/bin/anaconda/lib/python2.7/site-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) { /* "/home/leo/bin/anaconda/lib/python2.7/site-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; } /*else*/ { /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "/home/leo/bin/anaconda/lib/python2.7/site-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; } 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 __Pyx_NAMESTR("_prism"), __Pyx_DOCSTR(__pyx_k_Cython_implementation_of_the_gr), /* 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_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_kp_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_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_array, __pyx_k_array, sizeof(__pyx_k_array), 0, 0, 1, 1}, {&__pyx_n_s_bx, __pyx_k_bx, sizeof(__pyx_k_bx), 0, 0, 1, 1}, {&__pyx_n_s_by, __pyx_k_by, sizeof(__pyx_k_by), 0, 0, 1, 1}, {&__pyx_n_s_bz, __pyx_k_bz, sizeof(__pyx_k_bz), 0, 0, 1, 1}, {&__pyx_n_s_density, __pyx_k_density, sizeof(__pyx_k_density), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_dx, __pyx_k_dx, sizeof(__pyx_k_dx), 0, 0, 1, 1}, {&__pyx_n_s_dy, __pyx_k_dy, sizeof(__pyx_k_dy), 0, 0, 1, 1}, {&__pyx_n_s_dz, __pyx_k_dz, sizeof(__pyx_k_dz), 0, 0, 1, 1}, {&__pyx_n_s_fatiando_gravmag__prism, __pyx_k_fatiando_gravmag__prism, sizeof(__pyx_k_fatiando_gravmag__prism), 0, 0, 1, 1}, {&__pyx_n_s_float, __pyx_k_float, sizeof(__pyx_k_float), 0, 0, 1, 1}, {&__pyx_n_s_fx, __pyx_k_fx, sizeof(__pyx_k_fx), 0, 0, 1, 1}, {&__pyx_n_s_fy, __pyx_k_fy, sizeof(__pyx_k_fy), 0, 0, 1, 1}, {&__pyx_n_s_fz, __pyx_k_fz, sizeof(__pyx_k_fz), 0, 0, 1, 1}, {&__pyx_n_s_gx, __pyx_k_gx, sizeof(__pyx_k_gx), 0, 0, 1, 1}, {&__pyx_n_s_gxx, __pyx_k_gxx, sizeof(__pyx_k_gxx), 0, 0, 1, 1}, {&__pyx_n_s_gxy, __pyx_k_gxy, sizeof(__pyx_k_gxy), 0, 0, 1, 1}, {&__pyx_n_s_gxz, __pyx_k_gxz, sizeof(__pyx_k_gxz), 0, 0, 1, 1}, {&__pyx_n_s_gy, __pyx_k_gy, sizeof(__pyx_k_gy), 0, 0, 1, 1}, {&__pyx_n_s_gyy, __pyx_k_gyy, sizeof(__pyx_k_gyy), 0, 0, 1, 1}, {&__pyx_n_s_gyz, __pyx_k_gyz, sizeof(__pyx_k_gyz), 0, 0, 1, 1}, {&__pyx_n_s_gz, __pyx_k_gz, sizeof(__pyx_k_gz), 0, 0, 1, 1}, {&__pyx_n_s_gzz, __pyx_k_gzz, sizeof(__pyx_k_gzz), 0, 0, 1, 1}, {&__pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_k_home_leo_src_fatiando_fatiando, sizeof(__pyx_k_home_leo_src_fatiando_fatiando), 0, 0, 1, 0}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, {&__pyx_n_s_kernel, __pyx_k_kernel, sizeof(__pyx_k_kernel), 0, 0, 1, 1}, {&__pyx_n_s_l, __pyx_k_l, sizeof(__pyx_k_l), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mx, __pyx_k_mx, sizeof(__pyx_k_mx), 0, 0, 1, 1}, {&__pyx_n_s_my, __pyx_k_my, sizeof(__pyx_k_my), 0, 0, 1, 1}, {&__pyx_n_s_mz, __pyx_k_mz, sizeof(__pyx_k_mz), 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_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_n_s_potential, __pyx_k_potential, sizeof(__pyx_k_potential), 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_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, {&__pyx_n_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_res, __pyx_k_res, sizeof(__pyx_k_res), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_tf, __pyx_k_tf, sizeof(__pyx_k_tf), 0, 0, 1, 1}, {&__pyx_n_s_tmp1, __pyx_k_tmp1, sizeof(__pyx_k_tmp1), 0, 0, 1, 1}, {&__pyx_n_s_tmp2, __pyx_k_tmp2, sizeof(__pyx_k_tmp2), 0, 0, 1, 1}, {&__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_v1, __pyx_k_v1, sizeof(__pyx_k_v1), 0, 0, 1, 1}, {&__pyx_n_s_v2, __pyx_k_v2, sizeof(__pyx_k_v2), 0, 0, 1, 1}, {&__pyx_n_s_v3, __pyx_k_v3, sizeof(__pyx_k_v3), 0, 0, 1, 1}, {&__pyx_n_s_v4, __pyx_k_v4, sizeof(__pyx_k_v4), 0, 0, 1, 1}, {&__pyx_n_s_v5, __pyx_k_v5, sizeof(__pyx_k_v5), 0, 0, 1, 1}, {&__pyx_n_s_v6, __pyx_k_v6, sizeof(__pyx_k_v6), 0, 0, 1, 1}, {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, {&__pyx_n_s_x1, __pyx_k_x1, sizeof(__pyx_k_x1), 0, 0, 1, 1}, {&__pyx_n_s_x2, __pyx_k_x2, sizeof(__pyx_k_x2), 0, 0, 1, 1}, {&__pyx_n_s_xp, __pyx_k_xp, sizeof(__pyx_k_xp), 0, 0, 1, 1}, {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, {&__pyx_n_s_y1, __pyx_k_y1, sizeof(__pyx_k_y1), 0, 0, 1, 1}, {&__pyx_n_s_y2, __pyx_k_y2, sizeof(__pyx_k_y2), 0, 0, 1, 1}, {&__pyx_n_s_yp, __pyx_k_yp, sizeof(__pyx_k_yp), 0, 0, 1, 1}, {&__pyx_n_s_z, __pyx_k_z, sizeof(__pyx_k_z), 0, 0, 1, 1}, {&__pyx_n_s_z1, __pyx_k_z1, sizeof(__pyx_k_z1), 0, 0, 1, 1}, {&__pyx_n_s_z2, __pyx_k_z2, sizeof(__pyx_k_z2), 0, 0, 1, 1}, {&__pyx_n_s_zp, __pyx_k_zp, sizeof(__pyx_k_zp), 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_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * 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_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * 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__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "/home/leo/bin/anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "/home/leo/bin/anaconda/lib/python2.7/site-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__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "/home/leo/bin/anaconda/lib/python2.7/site-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__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "/home/leo/bin/anaconda/lib/python2.7/site-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__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "fatiando/gravmag/_prism.pyx":74 * @cython.wraparound(False) * @cython.boundscheck(False) * def tf(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__7 = PyTuple_Pack(38, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_mx, __pyx_n_s_my, __pyx_n_s_mz, __pyx_n_s_fx, __pyx_n_s_fy, __pyx_n_s_fz, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_v1, __pyx_n_s_v2, __pyx_n_s_v3, __pyx_n_s_v4, __pyx_n_s_v5, __pyx_n_s_v6, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_bz, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); __pyx_codeobj__8 = (PyObject*)__Pyx_PyCode_New(16, 0, 38, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__7, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_tf, 74, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":111 * @cython.wraparound(False) * @cython.boundscheck(False) * def bx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__9 = PyTuple_Pack(29, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_mx, __pyx_n_s_my, __pyx_n_s_mz, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_v1, __pyx_n_s_v2, __pyx_n_s_v3, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); __pyx_codeobj__10 = (PyObject*)__Pyx_PyCode_New(13, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__9, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_bx, 111, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":142 * @cython.wraparound(False) * @cython.boundscheck(False) * def by(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__11 = PyTuple_Pack(29, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_mx, __pyx_n_s_my, __pyx_n_s_mz, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_v2, __pyx_n_s_v4, __pyx_n_s_v5, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); __pyx_codeobj__12 = (PyObject*)__Pyx_PyCode_New(13, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__11, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_by, 142, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":173 * @cython.wraparound(False) * @cython.boundscheck(False) * def bz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__13 = PyTuple_Pack(29, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_mx, __pyx_n_s_my, __pyx_n_s_mz, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_v3, __pyx_n_s_v5, __pyx_n_s_v6, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(13, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_bz, 173, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":204 * @cython.wraparound(False) * @cython.boundscheck(False) * def gx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__15 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gx, 204, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":232 * @cython.wraparound(False) * @cython.boundscheck(False) * def gy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__17 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__17); __Pyx_GIVEREF(__pyx_tuple__17); __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gy, 232, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":260 * @cython.wraparound(False) * @cython.boundscheck(False) * def gz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__19 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gz, 260, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":288 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__21 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__21); __Pyx_GIVEREF(__pyx_tuple__21); __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gxx, 288, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":316 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__23 = PyTuple_Pack(26, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz, __pyx_n_s_tmp1, __pyx_n_s_tmp2); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__23); __Pyx_GIVEREF(__pyx_tuple__23); __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(11, 0, 26, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__23, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gxy, 316, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":349 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__25 = PyTuple_Pack(26, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz, __pyx_n_s_tmp1, __pyx_n_s_tmp2); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(11, 0, 26, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gxz, 349, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":382 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__27 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__27); __Pyx_GIVEREF(__pyx_tuple__27); __pyx_codeobj__28 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__27, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gyy, 382, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":410 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__29 = PyTuple_Pack(26, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz, __pyx_n_s_tmp1, __pyx_n_s_tmp2); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__29); __Pyx_GIVEREF(__pyx_tuple__29); __pyx_codeobj__30 = (PyObject*)__Pyx_PyCode_New(11, 0, 26, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__29, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gyz, 410, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":443 * @cython.wraparound(False) * @cython.boundscheck(False) * def gzz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__31 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__31); __Pyx_GIVEREF(__pyx_tuple__31); __pyx_codeobj__32 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__31, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_gzz, 443, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "fatiando/gravmag/_prism.pyx":471 * @cython.wraparound(False) * @cython.boundscheck(False) * def potential(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_tuple__33 = PyTuple_Pack(24, __pyx_n_s_xp, __pyx_n_s_yp, __pyx_n_s_zp, __pyx_n_s_x1, __pyx_n_s_x2, __pyx_n_s_y1, __pyx_n_s_y2, __pyx_n_s_z1, __pyx_n_s_z2, __pyx_n_s_density, __pyx_n_s_res, __pyx_n_s_l, __pyx_n_s_size, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_kernel, __pyx_n_s_r, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_dz); if (unlikely(!__pyx_tuple__33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__33); __Pyx_GIVEREF(__pyx_tuple__33); __pyx_codeobj__34 = (PyObject*)__Pyx_PyCode_New(11, 0, 24, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__33, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_leo_src_fatiando_fatiando, __pyx_n_s_potential, 471, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_prism(void); /*proto*/ PyMODINIT_FUNC init_prism(void) #else PyMODINIT_FUNC PyInit__prism(void); /*proto*/ PyMODINIT_FUNC PyInit__prism(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__prism(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_prism"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_Cython_implementation_of_the_gr), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif if (__pyx_module_is_main_fatiando__gravmag___prism) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!PyDict_GetItemString(modules, "fatiando.gravmag._prism")) { if (unlikely(PyDict_SetItemString(modules, "fatiando.gravmag._prism", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "fatiando/gravmag/_prism.pyx":6 * prisms. * """ * import numpy # <<<<<<<<<<<<<< * * from libc.math cimport log, atan2, sqrt */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_numpy, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "fatiando/gravmag/_prism.pyx":15 * from cython.parallel cimport prange, parallel * * DTYPE = numpy.float # <<<<<<<<<<<<<< * ctypedef numpy.float_t DTYPE_T * */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":74 * @cython.wraparound(False) * @cython.boundscheck(False) * def tf(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_1tf, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_tf, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":111 * @cython.wraparound(False) * @cython.boundscheck(False) * def bx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_3bx, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_bx, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":142 * @cython.wraparound(False) * @cython.boundscheck(False) * def by(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_5by, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_by, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":173 * @cython.wraparound(False) * @cython.boundscheck(False) * def bz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_7bz, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_bz, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":204 * @cython.wraparound(False) * @cython.boundscheck(False) * def gx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_9gx, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gx, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":232 * @cython.wraparound(False) * @cython.boundscheck(False) * def gy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_11gy, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gy, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":260 * @cython.wraparound(False) * @cython.boundscheck(False) * def gz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_13gz, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gz, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":288 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxx(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_15gxx, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gxx, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":316 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_17gxy, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gxy, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":349 * @cython.wraparound(False) * @cython.boundscheck(False) * def gxz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_19gxz, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gxz, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":382 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyy(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_21gyy, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gyy, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":410 * @cython.wraparound(False) * @cython.boundscheck(False) * def gyz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_23gyz, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gyz, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":443 * @cython.wraparound(False) * @cython.boundscheck(False) * def gzz(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_25gzz, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_gzz, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":471 * @cython.wraparound(False) * @cython.boundscheck(False) * def potential(numpy.ndarray[DTYPE_T, ndim=1] xp not None, # <<<<<<<<<<<<<< * numpy.ndarray[DTYPE_T, ndim=1] yp not None, * numpy.ndarray[DTYPE_T, ndim=1] zp not None, */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8fatiando_7gravmag_6_prism_27potential, NULL, __pyx_n_s_fatiando_gravmag__prism); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_potential, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "fatiando/gravmag/_prism.pyx":1 * #cython: embedsignature=True # <<<<<<<<<<<<<< * """ * Cython implementation of the gravity and magnetic fields of right rectangular */ __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "/home/leo/bin/anaconda/lib/python2.7/site-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 */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { __Pyx_AddTraceback("init fatiando.gravmag._prism", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init fatiando.gravmag._prism"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* Runtime support code */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* CYTHON_REFNANNY */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) /* First char was not a digit */ 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; /* Consume from buffer string */ while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; /* breaks both loops as ctx->enc_count == 0 */ } 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; /* empty struct */ 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; /* not a 'break' in the loop */ } 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 10: case 13: ++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': /* substruct */ { 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; /* Erase processed last struct element */ 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 '}': /* end of substruct; either repeat or move on */ { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; /* Erase processed last struct element */ 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; } /* fall through */ 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 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; } else { if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; } ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if CYTHON_COMPILING_IN_CPYTHON result = PyDict_GetItem(__pyx_d, name); if (result) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } #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 PY_VERSION_HEX >= 0x02060000 if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; #endif result = (*call)(func, arg, kw); #if PY_VERSION_HEX >= 0x02060000 Py_LeaveRecursiveCall(); #endif if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } static void __Pyx_RaiseBufferFallbackError(void) { PyErr_SetString(PyExc_ValueError, "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_Restore(type, value, tb); #endif } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(type, value, tb); #endif } #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } #if PY_VERSION_HEX < 0x02050000 if (PyClass_Check(type)) { #else if (PyType_Check(type)) { #endif #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; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); } else { type = 0; PyErr_SetString(PyExc_TypeError, "raise: exception must be an old-style class or instance"); goto raise_error; } #else 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; } #endif } __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { if (PyObject_IsSubclass(instance_class, type)) { type = instance_class; } else { instance_class = NULL; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { 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); } } bad: Py_XDECREF(owned_instance); return; } #endif static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); #if PY_VERSION_HEX < 0x02060000 if (obj->ob_type->tp_dict) { PyObject *getbuffer_cobj = PyObject_GetItem( obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); if (getbuffer_cobj) { getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); Py_DECREF(getbuffer_cobj); if (!func) goto fail; return func(obj, view, flags); } else { PyErr_Clear(); } } #endif PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); #if PY_VERSION_HEX < 0x02060000 fail: #endif return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } #if PY_VERSION_HEX < 0x02060000 if (obj->ob_type->tp_dict) { PyObject *releasebuffer_cobj = PyObject_GetItem( obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); if (releasebuffer_cobj) { releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); Py_DECREF(releasebuffer_cobj); if (!func) goto fail; func(obj, view); return; } else { PyErr_Clear(); } } #endif goto nofail; #if PY_VERSION_HEX < 0x02060000 fail: #endif PyErr_WriteUnraisable(obj); nofail: Py_DECREF(obj); view->obj = NULL; } #endif /* PY_MAJOR_VERSION < 3 */ 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_VERSION_HEX >= 0x02050000 { #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; /* try absolute import on failure */ } #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 } } #else if (level>0) { PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); goto bad; } module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, NULL); #endif bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ { \ func_type value = func(x); \ if (sizeof(target_type) < sizeof(func_type)) { \ if (unlikely(value != (func_type) (target_type) value)) { \ func_type zero = 0; \ PyErr_SetString(PyExc_OverflowError, \ (is_unsigned && unlikely(value < zero)) ? \ "can't convert negative value to " #target_type : \ "value too large to convert to " #target_type); \ return (target_type) -1; \ } \ } \ return (target_type) value; \ } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { const unsigned int neg_one = (unsigned int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } return (unsigned int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (unsigned int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } if (sizeof(unsigned int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong) } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(unsigned int) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(unsigned int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (sizeof(unsigned int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong) } else if (sizeof(unsigned int) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned int val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned int) -1; } } else { unsigned int val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned int) -1; val = __Pyx_PyInt_As_unsigned_int(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(a, a); case 3: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, a); case 4: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_absf(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(a, a); case 3: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, a); case 4: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_abs(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(int) <= sizeof(unsigned long long)) { return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(long long)) { return PyLong_FromLongLong((long long) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) } else if (sizeof(int) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) } else if (sizeof(int) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(long) <= sizeof(unsigned long long)) { return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(long long)) { return PyLong_FromLongLong((long long) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) } else if (sizeof(long) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) } else if (sizeof(long) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } } 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); #if PY_VERSION_HEX < 0x02050000 return PyErr_Warn(NULL, message); #else return PyErr_WarnEx(NULL, message, 1); #endif } return 0; } #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); #if PY_VERSION_HEX < 0x02050000 if (PyErr_Warn(NULL, warning) < 0) goto bad; #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = (start + end) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ 0, /*int kwonlyargcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __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, /*int firstlineno,*/ __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; PyObject *py_globals = 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_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_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 /* Python 3+ has unicode identifiers */ 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(char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else /* PY_VERSION_HEX < 0x03030000 */ if (PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_DATA_SIZE(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ return PyUnicode_AsUTF8AndSize(o, length); #endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ #endif /* PY_VERSION_HEX < 0x03030000 */ } else #endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ #if !CYTHON_COMPILING_IN_PYPY #if PY_VERSION_HEX >= 0x02060000 if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) return PyInt_AS_LONG(b); #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(b)) { case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; case 0: return 0; case 1: return ((PyLongObject*)b)->ob_digit[0]; } #endif #endif #if PY_VERSION_HEX < 0x02060000 return PyInt_AsSsize_t(b); #else return PyLong_AsSsize_t(b); #endif } 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) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) return PyInt_FromLong((long)ival); else { unsigned char *bytes = (unsigned char *) &ival; int one = 1; int little = (int)*(unsigned char*)&one; return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); } #else return PyInt_FromSize_t(ival); #endif } #endif /* Py_PYTHON_H */
memdbg.h
/* ****** NOTE ****** * This header file should be the LAST header file included within every * .c file within the project. If there are .h files that have actual * code in them, then this header should be the last include within that * .h file, and that .h file should be the last one included within the * .c file. * ****** NOTE ***** */ #if !defined (__MEM_DBG_H_) #define __MEM_DBG_H_ // values to use within the MemDbg_Validate() function. #define MEMDBG_VALIDATE_MIN 0 #define MEMDBG_VALIDATE_DEEP 1 #define MEMDBG_VALIDATE_DEEPER 2 #define MEMDBG_VALIDATE_DEEPEST 3 #include <stdio.h> #include <stdlib.h> #include "os.h" #if (!AC_BUILT || HAVE_UNISTD_H) && !_MSC_VER #include <unistd.h> #endif #include <string.h> #include "memory.h" #if defined (MEMDBG_ON) /* * This software was written by Jim Fougeron jfoug AT cox dot net * in 2013. No copyright is claimed, and the software is hereby * placed in the public domain. In case this attempt to disclaim * copyright and place the software in the public domain is deemed * null and void, then the software is Copyright (c) 2013 Jim Fougeron * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ /* * memdbg.h * Memory management debugging (at runtime) * * memdbg contains routines detect, and report memory * problems, such as double frees, passing bad pointers to * free, most buffer overwrites. Also, tracking of non-freed * data, showing memory leaks, can also be shown. * * Compilation Options (provided from Makefile CFLAGS) * * MEMDBG_ON If this is NOT defined, then memdbg will * get out of your way, and most normal memory functions * will be called with no overhead at all. */ /* these functions can be called by client code. Normally Memdbg_Used() and * MemDbg_Display() would be called at program exit. That will dump a list * of any memory that was not released. The MemDbg_Validate() can be called * pretty much any time. That function will walk the memory allocation linked * lists, and sqwack if there are problems, such as overwrites, freed memory that * has been written to, etc. It would likely be good to call MemDbg_Validate() * within benchmarking, after every format is tested. * * TODO: Add a handle that can be passed to the MemDbg_Used() and MemDbg_Display() * and a function to get the 'current' state of memory as a handle. Thus, a * format self test could get a handle BEFORE starting, and then check after, and * ONLY show leaked memory from the time the handle was obtained, which was at the * start of the self test. Thus it would only show leaks from that format test. * * These functions are NOT thread safe. Do not call them within OMP blocks of code. * Normally, these would be called at program exit, or within things like format * self test code, etc, and not within OMP. But this warning is here, so that * it is known NOT to call within OMP. */ extern size_t MemDbg_Used(int show_freed); extern void MemDbg_Display(FILE *); extern void MemDbg_Validate(int level); extern void MemDbg_Validate_msg(int level, const char *pMsg); extern void MemDbg_Validate_msg2(int level, const char *pMsg, int bShowExData); /* these functions should almost NEVER be called by any client code. They * are listed here, because the macros need to know their names. Client code * should almost ALWAYS call malloc() like normal, vs calling MEMDBG_alloc() * If MEMDBG_alloc() was called, and MEMDBG_ON was not defined, then this * function would not be declared here, AND at link time, the function would * not be found. * NOTE, these functions should be thread safe in OMP builds (using #pragma omp atomic) * also note, memory allocation within OMP blocks SHOULD be avoided if possible. It is * very slow, and the thread safety required makes it even slow. This is not only talking * about these functions here, BUT malloc/free in general in OMP blocks. AVOID doing that * at almost all costs, and performance will usually go up. */ extern void *MEMDBG_alloc(size_t, char *, int); extern void *MEMDBG_alloc_align(size_t, int, char *, int); extern void *MEMDBG_calloc(size_t count, size_t, char *, int); extern void *MEMDBG_realloc(void *, size_t, char *, int); extern void MEMDBG_free(const void *, char *, int); extern char *MEMDBG_strdup(const char *, char *, int); #if !defined(__MEMDBG__) /* we get here on every file compiled EXCEPT memdbg.c */ #undef malloc #undef realloc #undef free #undef strdup #undef libc_free #undef libc_calloc #undef libc_malloc #define libc_free(a) MEMDBG_libc_free(a) #define libc_malloc(a) MEMDBG_libc_alloc(a) #define libc_calloc(a,b) MEMDBG_libc_calloc(a,b) #define malloc(a) MEMDBG_alloc((a),__FILE__,__LINE__) #define calloc(a,b) MEMDBG_calloc(a,b,__FILE__,__LINE__) #define realloc(a,b) MEMDBG_realloc((a),(b),__FILE__,__LINE__) #define free(a) MEMDBG_free((a),__FILE__,__LINE__) #define strdup(a) MEMDBG_strdup((a),__FILE__,__LINE__) #endif /* !defined __MEMDBG__ */ /* pass the file handle to write to (normally stderr) */ #define MEMDBG_PROGRAM_EXIT_CHECKS(a) do { \ if (MemDbg_Used(0) > 0 || getenv("MEMDBG")) MemDbg_Display(a); \ MemDbg_Validate_msg2(MEMDBG_VALIDATE_DEEPEST, "At Program Exit", 1); } while(0) typedef struct MEMDBG_HANDLE_t { unsigned id; unsigned alloc_cnt; size_t mem_size; } MEMDBG_HANDLE; /* * these functions give a caller some of the INSIDE information about the * allocated object. We simply return data from inside the memdbg header. * NOTE, if fence post is not valid, we still return something, BUT will * also return something in the err_msg stating this may not be valid. */ /* The count 'id' of an allocated block. Same as used in leak report */ unsigned MEMDBG_get_cnt (const void *ptr, const char **err_msg); /* the size allocated of the contained block */ size_t MEMDBG_get_size(const void *ptr, const char **err_msg); /* what file (source) did the allocation */ const char *MEMDBG_get_file(const void *ptr, const char **err_msg); /* what file (source) line number did the allocation */ unsigned MEMDBG_get_line(const void *ptr, const char **err_msg); /* * these functions allow taking a memory snapshot, calling some code, then validating that memory * is the same after the code. This will help catch memory leaks and other such problems, within * formats and such. Simply get the snapshot, run self tests (or other), when it exits, check * the snapshot to make sure nothing leaked. */ /* returning a struct (or passing as params it not super efficient but this is done so infrequently that this is not an issue. */ MEMDBG_HANDLE MEMDBG_getSnapshot(int id); /* will not exit on leaks. Does exit, on memory overwrite corruption. */ void MEMDBG_checkSnapshot(MEMDBG_HANDLE); /* same as MEMDBG_checkSnapshot() but if exit_on_any_leaks is true, will also exit if leaks found. */ void MEMDBG_checkSnapshot_possible_exit_on_error(MEMDBG_HANDLE, int exit_on_any_leaks); /* * the allocations from mem_alloc_tiny() must call this function to flag the memory they allocate * so it is not flagged as a leak, by these HANDLE snapshot functions. 'tiny' memory is expected * to leak, until program exit. At that time, any that was not freed, will be shown as leaked. * THIS function is also thread safe. The other checkSnapshot functions are NOT thread safe. */ void MEMDBG_tag_mem_from_alloc_tiny(void *); extern void MEMDBG_libc_free(void *); extern void *MEMDBG_libc_alloc(size_t size); extern void *MEMDBG_libc_calloc(size_t count, size_t size); #else #define libc_alloc alloc #define libc_calloc calloc #define libc_malloc malloc #define libc_free free #define MemDbg_Used(a) 0 #define MemDbg_Display(a) #define MemDbg_Validate(a) #define MemDbg_Validate_msg(a,b) #define MemDbg_Validate_msg2(a,b,c) #define MEMDBG_PROGRAM_EXIT_CHECKS(a) #define MEMDBG_tag_mem_from_alloc_tiny(a) #define MEMDBG_HANDLE int #define MEMDBG_getSnapshot(a) 0 #define MEMDBG_checkSnapshot(a) if(a) printf(" \b") #define MEMDBG_checkSnapshot_possible_exit_on_error(a, b) if(a) printf(" \b") #endif /* MEMDBG_ON */ #endif /* __MEMDBG_H_ */
DRB011-minusminus-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. */ /* The -- operation on numNodes2 is not protected, causing data race. Data race pair: numNodes2@74:7 vs. numNodes2@74:7 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int len=100; int numNodes=len, numNodes2=0; int x[100]; // initialize x[] #pragma omp parallel for for (i=0; i< len; i++) { if (i%2==0) x[i]=5; else x[i]= -5; } #pragma omp parallel for reduction(-:numNodes2) for (i=numNodes-1 ; i>-1 ; --i) { if (x[i]<=0) { numNodes2-- ; } } printf ("numNodes2 = %d\n", numNodes2); return 0; }
magsac.h
#pragma once #include <limits> #include <chrono> #include <memory> #include "model.h" #include "model_score.h" #include "sampler.h" #include "uniform_sampler.h" #include <math.h> #include "gamma_values.cpp" #include <iostream> #include "../experience/metrics.hpp" #ifdef _WIN32 #include <ppl.h> #endif template<class DatumType, class ModelEstimator> class MAGSAC { public: enum Version { // The original version of MAGSAC. It works well, however, can be quite slow in many cases. MAGSAC_ORIGINAL, // The recently proposed MAGSAC++ algorithm which keeps the accuracy of the original MAGSAC but is often orders of magnitude faster. MAGSAC_PLUS_PLUS }; MAGSAC(const Version magsac_version_ = Version::MAGSAC_PLUS_PLUS) : time_limit(std::numeric_limits<double>::max()), // desired_fps(-1), iteration_limit(std::numeric_limits<size_t>::max()), maximum_threshold(10.0), apply_post_processing(true), mininum_iteration_number(50), partition_number(5), core_number(1), number_of_irwls_iters(1), interrupting_threshold(1.0), last_iteration_number(0), log_confidence(0), point_number(0), magsac_version(magsac_version_) { } ~MAGSAC() {} // A function to run MAGSAC. bool run( const cv::Mat &points_, // The input data points const double confidence_, // The required confidence in the results ModelEstimator &estimator_, // The model estimator gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, // The sampler used gcransac::Model &obtained_model_, // The estimated model parameters int &iteration_number_, // The number of iterations done ModelScore &model_score_); // The score of the estimated model bool run( const cv::Mat &points_, const double confidence_, ModelEstimator &estimator_, gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, gcransac::Model &obtained_model_, int &iteration_number_, ModelScore &model_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved); // A function to set the maximum inlier-outlier threshold void setMaximumThreshold(const double maximum_threshold_) { maximum_threshold = maximum_threshold_; } // A function to set the inlier-outlier threshold used for speeding up the procedure // and for determining the required number of iterations. void setReferenceThreshold(const double threshold_) { interrupting_threshold = threshold_; } double getReferenceThreshold() { return interrupting_threshold; } // Setting the flag determining if post-processing is needed void applyPostProcessing(bool value_) { apply_post_processing = value_; } // A function to set the maximum number of iterations void setIterationLimit(size_t iteration_limit_) { iteration_limit = iteration_limit_; } // A function to set the minimum number of iterations void setMinimumIterationNumber(size_t mininum_iteration_number_) { mininum_iteration_number = mininum_iteration_number_; } // A function to set the number of cores used in the original MAGSAC algorithm. // In MAGSAC++, it is not used. Note that when multiple MAGSACs run in parallel, // it is beneficial to keep the core number one for each independent MAGSAC. // Otherwise, the threads will act weirdly. void setCoreNumber(size_t core_number_) { if (magsac_version == MAGSAC_PLUS_PLUS) fprintf(stderr, "Setting the core number for MAGSAC++ is deprecated."); core_number = core_number_; } // Setting the number of partitions used in the original MAGSAC algorithm // to speed up the procedure. In MAGSAC++, this parameter is not used. void setPartitionNumber(size_t partition_number_) { if (magsac_version == MAGSAC_PLUS_PLUS) fprintf(stderr, "Setting the partition number for MAGSAC++ is deprecated."); partition_number = partition_number_; } // A function to set a desired minimum frames-per-second (FPS) value. void setFPS(double fps_) { desired_fps = fps_; // The required FPS. // The time limit which the FPS implies time_limit = fps_ <= 0 ? std::numeric_limits<double>::max() : 1.0 / fps_; } // The post-processing algorithm applying sigma-consensus to the input model once. bool postProcessing( const cv::Mat &points, // All data points const gcransac::Model &so_far_the_best_model, // The input model to be improved gcransac::Model &output_model, // The improved model parameters ModelScore &output_score, // The score of the improved model const ModelEstimator &estimator); // The model estimator // The function determining the quality/score of a model using the original MAGSAC // criterion. Note that this function is significantly slower than the quality // function of MAGSAC++. void getModelQuality( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The input model const ModelEstimator &estimator_, // The model estimator double &marginalized_iteration_number_, // The required number of iterations marginalized over the noise scale double &score_); // The score/quality of the model // The function determining the quality/score of a // model using the MAGSAC++ criterion. void getModelQualityPlusPlus( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &score_, // The score to be calculated const double &previous_best_score_); // The score of the previous so-far-the-best model size_t number_of_irwls_iters; protected: Version magsac_version; // The version of MAGSAC used size_t iteration_limit; // Maximum number of iterations allowed size_t mininum_iteration_number; // Minimum number of iteration before terminating double maximum_threshold; // The maximum sigma value size_t core_number; // Number of core used in sigma-consensus double time_limit; // A time limit after the algorithm is interrupted double desired_fps; // The desired FPS (TODO: not tested with MAGSAC) bool apply_post_processing; // Decides if the post-processing step should be applied int point_number; // The current point number int last_iteration_number; // The iteration number implied by the last run of sigma-consensus double log_confidence; // The logarithm of the required confidence size_t partition_number; // Number of partitions used to speed up sigma-consensus double interrupting_threshold; // A threshold to speed up MAGSAC by interrupting the sigma-consensus procedure whenever there is no chance of being better than the previous so-far-the-best model bool sigmaConsensus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_); bool sigmaConsensus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved); bool sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_); bool sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved); }; template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::run( const cv::Mat &points_, const double confidence_, ModelEstimator &estimator_, gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, gcransac::Model &obtained_model_, int &iteration_number_, ModelScore &model_score_) { std::vector<size_t> inliersIdxsSaved; std::vector<double> weightsSaved; return run(points_, confidence_, estimator_, sampler_, obtained_model_, iteration_number_, model_score_, inliersIdxsSaved, weightsSaved); } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::run( const cv::Mat &points_, const double confidence_, ModelEstimator &estimator_, gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, gcransac::Model &obtained_model_, int &iteration_number_, ModelScore &model_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved) { // Initialize variables std::chrono::time_point<std::chrono::system_clock> start, end; // Variables for time measuring: start and end times std::chrono::duration<double> elapsed_seconds; // Variables for time measuring: elapsed time log_confidence = log(1.0 - confidence_); // The logarithm of 1 - confidence point_number = points_.rows; // Number of points const int sample_size = estimator_.sampleSize(); // The sample size required for the estimation size_t max_iteration = iteration_limit; // The maximum number of iterations initialized to the iteration limit int iteration = 0; // Current number of iterations gcransac::Model so_far_the_best_model; // Current best model ModelScore so_far_the_best_score; // The score of the current best model std::unique_ptr<size_t[]> minimal_sample(new size_t[sample_size]); // The sample used for the estimation std::vector<size_t> pool(points_.rows); for (size_t point_idx = 0; point_idx < point_number; ++point_idx) pool[point_idx] = point_idx; if (points_.rows < sample_size) { fprintf(stderr, "There are not enough points for applying robust estimation. Minimum is %d; while %d are given.\n", sample_size, points_.rows); return false; } // Set the start time variable if there is some time limit set if (desired_fps > -1) start = std::chrono::system_clock::now(); constexpr size_t max_unsuccessful_model_generations = 50; std::vector<size_t> inliersIdxsToSave; std::vector<double> weightsToSave; // Main MAGSAC iteration while (mininum_iteration_number > iteration || iteration < max_iteration) { // Increase the current iteration number ++iteration; // Sample a minimal subset std::vector<gcransac::Model> models; // The set of estimated models size_t unsuccessful_model_generations = 0; // The number of unsuccessful model generations // Try to select a minimal sample and estimate the implied model parameters while (++unsuccessful_model_generations < max_unsuccessful_model_generations) { // Get a minimal sample randomly if (!sampler_.sample(pool, // The index pool from which the minimal sample can be selected minimal_sample.get(), // The minimal sample sample_size)) // The size of a minimal sample continue; // Check if the selected sample is valid before estimating the model // parameters which usually takes more time. if (!estimator_.isValidSample(points_, // All points minimal_sample.get())) // The current sample continue; // Estimate the model from the minimal sample if (estimator_.estimateModel(points_, // All data points minimal_sample.get(), // The selected minimal sample &models)) // The estimated models break; } // If the method was not able to generate any usable models, break the cycle. iteration += unsuccessful_model_generations - 1; // Select the so-far-the-best from the estimated models for (const auto &model : models) { ModelScore score; // The score of the current model gcransac::Model refined_model; // The refined model parameters // Apply sigma-consensus to refine the model parameters by marginalizing over the noise level sigma bool success; if (magsac_version == Version::MAGSAC_ORIGINAL) success = sigmaConsensus(points_, model, refined_model, score, estimator_, so_far_the_best_score, inliersIdxsToSave, weightsToSave); else success = sigmaConsensusPlusPlus(points_, model, refined_model, score, estimator_, so_far_the_best_score, inliersIdxsToSave, weightsToSave); // Continue if the model was rejected if (!success || score.score == -1) continue; // Save the iteration number when the current model is found score.iteration = iteration; // Update the best model parameters if needed if (so_far_the_best_score < score) { so_far_the_best_model = refined_model; // Update the best model parameters so_far_the_best_score = score; // Update the best model's score max_iteration = MIN(max_iteration, last_iteration_number); // Update the max iteration number, but do not allow to increase inliersIdxsSaved = inliersIdxsToSave; weightsSaved = weightsToSave; } } // Update the time parameters if a time limit is set if (desired_fps > -1) { end = std::chrono::system_clock::now(); elapsed_seconds = end - start; // Interrupt if the time limit is exceeded if (elapsed_seconds.count() > time_limit) break; } } // Apply sigma-consensus as a post processing step if needed and the estimated model is valid if (apply_post_processing) { // TODO } obtained_model_ = so_far_the_best_model; iteration_number_ = iteration; model_score_ = so_far_the_best_score; return so_far_the_best_score.score > 0; } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::postProcessing( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &refined_score_, const ModelEstimator &estimator_) { fprintf(stderr, "Sigma-consensus++ is not implemented yet as post-processing.\n"); return false; } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_) { std::vector<size_t> inliersIdxsSaved; std::vector<double> weightsSaved; return sigmaConsensus(points_, model_, refined_model_, score_, estimator_, best_score_, inliersIdxsSaved, weightsSaved); } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved) { // Set up the parameters constexpr double L = 1.05; constexpr double k = ModelEstimator::getSigmaQuantile(); constexpr double threshold_to_sigma_multiplier = 1.0 / k; constexpr size_t sample_size = estimator_.sampleSize(); static auto comparator = [](std::pair<double, int> left, std::pair<double, int> right) { return left.first < right.first; }; const int point_number = points_.rows; double current_maximum_sigma = this->maximum_threshold; // Calculating the residuals std::vector<std::pair<double, size_t> > all_residuals; all_residuals.reserve(point_number); // If it is not the first run, consider the previous best and interrupt the validation when there is no chance of being better if (best_score_.inlier_number > 0) { // Number of inliers which should be exceeded int points_remaining = best_score_.inlier_number; // Collect the points which are closer than the threshold which the maximum sigma implies for (int point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index all_residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) --points_remaining; } // Interrupt if there is no chance of being better // TODO: replace this part by SPRT test if (point_number - point_idx < points_remaining) return false; } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = best_score_.inlier_number - points_remaining; } else { // The number of really close points size_t points_close = 0; // Collect the points which are closer than the threshold which the maximum sigma implies for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index all_residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; } std::vector<gcransac::Model> sigma_models; std::vector<size_t> sigma_inliers; std::vector<double> final_weights; // The number of possible inliers const size_t possible_inlier_number = all_residuals.size(); // Sort the residuals in ascending order std::sort(all_residuals.begin(), all_residuals.end(), comparator); // The maximum threshold is set to be slightly bigger than the distance of the // farthest possible inlier. current_maximum_sigma = all_residuals.back().first + std::numeric_limits<double>::epsilon(); const double sigma_step = current_maximum_sigma / partition_number; last_iteration_number = 10000; score_.score = 0; // The weights calculated by each parallel process std::vector<std::vector<double>> point_weights_par(partition_number, std::vector<double>(possible_inlier_number, 0)); // If OpenMP is used, calculate things in parallel #ifdef USE_OPENMP #pragma omp parallel for num_threads(core_number) for (int partition_idx = 0; partition_idx < partition_number; ++partition_idx) { // The maximum sigma value in the current partition const double max_sigma = (partition_idx + 1) * sigma_step; // Find the last element which has smaller distance than 'max_threshold' // Since the vector is ordered binary search can be used to find that particular element. const auto &last_element = std::upper_bound(all_residuals.begin(), all_residuals.end(), std::make_pair(max_sigma, 0), comparator); const size_t sigma_inlier_number = last_element - all_residuals.begin(); // Put the indices into a vector std::vector<size_t> sigma_inliers; sigma_inliers.reserve(sigma_inlier_number); // Store the points which are closer than the current sigma limit for (size_t relative_point_idx = 0; relative_point_idx < sigma_inlier_number; ++relative_point_idx) sigma_inliers.emplace_back(all_residuals[relative_point_idx].second); // Check if there are enough inliers to fit a model if (sigma_inliers.size() > sample_size) { // Estimating the model which the current set of inliers imply std::vector<gcransac::Model> sigma_models; estimator_.estimateModelNonminimal(points_, &(sigma_inliers)[0], sigma_inlier_number, &sigma_models); // If the estimation was successful calculate the implied probabilities if (sigma_models.size() == 1) { const double max_sigma_squared_2 = 2 * max_sigma * max_sigma; double residual_i_2, // The residual of the i-th point probability_i; // The probability of the i-th point // Iterate through all points to estimate the related probabilities for (size_t relative_point_idx = 0; relative_point_idx < sigma_inliers.size(); ++relative_point_idx) { // TODO: Replace with Chi-square instead of normal distribution const size_t &point_idx = sigma_inliers[relative_point_idx]; // Calculate the residual of the current point residual_i_2 = estimator_.squaredResidual(points_.row(point_idx), sigma_models[0]); // Calculate the probability of the i-th point assuming Gaussian distribution // TODO: replace by Chi-square distribution probability_i = exp(-residual_i_2 / max_sigma_squared_2); // Store the probability of the i-th point coming from the current partition point_weights_par[partition_idx][relative_point_idx] += probability_i; } std::vector<double> errors; computeModelError(sigma_inliers, points_, estimator_, sigma_models[0], errors); double errorMAX = 0; for (int i = 0; i < errors.size(); i++) { if (errors[i] > errorMAX) { errorMAX = errors[i]; } } } } } #else fprintf(stderr, "Not implemented yet.\n"); #endif // The weights used for the final weighted least-squares fitting final_weights.reserve(possible_inlier_number); // Collect all points which has higher probability of being inlier than zero sigma_inliers.reserve(possible_inlier_number); for (size_t point_idx = 0; point_idx < possible_inlier_number; ++point_idx) { // Calculate the weight of the current point double weight = 0.0; for (size_t partition_idx = 0; partition_idx < partition_number; ++partition_idx) weight += point_weights_par[partition_idx][point_idx]; // If the weight is approx. zero, continue. if (weight < std::numeric_limits<double>::epsilon()) continue; // Store the index and weight of the current point sigma_inliers.emplace_back(all_residuals[point_idx].second); final_weights.emplace_back(weight); } // If there are fewer inliers than the size of the minimal sample interupt the procedure if (sigma_inliers.size() < sample_size) return false; // Estimate the model parameters using weighted least-squares fitting if (!estimator_.estimateModelNonminimal( points_, // All input points &(sigma_inliers)[0], // Points which have higher than 0 probability of being inlier static_cast<int>(sigma_inliers.size()), // Number of possible inliers &sigma_models, // Estimated models &(final_weights)[0])) // Weights of points return false; bool is_model_updated = false; if (sigma_models.size() == 1 && // If only a single model is estimated estimator_.isValidModel(sigma_models.back(), points_, sigma_inliers, &(sigma_inliers)[0], interrupting_threshold, is_model_updated)) // and it is valid { // Return the refined model refined_model_ = sigma_models.back(); // Calculate the score of the model and the implied iteration number double marginalized_iteration_number; getModelQuality(points_, // All the input points refined_model_, // The estimated model estimator_, // The estimator marginalized_iteration_number, // The marginalized inlier ratio score_.score); // The marginalized score if (marginalized_iteration_number < 0 || std::isnan(marginalized_iteration_number)) last_iteration_number = std::numeric_limits<int>::max(); else last_iteration_number = static_cast<int>(round(marginalized_iteration_number)); std::vector<double> errors; computeModelError(sigma_inliers, points_, estimator_, refined_model_, errors); double errorMAX = 0; for (int i = 0; i < errors.size(); i++) { if (errors[i] > errorMAX) { errorMAX = errors[i]; } } inliersIdxsSaved = sigma_inliers; weightsSaved = final_weights; return true; } return false; } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_) { std::vector<size_t> inliersIdxsSaved; std::vector<double> weightsSaved; return sigmaConsensusPlusPlus(points_, model_, refined_model_, score_, estimator_, best_score_, inliersIdxsSaved, weightsSaved); } template<class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_, std::vector<size_t> &inliersIdxsSaved, std::vector<double> &weightsSaved) { // The degrees of freedom of the data from which the model is estimated. // E.g., for models coming from point correspondences (x1,y1,x2,y2), it is 4. constexpr size_t degrees_of_freedom = ModelEstimator::getDegreesOfFreedom(); // A 0.99 quantile of the Chi^2-distribution to convert sigma values to residuals constexpr double k = ModelEstimator::getSigmaQuantile(); // A multiplier to convert residual values to sigmas constexpr double threshold_to_sigma_multiplier = 1.0 / k; // Calculating k^2 / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double squared_k_per_2 = k * k / 2.0; // Calculating (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_minus_one_per_two = (degrees_of_freedom - 1.0) / 2.0; // TODO: check constexpr double C = ModelEstimator::getC(); // The size of a minimal sample used for the estimation constexpr size_t sample_size = estimator_.sampleSize(); // Calculating 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof = std::pow(2.0, dof_minus_one_per_two); // Calculating C * 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double C_times_two_ad_dof = C * two_ad_dof; // Calculating the gamma value of (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double gamma_value = tgamma(dof_minus_one_per_two); // Calculating the upper incomplete gamma value of (DoF - 1) / 2 with k^2 / 2. constexpr double gamma_k = ModelEstimator::getUpperIncompleteGammaOfK(); // Calculating the lower incomplete gamma value of (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double gamma_difference = gamma_value - gamma_k; // The number of points provided const int point_number = points_.rows; // The manually set maximum inlier-outlier threshold double current_maximum_sigma = this->maximum_threshold; // Calculating the pairs of (residual, point index). std::vector<std::pair<double, size_t> > residuals; // Occupy the maximum required memory to avoid doing it later. residuals.reserve(point_number); // If it is not the first run, consider the previous best and interrupt the validation when there is no chance of being better if (best_score_.inlier_number > 0) { // Number of points close to the previous so-far-the-best model. // This model should have more inliers. int points_remaining = best_score_.inlier_number; // Collect the points which are closer than the threshold which the maximum sigma implies for (int point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // all_residuals.emplace_back(std::make_pair(residual * threshold_to_sigma_multiplier, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) --points_remaining; } // Interrupt if there is no chance of being better // TODO: replace this part by SPRT test if (point_number - point_idx < points_remaining) return false; } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = best_score_.inlier_number - points_remaining; } else { // The number of really close points size_t points_close = 0; // Collect the points which are closer than the threshold which the maximum sigma implies for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; } // Models fit by weighted least-squares fitting std::vector<gcransac::Model> sigma_models; // Points used in the weighted least-squares fitting std::vector<size_t> sigma_inliers; // Weights used in the the weighted least-squares fitting std::vector<double> sigma_weights; // Number of points considered in the fitting const size_t possible_inlier_number = residuals.size(); // Occupy the memory to avoid doing it inside the calculation possibly multiple times sigma_inliers.reserve(possible_inlier_number); // Occupy the memory to avoid doing it inside the calculation possibly multiple times sigma_weights.reserve(possible_inlier_number); // Calculate 2 * \sigma_{max}^2 a priori const double squared_sigma_max_2 = current_maximum_sigma * current_maximum_sigma * 2.0; // Divide C * 2^(DoF - 1) by \sigma_{max} a priori const double one_over_sigma = C_times_two_ad_dof / current_maximum_sigma; // Calculate the weight of a point with 0 residual (i.e., fitting perfectly) a priori const double weight_zero = one_over_sigma * gamma_difference; // Initialize the polished model with the initial one gcransac::Model polished_model = model_; // A flag to determine if the initial model has been updated bool updated = false; // Do the iteratively re-weighted least squares fitting for (size_t iterations = 0; iterations < number_of_irwls_iters; ++iterations) { // If the current iteration is not the first, the set of possibly inliers // (i.e., points closer than the maximum threshold) have to be recalculated. if (iterations > 0) { // The number of points close to the model size_t points_close = 0; // Remove everything from the residual vector residuals.clear(); // Collect the points which are closer than the maximum threshold for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), polished_model); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; // Number of points closer than the threshold const size_t possible_inlier_number = residuals.size(); // Clear the inliers and weights sigma_inliers.clear(); sigma_weights.clear(); // Occupy the memory for the inliers and weights sigma_inliers.reserve(possible_inlier_number); sigma_weights.reserve(possible_inlier_number); } // Calculate the weight of each point for (const auto &[residual, idx] : residuals) { // The weight double weight = 0.0; // If the residual is ~0, the point fits perfectly and it is handled differently if (residual < std::numeric_limits<double>::epsilon()) weight = weight_zero; else { // Calculate the squared residual const double squared_residual = residual * residual; // Get the position of the gamma value in the lookup table size_t x = round(precision_of_stored_gammas * squared_residual / squared_sigma_max_2); // Put the index of the point into the vector of points used for the least squares fitting sigma_inliers.emplace_back(idx); // If the sought gamma value is not stored in the lookup, return the closest element if (stored_gamma_number < x) x = stored_gamma_number; // Calculate the weight of the point weight = one_over_sigma * (stored_gamma_values[x] - gamma_k); } // Store the weight of the point sigma_weights.emplace_back(weight); } // If there are fewer than the minimum point close to the model, // terminate. if (sigma_inliers.size() < sample_size) return false; // Estimate the model parameters using weighted least-squares fitting if (!estimator_.estimateModelNonminimal( points_, // All input points &(sigma_inliers)[0], // Points which have higher than 0 probability of being inlier static_cast<int>(sigma_inliers.size()), // Number of possible inliers &sigma_models, // Estimated models &(sigma_weights)[0])) // Weights of points { // If the estimation failed and the iteration was never successfull, // terminate with failure. if (iterations == 0) return false; // Otherwise, if the iteration was successfull at least one, // simply break it. break; } // Update the model parameters polished_model = sigma_models[0]; // Clear the vector of models and keep only the best sigma_models.clear(); // The model has been updated updated = true; } bool is_model_updated = false; if (updated && // If the model has been updated estimator_.isValidModel(polished_model, points_, sigma_inliers, &(sigma_inliers[0]), interrupting_threshold, is_model_updated)) // and it is valid { // Return the refined model refined_model_ = polished_model; // Calculate the score of the model and the implied iteration number double marginalized_iteration_number; getModelQualityPlusPlus(points_, // All the input points refined_model_, // The estimated model estimator_, // The estimator score_.score, // The marginalized score best_score_.score); // The score of the previous so-far-the-best model // Update the iteration number last_iteration_number = log_confidence / log(1.0 - std::pow(static_cast<double>(score_.inlier_number) / point_number, sample_size)); inliersIdxsSaved = sigma_inliers; weightsSaved = sigma_weights; return true; } return false; } template<class DatumType, class ModelEstimator> void MAGSAC<DatumType, ModelEstimator>::getModelQualityPlusPlus( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &score_, // The score to be calculated const double &previous_best_score_) // The score of the previous so-far-the-best model { // The degrees of freedom of the data from which the model is estimated. // E.g., for models coming from point correspondences (x1,y1,x2,y2), it is 4. constexpr size_t degrees_of_freedom = ModelEstimator::getDegreesOfFreedom(); // A 0.99 quantile of the Chi^2-distribution to convert sigma values to residuals constexpr double k = ModelEstimator::getSigmaQuantile(); // A multiplier to convert residual values to sigmas constexpr double threshold_to_sigma_multiplier = 1.0 / k; // Calculating k^2 / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double squared_k_per_2 = k * k / 2.0; // Calculating (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_minus_one_per_two = (degrees_of_freedom - 1.0) / 2.0; // Calculating (DoF + 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_plus_one_per_two = (degrees_of_freedom + 1.0) / 2.0; // TODO: check constexpr double C = 0.25; // Calculating 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof_minus_one = std::pow(2.0, dof_minus_one_per_two); // Calculating 2^(DoF + 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof_plus_one = std::pow(2.0, dof_plus_one_per_two); // Calculate the gamma value of k constexpr double gamma_value_of_k = ModelEstimator::getUpperIncompleteGammaOfK(); // Calculate the lower incomplete gamma value of k constexpr double lower_gamma_value_of_k = ModelEstimator::getLowerIncompleteGammaOfK(); // The number of points provided const int point_number = points_.rows; // The previous best loss const double previous_best_loss = 1.0 / previous_best_score_; // Convert the maximum threshold to a sigma value const double maximum_sigma = threshold_to_sigma_multiplier * maximum_threshold; // Calculate the squared maximum sigma const double maximum_sigma_2 = maximum_sigma * maximum_sigma; // Calculate \sigma_{max}^2 / 2 const double maximum_sigma_2_per_2 = maximum_sigma_2 / 2.0; // Calculate 2 * \sigma_{max}^2 const double maximum_sigma_2_times_2 = maximum_sigma_2 * 2.0; // Calculate the loss implied by an outlier const double outlier_loss = maximum_sigma * two_ad_dof_minus_one * lower_gamma_value_of_k; // Calculating 2^(DoF + 1) / \sigma_{max} which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. const double two_ad_dof_plus_one_per_maximum_sigma = two_ad_dof_plus_one / maximum_sigma; // The loss which a point implies double loss = 0.0, // The total loss regarding the current model total_loss = 0.0; // Iterate through all points to calculate the implied loss for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); // If the residual is smaller than the maximum threshold, consider it outlier // and add the loss implied to the total loss. if (maximum_threshold < residual) loss = outlier_loss; else // Otherwise, consider the point inlier, and calculate the implied loss { // Calculate the squared residual const double squared_residual = residual * residual; // Divide the residual by the 2 * \sigma^2 const double squared_residual_per_sigma = squared_residual / maximum_sigma_2_times_2; // Get the position of the gamma value in the lookup table size_t x = round(precision_of_stored_incomplete_gammas * squared_residual_per_sigma); // If the sought gamma value is not stored in the lookup, return the closest element if (stored_incomplete_gamma_number < x) x = stored_incomplete_gamma_number; // Calculate the loss implied by the current point loss = maximum_sigma_2_per_2 * stored_lower_incomplete_gamma_values[x] + squared_residual / 4.0 * (stored_complete_gamma_values[x] - gamma_value_of_k); loss = loss * two_ad_dof_plus_one_per_maximum_sigma; } // Update the total loss total_loss += loss; // Break the validation if there is no chance of being better than the previous // so-far-the-best model. if (previous_best_loss < total_loss) break; } // Calculate the score of the model from the total loss score_ = 1.0 / total_loss; } template<class DatumType, class ModelEstimator> void MAGSAC<DatumType, ModelEstimator>::getModelQuality( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &marginalized_iteration_number_, // The marginalized iteration number to be calculated double &score_) // The score to be calculated { // Set up the parameters constexpr size_t sample_size = estimator_.sampleSize(); const size_t point_number = points_.rows; // Getting the inliers std::vector<std::pair<double, size_t>> all_residuals; all_residuals.reserve(point_number); double max_distance = 0; for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); // If the residual is smaller than the maximum threshold, add it to the set of possible inliers if (maximum_threshold > residual) { max_distance = MAX(max_distance, residual); all_residuals.emplace_back(std::make_pair(residual, point_idx)); } } // Set the maximum distance to be slightly bigger than that of the farthest possible inlier max_distance = max_distance + std::numeric_limits<double>::epsilon(); // Number of possible inliers const size_t possible_inlier_number = all_residuals.size(); // The extent of a partition const double threshold_step = max_distance / partition_number; // The maximum threshold considered in each partition std::vector<double> thresholds(partition_number); std::vector<double> thresholds_squared(partition_number); std::vector<double> thresholds_2_squared(partition_number); // Calculating the thresholds for each partition for (size_t i = 0; i < partition_number; ++i) { thresholds[i] = (i + 1) * threshold_step; thresholds_squared[i] = thresholds[i] * thresholds[i]; thresholds_2_squared[i] = 2 * thresholds_squared[i]; } double residual_i, // Residual of the i-th point residual_i_squared, // Squared residual of the i-th poin probability_i; // Probability of the i-th point given the model std::vector<double> inliers(partition_number, 0), // RANSAC score for each partition probabilities(partition_number, 1); // Probabilities for each partition for (size_t point_idx = 0; point_idx < possible_inlier_number; ++point_idx) { residual_i = all_residuals[point_idx].first; residual_i_squared = residual_i * residual_i; for (size_t i = 0; i < partition_number; ++i) { if (residual_i < thresholds[i]) { probability_i = 1.0 - residual_i_squared / thresholds_squared[i]; ++inliers[i]; probabilities[i] += probability_i; } } } score_ = 0; marginalized_iteration_number_ = 0.0; for (auto i = 0; i < partition_number; ++i) { score_ += probabilities[i]; marginalized_iteration_number_ += log_confidence / log(1.0 - std::pow(inliers[i] / point_number, sample_size)); } marginalized_iteration_number_ = marginalized_iteration_number_ / partition_number; }
GB_binop__lor_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_08__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_02__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_04__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_int16) // A*D function (colscale): GB (_AxD__lor_int16) // D*A function (rowscale): GB (_DxB__lor_int16) // C+=B function (dense accum): GB (_Cdense_accumB__lor_int16) // C+=b function (dense accum): GB (_Cdense_accumb__lor_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_int16) // C=scalar+B GB (_bind1st__lor_int16) // C=scalar+B' GB (_bind1st_tran__lor_int16) // C=A+scalar GB (_bind2nd__lor_int16) // C=A'+scalar GB (_bind2nd_tran__lor_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) || (bij != 0)) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // 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) \ int16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ((x != 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_LOR || GxB_NO_INT16 || GxB_NO_LOR_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__lor_int16) ( 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__lor_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lor_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lor_int16) ( 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 int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lor_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lor_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_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__lor_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__lor_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__lor_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__lor_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lor_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = ((x != 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_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = ((aij != 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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) || (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lor_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) || (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lor_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ten_tusscher_2004_epi_S2_1.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S2_1.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } //TODO: this should be called only once for the whole mesh, like in the GPU code SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.7787928226268,0.00123339508649700,0.784831144233936,0.784673023102172,0.000169405106163081,0.487281523786458,0.00289654265697758,0.999998418745548,1.86681673058670e-08,1.83872100639159e-05,0.999777546403090,1.00731261455043,0.999997755681027,4.00467125306598e-05,0.953040239833913,9.39175391367938,139.965667493392}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; ///#ifdef EPI real Gks=0.245; ///#endif ///#ifdef ENDO /// real Gks=0.245; ///#endif ///#ifdef MCELL /// real Gks=0.062; ///#endif //Parameters for Ik1 real GK1=5.405; //Parameters for Ito //#ifdef EPI real Gto=0.294; //#endif // #ifdef ENDO // real Gto=0.073; //#endif //#ifdef MCELL // real Gto=0.294; ///#endif //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.7730247891532,0.000208550376791424,0.000166345602997405,0.000314427207496467,0.272150547490643,0.206045798160674,0.134878222351137,2.91860118931279,0.0222099400341836,2.12194476134155,1099.53480175178,0.000604923870766662,0.118384383617544,0.0193733747777405,0.00390066599158743,2.21704721596155e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; ///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; ///Ileak=0.00008f*(CaSR-Cai); Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; #ifdef EPI R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif #ifdef ENDO R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+28)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.; #endif #ifdef MCELL R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
senha-parallel.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <omp.h> // NOTES(ciroceissler): variaveis globas gerais static char finalcmd[300] = "unzip -P%d -t %s 2>&1"; static char filename[100]; static int chunk_size = 10000; //NOTES(ciroceissler) variavel global par ainformar que a senha foi encontrada int has_finish; FILE *popen(const char *command, const char *type); double rtclock() { struct timezone Tzp; struct timeval Tp; int stat; stat = gettimeofday (&Tp, &Tzp); if (stat != 0) printf("Error return from gettimeofday: %d",stat); return(Tp.tv_sec + Tp.tv_usec*1.0e-6); } // NOTES(ciroceissler): metodo para computar a senha a partir de uma valor inicial // (initial_i) ate o valor do chunk_size. void test_passwd(int initial_i) { FILE * fp; char ret[200]; char cmd[400]; unsigned int k; // NOTES(ciroceissler): percorre todo o chunk_size for (k = initial_i; !has_finish && k < initial_i + chunk_size; k++) { sprintf((char*)&cmd, finalcmd, k, filename); fp = popen(cmd, "r"); while (!feof(fp)) { fgets((char*)&ret, 200, fp); if (strcasestr(ret, "ok") != NULL) { printf("Senha:%d\n", k); // NOTES(ciroceissler): senha encontrada #pragma omp critical has_finish = 1; } } pclose(fp); } } int main () { int nt; double t_start, t_end; int i; scanf("%d", &nt); scanf("%s", filename); has_finish = 0; t_start = rtclock(); #pragma omp parallel num_threads(nt) private(i) shared(chunk_size, has_finish) // NOTES(ciroceissler): thread de controle, inicia as outras threads e tambem // processa o workload. #pragma omp master { for(i=0; !has_finish && i < 500000; i += nt*chunk_size) { for(unsigned int j = 0; j < nt; j++) { #pragma omp task shared(finalcmd, filename) { test_passwd(i + j*chunk_size); } } } } t_end = rtclock(); fprintf(stdout, "%0.6lf\n", t_end - t_start); } // // RESULTADOS: // // == tempo de execucao paralelo: // // arq1.in: // Senha:10000 // 0.006370 // // arq2.in: // Senha:100000 // 145.808934 // // arq3.in: // Senha:450000 // 530.587558 // // arq4.in: // Senha:310000 // 349.136113 // // arq5.in: // Senha:65000 // 50.764964 // // arq6.in: // Senha:245999 // 325.156417 // // == tempo de execucao serial: // // arq1.in: // Senha:10000 // 24.056035 // // arq2.in: // Senha:100000 // 240.915763 // // arq3,in: // Senha:450000 // 1079.184434 // // arq4.in: // Senha:310000 // 744.927912 // // arq5.in: // Senha:65000 // 155.354699 // // arq6.in: // Senha:245999 // 588.531458 // // taf!
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % John Cristy % % July 2009 % % % % % % Copyright 1999-2012 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/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *fourier) { double *roll; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ roll=(double *) AcquireQuantumMemory((size_t) height,width*sizeof(*roll)); if (roll == (double *) NULL) return(MagickFalse); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; roll[v*width+u]=fourier[i++]; } } (void) CopyMagickMemory(fourier,roll,height*width*sizeof(*roll)); roll=(double *) RelinquishMagickMemory(roll); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source,double *destination) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) floor((double) width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,source); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L-1L); x++) destination[width*y+x+width/2L]=source[center*y+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L-1L); x++) destination[width*(height-y)+width/2L-x-1L]=source[center*y+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) destination[-x+width/2L-1L]=destination[x+width/2L+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_source, *phase_source; Image *magnitude_image, *phase_image; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_source=(double *) AcquireQuantumMemory((size_t) fourier_info->height,fourier_info->width*sizeof(*magnitude_source)); if (magnitude_source == (double *) NULL) return(MagickFalse); (void) ResetMagickMemory(magnitude_source,0,fourier_info->height* fourier_info->width*sizeof(*magnitude_source)); phase_source=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->width*sizeof(*phase_source)); if (phase_source == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); magnitude_source=(double *) RelinquishMagickMemory(magnitude_source); return(MagickFalse); } status=ForwardQuadrantSwap(fourier_info->height,fourier_info->height, magnitude,magnitude_source); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->height,fourier_info->height,phase, phase_source); CorrectPhaseLHS(fourier_info->height,fourier_info->height,phase_source); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_source[i]/=(2.0*MagickPI); phase_source[i]+=0.5; i++; } } magnitude_view=AcquireCacheView(magnitude_image); phase_view=AcquireCacheView(phase_image); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->height,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange* magnitude_source[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->height,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange* phase_source[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange* phase_source[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange* phase_source[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange* phase_source[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* phase_source[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_source[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); magnitude_view=DestroyCacheView(magnitude_view); phase_source=(double *) RelinquishMagickMemory(phase_source); magnitude_source=(double *) RelinquishMagickMemory(magnitude_source); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *image_view; double n, *source; fftw_complex *fourier; fftw_plan fftw_r2c_plan; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->width*sizeof(*source)); if (source == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } ResetMagickMemory(source,0,fourier_info->height*fourier_info->width* sizeof(*source)); i=0L; image_view=AcquireCacheView(image); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); fourier=(fftw_complex *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->center*sizeof(*fourier)); if (fourier == (fftw_complex *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source=(double *) RelinquishMagickMemory(source); return(MagickFalse); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->width, source,fourier,FFTW_ESTIMATE); fftw_execute(fftw_r2c_plan); fftw_destroy_plan(fftw_r2c_plan); source=(double *) RelinquishMagickMemory(source); /* Normalize Fourier transform. */ n=(double) fourier_info->width*(double) fourier_info->width; i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier[i]/=n; #else fourier[i][0]/=n; fourier[i][1]/=n; #endif i++; } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude[i]=cabs(fourier[i]); phase[i]=carg(fourier[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude[i]=creal(fourier[i]); phase[i]=cimag(fourier[i]); i++; } fourier=(fftw_complex *) RelinquishMagickMemory(fourier); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude, *phase; fftw_complex *fourier; FourierInfo fourier_info; MagickBooleanType status; size_t extent; fourier_info.width=image->columns; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) floor((double) fourier_info.width/2.0)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude=(double *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*magnitude)); if (magnitude == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } phase=(double *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*phase)); if (phase == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); magnitude=(double *) RelinquishMagickMemory(magnitude); return(MagickFalse); } fourier=(fftw_complex *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*fourier)); if (fourier == (fftw_complex *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); phase=(double *) RelinquishMagickMemory(phase); magnitude=(double *) RelinquishMagickMemory(magnitude); return(MagickFalse); } status=ForwardFourierTransform(&fourier_info,image,magnitude,phase,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude,phase, exception); fourier=(fftw_complex *) RelinquishMagickMemory(fourier); phase=(double *) RelinquishMagickMemory(phase); magnitude=(double *) RelinquishMagickMemory(magnitude); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t extent, width; width=image->columns; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } magnitude_image=CloneImage(image,width,width,MagickFalse,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,width,MagickFalse,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) floor((double) width/2.0)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[center*(height-y)-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[center*y]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image,fftw_complex *fourier, ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude, *phase, *magnitude_source, *phase_source; MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_source=(double *) AcquireQuantumMemory((size_t) fourier_info->height,fourier_info->width*sizeof(*magnitude_source)); if (magnitude_source == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } phase_source=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->width*sizeof(*phase_source)); if (phase_source == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); magnitude_source=(double *) RelinquishMagickMemory(magnitude_source); return(MagickFalse); } i=0L; magnitude_view=AcquireCacheView(magnitude_image); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_source[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_source[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_source[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_source[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_source[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_source[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } i=0L; phase_view=AcquireCacheView(phase_image); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_source[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_source[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_source[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_source[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_source[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_source[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_source[i]-=0.5; phase_source[i]*=(2.0*MagickPI); i++; } } magnitude_view=DestroyCacheView(magnitude_view); phase_view=DestroyCacheView(phase_view); magnitude=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->center*sizeof(*magnitude)); if (magnitude == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); magnitude_source=(double *) RelinquishMagickMemory(magnitude_source); phase_source=(double *) RelinquishMagickMemory(phase_source); return(MagickFalse); } status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_source,magnitude); magnitude_source=(double *) RelinquishMagickMemory(magnitude_source); phase=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->width*sizeof(*phase)); if (phase == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); phase_source=(double *) RelinquishMagickMemory(phase_source); return(MagickFalse); } CorrectPhaseLHS(fourier_info->width,fourier_info->width,phase_source); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_source,phase); phase_source=(double *) RelinquishMagickMemory(phase_source); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier[i]=magnitude[i]*cos(phase[i])+I*magnitude[i]*sin(phase[i]); #else fourier[i][0]=magnitude[i]*cos(phase[i]); fourier[i][1]=magnitude[i]*sin(phase[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier[i]=magnitude[i]+I*phase[i]; #else fourier[i][0]=magnitude[i]; fourier[i][1]=phase[i]; #endif i++; } phase=(double *) RelinquishMagickMemory(phase); magnitude=(double *) RelinquishMagickMemory(magnitude); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source; fftw_plan fftw_c2r_plan; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source=(double *) AcquireQuantumMemory((size_t) fourier_info->height, fourier_info->width*sizeof(*source)); if (source == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif { fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier,source,FFTW_ESTIMATE); fftw_execute(fftw_c2r_plan); fftw_destroy_plan(fftw_c2r_plan); } i=0L; image_view=AcquireCacheView(image); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source=(double *) RelinquishMagickMemory(source); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude, *phase; fftw_complex *fourier; FourierInfo fourier_info; MagickBooleanType status; size_t extent; fourier_info.width=magnitude_image->columns; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) floor((double) fourier_info.width/2.0)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude=(double *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*magnitude)); if (magnitude == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } phase=(double *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*phase)); if (phase == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); magnitude=(double *) RelinquishMagickMemory(magnitude); return(MagickFalse); } fourier=(fftw_complex *) AcquireQuantumMemory((size_t) fourier_info.height, fourier_info.center*sizeof(*fourier)); if (fourier == (fftw_complex *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); phase=(double *) RelinquishMagickMemory(phase); magnitude=(double *) RelinquishMagickMemory(magnitude); return(MagickFalse); } status=InverseFourier(&fourier_info,magnitude_image,phase_image,fourier, exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,fourier,fourier_image, exception); fourier=(fftw_complex *) RelinquishMagickMemory(fourier); phase=(double *) RelinquishMagickMemory(phase); magnitude=(double *) RelinquishMagickMemory(magnitude); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickFalse,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red); Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red); gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+ snr); Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green); Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green); gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr); Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue); Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity* Bi->opacity+snr); Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity* Bi->opacity); Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity* Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red); Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green); Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5; Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity); Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red); Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red); Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green); Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green); Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue); Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity* Bi->opacity); Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity* Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize Fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image,RedChannel, modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse Fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source_pixels; const char *value; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
RandomGenerator.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign // Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign // Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign // Mark Dewing, markdewing@gmail.com, University of Illinois at Urbana-Champaign // // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign ////////////////////////////////////////////////////////////////////////////////////// /** @file RandomGenerator.h * @brief Declare a global Random Number Generator * * Selected among * - boost::random * - sprng * - math::random * qmcplusplus::Random() returns a random number [0,1) * For OpenMP is enabled, it is important to use thread-safe boost::random. Each * thread uses its own random number generator with a distinct seed. This prevents * a use of global lock which will slow down the applications significantly. */ #ifndef OHMMS_RANDOMGENERATOR #define OHMMS_RANDOMGENERATOR #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <cmath> #include <ctime> #include <stdint.h> struct BoxMuller2 { template<typename RNG> static inline void generate(RNG& rng, double* restrict a, int n) { for (int i = 0; i + 1 < n; i += 2) { double temp1 = 1.0 - 0.9999999999 * rng(), temp2 = rng(); a[i] = sqrt(-2.0 * log(temp1)) * cos(6.283185306 * temp2); a[i + 1] = sqrt(-2.0 * log(temp1)) * sin(6.283185306 * temp2); } if (n % 2 == 1) { double temp1 = 1 - 0.9999999999 * rng(), temp2 = rng(); a[n - 1] = sqrt(-2.0 * log(temp1)) * cos(6.283185306 * temp2); } } template<typename RNG> static inline void generate(RNG& rng, float* restrict a, int n) { for (int i = 0; i + 1 < n; i += 2) { float temp1 = 1.0f - 0.9999999999f * rng(), temp2 = rng(); a[i] = sqrtf(-2.0f * logf(temp1)) * cosf(6.283185306f * temp2); a[i + 1] = sqrtf(-2.0f * logf(temp1)) * sinf(6.283185306f * temp2); } if (n % 2 == 1) { float temp1 = 1.0f - 0.9999999999f * rng(), temp2 = rng(); a[n - 1] = sqrtf(-2.0f * logf(temp1)) * cosf(6.283185306f * temp2); } } }; inline uint32_t make_seed(int i, int n) { return static_cast<uint32_t>(std::time(0)) % 10474949 + (i + 1) * n + i; } // The definition of the fake RNG should always be available for unit testing #include "Utilities/FakeRandom.h" #ifdef USE_FAKE_RNG namespace qmcplusplus { typedef FakeRandom RandomGenerator_t; } // namespace qmcplusplus #else #ifdef HAVE_LIBBOOST #include "Utilities/BoostRandom.h" namespace qmcplusplus { template<class T> using RandomGenerator = BoostRandom<T>; typedef BoostRandom<OHMMS_PRECISION_FULL> RandomGenerator_t; } // namespace qmcplusplus #else #error -DHAVE_LIBBOOST is missing in the compile line. A cmake dependency fix is needed. #endif #endif namespace qmcplusplus { class RNGThreadSafe : public RandomGenerator_t { public: inline RandomGenerator_t::result_type rand() { result_type result; // This should be a named section but at least clang 9 doesn't seem to support // and warns of extra tokens. #pragma omp critical { result = RandomGenerator_t::rand(); } return result; } /** return a random number [0,1) */ inline RandomGenerator_t::result_type operator()() { result_type result; #pragma omp critical { result = RandomGenerator_t::rand(); } return result;} /** generate a series of random numbers */ template<typename T1> inline void generate_uniform(T1* restrict d, int n) { #pragma omp critical { for (int i = 0; i < n; ++i) d[i] = RandomGenerator_t::rand(); } } }; extern RNGThreadSafe Random; } #endif
camera.h
#pragma once #include "tracer.h" class Camera { private: Vec origin, dir, right, up; static double transform(double p, int n, int i, int j, double d) { // (i + j * p + p / 2 + d / 2) / n * 2 - 1 return (i * 2 + (j * 2 + 1) * p + d) / n - 1; } public: Camera(const Vec& origin, const Vec& direction, double aspect, double fov = PI / 4, const Vec& worldUp = Vec(0, 1, 0)) : origin(origin), dir(direction), right(glm::cross(dir, worldUp)), up(glm::cross(right, dir)) { double k = glm::tan(fov / 2); right *= k / glm::length(right) * aspect; up *= k / glm::length(up); } template <typename Device> void render(const Scene& scene, Device& device, const Option& opt) { int s1 = opt.ssaa; int s2 = num::pow<2>(s1); double inv_s1 = 1.0 / s1; int n = opt.spp / s2; int w = device.width(); int h = device.height(); fprintf(stderr, "Start rendering with width = %d, height = %d, spp = %d\n", w, h, n * s2); int m = opt.rounds; int tot = 0; #pragma omp parallel for schedule(dynamic, 1) for (int y = h - 1; y >= 0; --y) { Sampler samp(num::pow<2>((uint32_t) y)); RayTracer tracer(scene, samp, opt); for (int x = w - 1; x >= 0; --x) { Vec c(0); for (int k = s2 - 1; k >= 0; --k) { int i = 0; for (int j = 1; j <= m; ++j) { Vec sum(0); double i0 = i; // (i / n) < (j / m) for (; i * m < j * n; ++i) { double nx = transform(inv_s1, w, x, k % s1, samp.triangle()); double ny = transform(inv_s1, h, y, k / s1, samp.triangle()); sum += tracer.radiance(Ray(origin, glm::normalize(nx * right + ny * up + dir))); } c += glm::clamp(sum / (i - i0), 0.0, 1.0); } } device.set(x, h - y - 1, c * (1.0 / (m * s2))); #pragma omp atomic ++tot; fprintf(stderr, "\rRendered: %5.2f%%", 100.0 * tot / (w * h)); if (tot == w * h) { fputs("\n", stderr); } } } } static Camera load(const Env& t, double aspect) { auto v = env::accessor(Vec(0))(t); Vec o = v("origin"); Vec d = v("direction"); double fov = glm::radians(env::fetch(t["fov"], 45.0)); return Camera(o, d, aspect, fov); } };
parser.h
/* Data structures and function exported by the C++ Parser. Copyright (C) 2010-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_CP_PARSER_H #define GCC_CP_PARSER_H #include "tree.h" #include "cp/cp-tree.h" #include "c-family/c-pragma.h" /* A token's value and its associated deferred access checks and qualifying scope. */ struct GTY(()) tree_check { /* The value associated with the token. */ tree value; /* The checks that have been associated with value. */ vec<deferred_access_check, va_gc> *checks; /* The token's qualifying scope (used when it is a CPP_NESTED_NAME_SPECIFIER). */ tree qualifying_scope; }; /* A C++ token. */ struct GTY (()) cp_token { /* The kind of token. */ ENUM_BITFIELD (cpp_ttype) type : 8; /* If this token is a keyword, this value indicates which keyword. Otherwise, this value is RID_MAX. */ ENUM_BITFIELD (rid) keyword : 8; /* Token flags. */ unsigned char flags; /* True if this token is from a context where it is implicitly extern "C" */ BOOL_BITFIELD implicit_extern_c : 1; /* True if an error has already been reported for this token, such as a CPP_NAME token that is not a keyword (i.e., for which KEYWORD is RID_MAX) iff this name was looked up and found to be ambiguous. */ BOOL_BITFIELD error_reported : 1; /* True for a token that has been purged. If a token is purged, it is no longer a valid token and it should be considered deleted. */ BOOL_BITFIELD purged_p : 1; /* 5 unused bits. */ /* The location at which this token was found. */ location_t location; /* The value associated with this token, if any. */ union cp_token_value { /* Used for compound tokens such as CPP_NESTED_NAME_SPECIFIER. */ struct tree_check* GTY((tag ("1"))) tree_check_value; /* Use for all other tokens. */ tree GTY((tag ("0"))) value; } GTY((desc ("(%1.type == CPP_TEMPLATE_ID)" "|| (%1.type == CPP_NESTED_NAME_SPECIFIER)" "|| (%1.type == CPP_DECLTYPE)"))) u; }; /* We use a stack of token pointer for saving token sets. */ typedef struct cp_token *cp_token_position; /* The cp_lexer structure represents the C++ lexer. It is responsible for managing the token stream from the preprocessor and supplying it to the parser. Tokens are never added to the cp_lexer after it is created. */ struct GTY (()) cp_lexer { /* The memory allocated for the buffer. NULL if this lexer does not own the token buffer. */ vec<cp_token, va_gc> *buffer; /* A pointer just past the last available token. The tokens in this lexer are [buffer, last_token). */ cp_token_position GTY ((skip)) last_token; /* The next available token. If NEXT_TOKEN is &eof_token, then there are no more available tokens. */ cp_token_position GTY ((skip)) next_token; /* A stack indicating positions at which cp_lexer_save_tokens was called. The top entry is the most recent position at which we began saving tokens. If the stack is non-empty, we are saving tokens. */ vec<cp_token_position> GTY ((skip)) saved_tokens; /* The next lexer in a linked list of lexers. */ struct cp_lexer *next; /* True if we should output debugging information. */ bool debugging_p; /* True if we're in the context of parsing a pragma, and should not increment past the end-of-line marker. */ bool in_pragma; }; /* cp_token_cache is a range of tokens. There is no need to represent allocate heap memory for it, since tokens are never removed from the lexer's array. There is also no need for the GC to walk through a cp_token_cache, since everything in here is referenced through a lexer. */ struct GTY(()) cp_token_cache { /* The beginning of the token range. */ cp_token * GTY((skip)) first; /* Points immediately after the last token in the range. */ cp_token * GTY ((skip)) last; }; typedef cp_token_cache *cp_token_cache_ptr; struct cp_token_ident { unsigned int ident_len; const char *ident_str; unsigned int before_len; const char *before_str; unsigned int after_len; const char *after_str; }; /* An entry in a queue of function arguments that require post-processing. */ struct GTY(()) cp_default_arg_entry { /* The current_class_type when we parsed this arg. */ tree class_type; /* The function decl itself. */ tree decl; }; /* An entry in a stack for member functions defined within their classes. */ struct GTY(()) cp_unparsed_functions_entry { /* Functions with default arguments that require post-processing. Functions appear in this list in declaration order. */ vec<cp_default_arg_entry, va_gc> *funs_with_default_args; /* Functions with defintions that require post-processing. Functions appear in this list in declaration order. */ vec<tree, va_gc> *funs_with_definitions; /* Non-static data members with initializers that require post-processing. FIELD_DECLs appear in this list in declaration order. */ vec<tree, va_gc> *nsdmis; /* Nested classes go in this vector, so that we can do some final processing after parsing any NSDMIs. */ vec<tree, va_gc> *classes; }; /* The status of a tentative parse. */ enum cp_parser_status_kind { /* No errors have occurred. */ CP_PARSER_STATUS_KIND_NO_ERROR, /* An error has occurred. */ CP_PARSER_STATUS_KIND_ERROR, /* We are committed to this tentative parse, whether or not an error has occurred. */ CP_PARSER_STATUS_KIND_COMMITTED }; /* Context that is saved and restored when parsing tentatively. */ struct GTY (()) cp_parser_context { /* If this is a tentative parsing context, the status of the tentative parse. */ enum cp_parser_status_kind status; /* If non-NULL, we have just seen a `x->' or `x.' expression. Names that are looked up in this context must be looked up both in the scope given by OBJECT_TYPE (the type of `x' or `*x') and also in the context of the containing expression. */ tree object_type; /* The next parsing context in the stack. */ struct cp_parser_context *next; }; /* Helper data structure for parsing #pragma omp declare simd. */ struct cp_omp_declare_simd_data { bool error_seen; /* Set if error has been reported. */ bool fndecl_seen; /* Set if one fn decl/definition has been seen already. */ vec<cp_token_cache_ptr> tokens; tree clauses; }; /* Helper data structure for parsing #pragma acc routine. */ struct cp_oacc_routine_data : cp_omp_declare_simd_data { location_t loc; }; /* The cp_parser structure represents the C++ parser. */ struct GTY(()) cp_parser { /* The lexer from which we are obtaining tokens. */ cp_lexer *lexer; /* The scope in which names should be looked up. If NULL_TREE, then we look up names in the scope that is currently open in the source program. If non-NULL, this is either a TYPE or NAMESPACE_DECL for the scope in which we should look. It can also be ERROR_MARK, when we've parsed a bogus scope. This value is not cleared automatically after a name is looked up, so we must be careful to clear it before starting a new look up sequence. (If it is not cleared, then `X::Y' followed by `Z' will look up `Z' in the scope of `X', rather than the current scope.) Unfortunately, it is difficult to tell when name lookup is complete, because we sometimes peek at a token, look it up, and then decide not to consume it. */ tree scope; /* OBJECT_SCOPE and QUALIFYING_SCOPE give the scopes in which the last lookup took place. OBJECT_SCOPE is used if an expression like "x->y" or "x.y" was used; it gives the type of "*x" or "x", respectively. QUALIFYING_SCOPE is used for an expression of the form "X::Y"; it refers to X. */ tree object_scope; tree qualifying_scope; /* A stack of parsing contexts. All but the bottom entry on the stack will be tentative contexts. We parse tentatively in order to determine which construct is in use in some situations. For example, in order to determine whether a statement is an expression-statement or a declaration-statement we parse it tentatively as a declaration-statement. If that fails, we then reparse the same token stream as an expression-statement. */ cp_parser_context *context; /* True if we are parsing GNU C++. If this flag is not set, then GNU extensions are not recognized. */ bool allow_gnu_extensions_p; /* TRUE if the `>' token should be interpreted as the greater-than operator. FALSE if it is the end of a template-id or template-parameter-list. In C++0x mode, this flag also applies to `>>' tokens, which are viewed as two consecutive `>' tokens when this flag is FALSE. */ bool greater_than_is_operator_p; /* TRUE if default arguments are allowed within a parameter list that starts at this point. FALSE if only a gnu extension makes them permissible. */ bool default_arg_ok_p; /* TRUE if we are parsing an integral constant-expression. See [expr.const] for a precise definition. */ bool integral_constant_expression_p; /* TRUE if we are parsing an integral constant-expression -- but a non-constant expression should be permitted as well. This flag is used when parsing an array bound so that GNU variable-length arrays are tolerated. */ bool allow_non_integral_constant_expression_p; /* TRUE if ALLOW_NON_CONSTANT_EXPRESSION_P is TRUE and something has been seen that makes the expression non-constant. */ bool non_integral_constant_expression_p; /* TRUE if local variable names and `this' are forbidden in the current context. */ bool local_variables_forbidden_p; /* TRUE if the declaration we are parsing is part of a linkage-specification of the form `extern string-literal declaration'. */ bool in_unbraced_linkage_specification_p; /* TRUE if we are presently parsing a declarator, after the direct-declarator. */ bool in_declarator_p; /* TRUE if we are presently parsing a template-argument-list. */ bool in_template_argument_list_p; /* Set to IN_ITERATION_STMT if parsing an iteration-statement, to IN_OMP_BLOCK if parsing OpenMP structured block and IN_OMP_FOR if parsing OpenMP loop. If parsing a switch statement, this is bitwise ORed with IN_SWITCH_STMT, unless parsing an iteration-statement, OpenMP block or loop within that switch. */ #define IN_SWITCH_STMT 1 #define IN_ITERATION_STMT 2 #define IN_OMP_BLOCK 4 #define IN_OMP_FOR 8 #define IN_IF_STMT 16 unsigned char in_statement; /* TRUE if we are presently parsing the body of a switch statement. Note that this doesn't quite overlap with in_statement above. The difference relates to giving the right sets of error messages: "case not in switch" vs "break statement used with OpenMP...". */ bool in_switch_statement_p; /* TRUE if we are parsing a type-id in an expression context. In such a situation, both "type (expr)" and "type (type)" are valid alternatives. */ bool in_type_id_in_expr_p; /* TRUE if we are currently in a header file where declarations are implicitly extern "C". */ bool implicit_extern_c; /* TRUE if strings in expressions should be translated to the execution character set. */ bool translate_strings_p; /* TRUE if we are presently parsing the body of a function, but not a local class. */ bool in_function_body; /* Nonzero if we're processing a __transaction_atomic or __transaction_relaxed statement. */ unsigned char in_transaction; /* TRUE if we can auto-correct a colon to a scope operator. */ bool colon_corrects_to_scope_p; /* TRUE if : doesn't start a class definition. Should be only used together with type_definition_forbidden_message non-NULL, in contexts where new types may not be defined, and the type list is terminated by colon. */ bool colon_doesnt_start_class_def_p; /* If non-NULL, then we are parsing a construct where new type definitions are not permitted. The string stored here will be issued as an error message if a type is defined. */ const char *type_definition_forbidden_message; /* A stack used for member functions of local classes. The lists contained in an individual entry can only be processed once the outermost class being defined is complete. */ vec<cp_unparsed_functions_entry, va_gc> *unparsed_queues; /* The number of classes whose definitions are currently in progress. */ unsigned num_classes_being_defined; /* The number of template parameter lists that apply directly to the current declaration. */ unsigned num_template_parameter_lists; /* When parsing #pragma omp declare simd, this is a pointer to a helper data structure. */ cp_omp_declare_simd_data * GTY((skip)) omp_declare_simd; /* When parsing #pragma acc routine, this is a pointer to a helper data structure. */ cp_oacc_routine_data * GTY((skip)) oacc_routine; /* Nonzero if parsing a parameter list where 'auto' should trigger an implicit template parameter. */ bool auto_is_implicit_function_template_parm_p; /* TRUE if the function being declared was made a template due to its parameter list containing generic type specifiers (`auto' or concept identifiers) rather than an explicit template parameter list. */ bool fully_implicit_function_template_p; /* Tracks the function's template parameter list when declaring a function using generic type parameters. This is either a new chain in the case of a fully implicit function template or an extension of the function's existing template parameter list. This is tracked to optimize calls subsequent calls to synthesize_implicit_template_parm during cp_parser_parameter_declaration. */ tree implicit_template_parms; /* The scope into which an implicit template parameter list has been introduced or an existing template parameter list is being extended with implicit template parameters. In most cases this is the sk_function_parms scope containing the use of a generic type. In the case of an out-of-line member definition using a generic type, it is the sk_class scope. */ cp_binding_level* implicit_template_scope; /* True if parsing a result type in a compound requirement. This permits constrained-type-specifiers inside what would normally be a trailing return type. */ bool in_result_type_constraint_p; /* True if a constrained-type-specifier is not allowed in this context e.g., because they could never be deduced. */ int prevent_constrained_type_specifiers; /* Location of the string-literal token within the current linkage specification, if any, or UNKNOWN_LOCATION otherwise. */ location_t innermost_linkage_specification_location; }; /* In parser.c */ extern void debug (cp_token &ref); extern void debug (cp_token *ptr); extern void cp_lexer_debug_tokens (vec<cp_token, va_gc> *); extern void debug (vec<cp_token, va_gc> &ref); extern void debug (vec<cp_token, va_gc> *ptr); extern void cp_debug_parser (FILE *, cp_parser *); extern void debug (cp_parser &ref); extern void debug (cp_parser *ptr); extern bool cp_keyword_starts_decl_specifier_p (enum rid keyword); #endif /* GCC_CP_PARSER_H */
3.h
// // Created by aleksey on 28.11.16. // #ifndef TASKSOPENMP_3_H #define TASKSOPENMP_3_H #include <iostream> #include <ctime> #include <omp.h> #include "Tree.h" using namespace std; int par, prec; int found_count; //Обрабатываем узел void find(struct node *tree) { // Подсчитываем число узлов num_nodes++; // Связываем с каждым узлом какую-то работу // Работа имеет разную вычислительную сложность для различных вершин //work(tree->num); // Выводим номер узла, который обработали //cout << tree->num << endl; if (abs(tree->num - par) <= prec) found_count += 1; if (tree->left) find(tree->left); if (tree->right) find(tree->right); return; } //Обрабатываем узел void find_parallel(struct node *tree) { // Подсчитываем число узлов #pragma omp atomic num_nodes++; // Связываем с каждым узлом какую-то работу // Работа имеет разную вычислительную сложность для различных вершин // work(tree->num); // Выводим номер узла, который обработали //cout << tree->num << " " << omp_get_thread_num() << endl; if (abs(tree->num - par) <= prec) #pragma omp atomic found_count += 1; #pragma omp task if (tree->left) find_parallel(tree->left); #pragma omp task if (tree->right) find_parallel(tree->right); return; } void task_3a(node *tree, int par, int prec){ cout << "3a) Поиск элементов abs(N - " << par << ") < " << prec << endl; ::par = par; ::prec = prec; found_count = 0; num_nodes = 0; clock_t start, finish; // переменные для измерения времени double time1, time2; start = clock(); find(tree); finish = clock(); time1 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Time serial is " << time1 << endl; cout << "Число элементов (abs(N-par) <= prec) = " << found_count; found_count = 0; num_nodes = 0; start = clock(); #pragma omp parallel { #pragma omp single { find_parallel(tree); } } finish = clock(); time2 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Время выполнения параллельного варианта" << time2 << endl; cout << "Число вершин " << num_nodes << endl; cout << "Число элементов (abs(N-par) <= prec) = " << found_count; } //Обрабатываем узел void find_parallel_atomic(struct node *tree) { // Подсчитываем число узлов #pragma omp atomic num_nodes++; // Связываем с каждым узлом какую-то работу // Работа имеет разную вычислительную сложность для различных вершин // work(tree->num); // Выводим номер узла, который обработали //cout << tree->num << " " << omp_get_thread_num() << endl; if (abs(tree->num - par) <= prec) #pragma omp atomic found_count += 1; #pragma omp task if (tree->left) find_parallel_atomic(tree->left); #pragma omp task if (tree->right) find_parallel_atomic(tree->right); return; } void task_3b(node *tree, int par, int prec){ cout << "3б) [Atomic] Поиск элементов abs(N - " << par << ") < " << prec << endl; ::par = par; ::prec = prec; found_count = 0; num_nodes = 0; clock_t start, finish; // переменные для измерения времени double time1, time2; start = clock(); find(tree); finish = clock(); time1 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Время посоледовательного варианта " << time1 << endl; cout << "Число вершин (abs(N-par) <= prec) = " << found_count; found_count = 0; num_nodes = 0; start = clock(); #pragma omp parallel { #pragma omp single { find_parallel_atomic(tree); } } finish = clock(); time2 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Время параллельного варианта (atomic) " << time2 << endl; cout << "Число вершин " << num_nodes << endl; cout << "Число вершин (abs(N-par) <= prec) = " << found_count; } int first_found_number = 0; //Обрабатываем узел void find_until_first(struct node *tree) { // Подсчитываем число узлов #pragma omp atomic num_nodes++; // Связываем с каждым узлом какую-то работу // Работа имеет разную вычислительную сложность для различных вершин // work(tree->num); // Выводим номер узла, который обработали //cout << tree->num << " " << omp_get_thread_num() << endl; if (abs(tree->num - par) <= prec) { #pragma omp atomic found_count += 1; first_found_number = tree->num; return; } #pragma omp task if (tree->left) find_until_first(tree->left); #pragma omp task if (tree->right) find_until_first(tree->right); return; } void task_3ge(node * tree, int par, int prec){ cout << "3ге) Последовательный и параллельный варианты поиска до 1 встретившейся вершины" << endl; ::par = par; ::prec = prec; found_count = 0; num_nodes = 0; first_found_number = -1; clock_t start, finish; // переменные для измерения времени double time1, time2; start = clock(); find_until_first(tree); finish = clock(); time1 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Последовательный вариант " << time1 << endl; cout << "Число вершин " << num_nodes << endl; cout << "Первая найденная " << first_found_number << endl; found_count = 0; num_nodes = 0; first_found_number = -1; start = clock(); #pragma omp parallel { #pragma omp single { find_until_first(tree); } } finish = clock(); time2 = (double)(finish - start)/CLOCKS_PER_SEC; cout << "Параллельный вариант " << time2 << endl; cout << "Число вершин " << num_nodes << endl; cout << "Первая найденная " << first_found_number << endl; found_count = 0; num_nodes = 0; first_found_number = -1; } #endif // TASKSOPENMP_3_H
DRB025-simdtruedep-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. */ /* This one has race condition due to true dependence. But data races happen at instruction level, not thread level. Data race pair: a[i+1]@68:5 vs. a[i]@68:12 */ #include <stdlib.h> int main(int argc, char* argv[]) { int i; int len=100; if (argc>1) len = atoi(argv[1]); int a[len], b[len]; #pragma omp parallel for for (i=0;i<len;i++) { a[i]=i; b[i]=i+1; } for (i=0;i<len-1;i++) a[i+1]=a[i]*b[i]; for (i=0;i<len;i++) printf("i=%d a[%d]=%d\n",i,i,a[i]); return 0; }
omp_bug2.c
/****************************************************************************** * FILE: omp_bug2.c * DESCRIPTION: * Another OpenMP program with a bug. * AUTHOR: Blaise Barney * LAST REVISED: 04/06/05 ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int nthreads, i, tid; float total; /*** Spawn parallel region ***/ #pragma omp parallel { /* Obtain thread number */ tid = omp_get_thread_num(); /* Only master thread does this */ if (tid == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } printf("Thread %d is starting...\n",tid); #pragma omp barrier /* do some work */ total = 0.0; #pragma omp for schedule(dynamic,10) for (i=0; i<1000000; i++) total = total + i*1.0; printf ("Thread %d is done! Total= %e\n",tid,total); } /*** End of parallel region ***/ }
GB_binop__iseq_fp32.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__iseq_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__iseq_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__iseq_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_fp32) // A*D function (colscale): GB (_AxD__iseq_fp32) // D*A function (rowscale): GB (_DxB__iseq_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_fp32) // C=scalar+B GB (_bind1st__iseq_fp32) // C=scalar+B' GB (_bind1st_tran__iseq_fp32) // C=A+scalar GB (_bind2nd__iseq_fp32) // C=A'+scalar GB (_bind2nd_tran__iseq_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float 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) \ float bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float 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_ISEQ || GxB_NO_FP32 || GxB_NO_ISEQ_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__iseq_fp32) ( 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__iseq_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__iseq_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__iseq_fp32) ( 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 float *restrict Cx = (float *) 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__iseq_fp32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) 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__iseq_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) 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__iseq_fp32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__iseq_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__iseq_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__iseq_fp32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__iseq_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float 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__iseq_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = 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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_fp32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
matrix_base.h
#ifndef MATRIX_BASE_H_ #define MATRIX_BASE_H_ namespace acspo { template <typename T> class matrix { private: std::shared_ptr<T> _refs; T *_data; unsigned int _rows, _cols, _elem; public: matrix(); matrix(unsigned int rows, unsigned int cols); matrix(std::pair<unsigned int, unsigned int> size); matrix(unsigned int rows, unsigned int cols, T *data); matrix(std::pair<unsigned int, unsigned int> size, T *_data); unsigned int rows() const; unsigned int cols() const; std::pair<unsigned int, unsigned int> size() const; unsigned int elem() const; T & at(unsigned int i, unsigned int j); T & operator()(unsigned int i, unsigned int j); const T & at(unsigned int i, unsigned int j) const; const T & operator()(unsigned int i, unsigned int j) const; T & at(std::pair<unsigned int, unsigned int> ij); T & operator()(std::pair<unsigned int, unsigned int> ij); const T & at(std::pair<unsigned int, unsigned int> ij) const; const T & operator()(std::pair<unsigned int, unsigned int> ij) const; T & at(unsigned int i); T & operator()(unsigned int i); const T & at(unsigned int i) const; const T & operator()(unsigned int i) const; T * ptr(unsigned int i = 0); T * operator[](unsigned int i); const T * ptr(unsigned int i = 0) const; const T * operator[](unsigned int i) const; matrix & copy(const matrix &mat); matrix & assign(const T &val); matrix & assign(const T &val, const matrix<bool> &mask); matrix & assign(const T &val1, const T &val2, const matrix<bool> &mask); matrix & create(unsigned int rows, unsigned int cols); matrix & create(std::pair<unsigned int, unsigned int> size); matrix clone() const; static matrix zeros(unsigned int rows, unsigned int cols); static matrix zeros(std::pair<unsigned int, unsigned int> size); template <typename S> matrix<S> convert() const; void write(const std::string &name, bool newline = true) const; void write(std::ostream &os, bool newline = true) const; }; template <typename T> matrix<T>::matrix() { _rows = 0; _cols = 0; _elem = 0; } template <typename T> matrix<T>::matrix(unsigned int rows, unsigned int cols) { _rows = 0; _cols = 0; _elem = 0; create(rows, cols); } template <typename T> matrix<T>::matrix(std::pair<unsigned int, unsigned int> size) { _rows = 0; _cols = 0; _elem = 0; create(size); } template <typename T> matrix<T>::matrix(unsigned int rows, unsigned int cols, T *data) { _rows = rows; _cols = cols; _elem = rows*cols; _data = data; } template <typename T> matrix<T>::matrix(std::pair<unsigned int, unsigned int> size, T *data) { _rows = size.first; _cols = size.second; _elem = size.first*size.second; _data = data; } template <typename T> unsigned int matrix<T>::rows() const { return _rows; } template <typename T> unsigned int matrix<T>::cols() const { return _cols; } template <typename T> std::pair<unsigned int, unsigned int> matrix<T>::size() const { return std::make_pair(_rows, _cols); } template <typename T> unsigned int matrix<T>::elem() const { return _elem; } template <typename T> T & matrix<T>::at(unsigned int i, unsigned int j) { return const_cast<T &>(static_cast<const matrix<T> &>(*this).at(i, j)); } template <typename T> T & matrix<T>::operator()(unsigned int i, unsigned int j) { return at(i, j); } template <typename T> T & matrix<T>::at(std::pair<unsigned int, unsigned int> ij) { return at(ij.first, ij.second); } template <typename T> T & matrix<T>::operator()(std::pair<unsigned int, unsigned int> ij) { return at(ij.first, ij.second); } template <typename T> T & matrix<T>::at(unsigned int i) { return const_cast<T &>(static_cast<const matrix<T> &>(*this).at(i)); } template <typename T> T & matrix<T>::operator()(unsigned int i) { return at(i); } template <typename T> const T & matrix<T>::at(unsigned int i, unsigned int j) const { #ifndef NDEBUG if (i >= _rows) { throw std::out_of_range("row is out of range"); } if (j >= _cols) { throw std::out_of_range("column is out of range"); } #endif return _data[i*_cols+j]; } template <typename T> const T & matrix<T>::operator()(unsigned int i, unsigned int j) const { return at(i, j); } template <typename T> const T & matrix<T>::at(std::pair<unsigned int, unsigned int> ij) const { return at(ij.first, ij.second); } template <typename T> const T & matrix<T>::operator()(std::pair<unsigned int, unsigned int> ij) const { return at(ij.first, ij.second); } template <typename T> const T & matrix<T>::at(unsigned int i) const { #ifndef NDEBUG if (i >= _elem) { throw std::out_of_range("element is out of range"); } #endif return _data[i]; } template <typename T> const T & matrix<T>::operator()(unsigned int i) const { return at(i); } template <typename T> T * matrix<T>::ptr(unsigned int i) { return const_cast<T *>(static_cast<const matrix<T> &>(*this).ptr(i)); } template <typename T> T * matrix<T>::operator[](unsigned int i) { return ptr(i); } template <typename T> const T * matrix<T>::ptr(unsigned int i) const { #ifndef NDEBUG if (i >= _rows) { throw std::out_of_range("row is out of range"); } #endif return &_data[i*_cols]; } template <typename T> const T * matrix<T>::operator[](unsigned int i) const { return ptr(i); } template <typename T> matrix<T> & matrix<T>::copy(const matrix &mat) { if (size() != mat.size()) { throw std::invalid_argument("dimension mismatch"); } #pragma omp parallel for for (int i = 0; i < _elem; i++) { _data[i] = mat._data[i]; } return *this; } template <typename T> matrix<T> matrix<T>::clone() const { return matrix(_rows, _cols).copy(*this); } template <typename T> template <typename S> matrix<S> matrix<T>::convert() const { matrix<S> ret(_rows, _cols); S *ptr = ret.ptr(); #pragma omp parallel for for (unsigned int i = 0; i < _elem; i++) { ptr[i] = _data[i]; } return ret; } template <typename T> void matrix<T>::write(std::ostream &os, bool newline) const { for (unsigned int i = 0; i < _rows; i++) { for (unsigned int j = 0; j < _cols; j++) { os << at(i, j); if (j < _cols-1) { os << " "; } } if (i < _rows-1) { os << std::endl; } } if (newline) { os << std::endl; } } template <typename T> void matrix<T>::write(const std::string &name, bool newline) const { std::ofstream os(name); write(os, newline); } template <typename T> std::ostream & operator<<(std::ostream &os, const matrix<T> &mat) { os << mat.rows() << " x " << mat.cols() << " matrix:" << std::endl; mat.write(os, false); return os; } template <typename T> matrix<T> & matrix<T>::assign(const T &val) { #pragma omp parallel for for (unsigned int i = 0; i < _elem; i++) { _data[i] = val; } return *this; } template <typename T> matrix<T> & matrix<T>::assign(const T &val, const matrix<bool> &mask) { if (size() != mask.size()) { throw std::invalid_argument("dimension mismatch"); } const bool *ptr = mask.ptr(); #pragma omp parallel for for (unsigned int i = 0; i < _elem; i++) { if (ptr[i]) { _data[i] = val; } } return *this; } template <typename T> matrix<T> & matrix<T>::assign(const T &val1, const T &val2, const matrix<bool> &mask) { if (size() != mask.size()) { throw std::invalid_argument("dimension mismatch"); } const bool *ptr = mask.ptr(); #pragma omp parallel for for (unsigned int i = 0; i < _elem; i++) { if (ptr[i]) { _data[i] = val1; } else { _data[i] = val2; } } return *this; } template <typename T> matrix<T> & matrix<T>::create(unsigned int rows, unsigned int cols) { unsigned int elem = rows*cols; if (elem == _elem) { _rows = rows; _cols = cols; return *this; } _rows = rows; _cols = cols; _elem = elem; _refs.reset(); _data = new T[_elem]; _refs.reset(_data, std::default_delete<T[]>()); return *this; } template <typename T> matrix<T> & matrix<T>::create(std::pair<unsigned int, unsigned int> size) { return create(size.first, size.second); } template <typename T> matrix<T> matrix<T>::zeros(unsigned int rows, unsigned int cols) { return matrix(rows, cols).assign(0); } template <typename T> matrix<T> matrix<T>::zeros(std::pair<unsigned int, unsigned int> size) { return matrix(size).assign(0); } } #endif
ocp_nlp_sqp.c
/* * Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, * Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, * Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, * Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl * * This file is part of acados. * * The 2-Clause 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 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 "acados/ocp_nlp/ocp_nlp_sqp.h" // external #include <assert.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #if defined(ACADOS_WITH_OPENMP) #include <omp.h> #endif // blasfeo #include "blasfeo/include/blasfeo_d_aux.h" #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" #include "blasfeo/include/blasfeo_d_blas.h" // acados #include "acados/ocp_nlp/ocp_nlp_common.h" #include "acados/ocp_nlp/ocp_nlp_dynamics_cont.h" #include "acados/ocp_nlp/ocp_nlp_reg_common.h" #include "acados/ocp_qp/ocp_qp_common.h" #include "acados/utils/mem.h" #include "acados/utils/print.h" #include "acados/utils/timing.h" #include "acados/utils/types.h" #include "acados_c/ocp_qp_interface.h" /************************************************ * options ************************************************/ acados_size_t ocp_nlp_sqp_opts_calculate_size(void *config_, void *dims_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_opts); size += ocp_nlp_opts_calculate_size(config, dims); return size; } void *ocp_nlp_sqp_opts_assign(void *config_, void *dims_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; char *c_ptr = (char *) raw_memory; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_opts); opts->nlp_opts = ocp_nlp_opts_assign(config, dims, c_ptr); c_ptr += ocp_nlp_opts_calculate_size(config, dims); assert((char *) raw_memory + ocp_nlp_sqp_opts_calculate_size(config, dims) >= c_ptr); return opts; } void ocp_nlp_sqp_opts_initialize_default(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // int ii; // this first !!! ocp_nlp_opts_initialize_default(config, dims, nlp_opts); // SQP opts opts->max_iter = 20; opts->tol_stat = 1e-8; opts->tol_eq = 1e-8; opts->tol_ineq = 1e-8; opts->tol_comp = 1e-8; opts->ext_qp_res = 0; opts->qp_warm_start = 0; opts->warm_start_first_qp = false; opts->rti_phase = 0; opts->print_level = 0; opts->initialize_t_slacks = 0; // overwrite default submodules opts // qp tolerance qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_stat", &opts->tol_stat); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_eq", &opts->tol_eq); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_ineq", &opts->tol_ineq); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_comp", &opts->tol_comp); return; } void ocp_nlp_sqp_opts_update(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_update(config, dims, nlp_opts); return; } void ocp_nlp_sqp_opts_set(void *config_, void *opts_, const char *field, void* value) { ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; int ii; char module[MAX_STR_LEN]; char *ptr_module = NULL; int module_length = 0; // extract module name char *char_ = strchr(field, '_'); if (char_!=NULL) { module_length = char_-field; for (ii=0; ii<module_length; ii++) module[ii] = field[ii]; module[module_length] = '\0'; // add end of string ptr_module = module; } // pass options to QP module if ( ptr_module!=NULL && (!strcmp(ptr_module, "qp")) ) { ocp_nlp_opts_set(config, nlp_opts, field, value); if (!strcmp(field, "qp_warm_start")) { int* i_ptr = (int *) value; opts->qp_warm_start = *i_ptr; } } else // nlp opts { if (!strcmp(field, "max_iter")) { int* max_iter = (int *) value; opts->max_iter = *max_iter; } else if (!strcmp(field, "tol_stat")) { double* tol_stat = (double *) value; opts->tol_stat = *tol_stat; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_stat", value); } else if (!strcmp(field, "tol_eq")) { double* tol_eq = (double *) value; opts->tol_eq = *tol_eq; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_eq", value); } else if (!strcmp(field, "tol_ineq")) { double* tol_ineq = (double *) value; opts->tol_ineq = *tol_ineq; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_ineq", value); } else if (!strcmp(field, "tol_comp")) { double* tol_comp = (double *) value; opts->tol_comp = *tol_comp; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_comp", value); } else if (!strcmp(field, "ext_qp_res")) { int* ext_qp_res = (int *) value; opts->ext_qp_res = *ext_qp_res; } else if (!strcmp(field, "warm_start_first_qp")) { bool* warm_start_first_qp = (bool *) value; opts->warm_start_first_qp = *warm_start_first_qp; } else if (!strcmp(field, "rti_phase")) { int* rti_phase = (int *) value; if (*rti_phase < 0 || *rti_phase > 0) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for rti_phase field."); printf("possible values are: 0\n"); exit(1); } else opts->rti_phase = *rti_phase; } else if (!strcmp(field, "print_level")) { int* print_level = (int *) value; if (*print_level < 0) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for print_level field, need int >=0, got %d.", *print_level); exit(1); } opts->print_level = *print_level; } else if (!strcmp(field, "initialize_t_slacks")) { int* initialize_t_slacks = (int *) value; if (*initialize_t_slacks != 0 && *initialize_t_slacks != 1) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for initialize_t_slacks field, need int 0 or 1, got %d.", *initialize_t_slacks); exit(1); } opts->initialize_t_slacks = *initialize_t_slacks; } else { ocp_nlp_opts_set(config, nlp_opts, field, value); } } return; } void ocp_nlp_sqp_opts_set_at_stage(void *config_, void *opts_, size_t stage, const char *field, void* value) { ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_set_at_stage(config, nlp_opts, stage, field, value); return; } /************************************************ * memory ************************************************/ acados_size_t ocp_nlp_sqp_memory_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_memory); // nlp mem size += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat int stat_m = opts->max_iter+1; int stat_n = 6; if (opts->ext_qp_res) stat_n += 4; size += stat_n*stat_m*sizeof(double); size += 3*8; // align make_int_multiple_of(8, &size); return size; } void *ocp_nlp_sqp_memory_assign(void *config_, void *dims_, void *opts_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // ocp_nlp_dynamics_config **dynamics = config->dynamics; // ocp_nlp_cost_config **cost = config->cost; // ocp_nlp_constraints_config **constraints = config->constraints; char *c_ptr = (char *) raw_memory; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; // initial align align_char_to(8, &c_ptr); ocp_nlp_sqp_memory *mem = (ocp_nlp_sqp_memory *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_memory); align_char_to(8, &c_ptr); // nlp mem mem->nlp_mem = ocp_nlp_memory_assign(config, dims, nlp_opts, c_ptr); c_ptr += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat mem->stat = (double *) c_ptr; mem->stat_m = opts->max_iter+1; mem->stat_n = 6; if (opts->ext_qp_res) mem->stat_n += 4; c_ptr += mem->stat_m*mem->stat_n*sizeof(double); mem->status = ACADOS_READY; align_char_to(8, &c_ptr); assert((char *) raw_memory + ocp_nlp_sqp_memory_calculate_size(config, dims, opts) >= c_ptr); return mem; } /************************************************ * workspace ************************************************/ acados_size_t ocp_nlp_sqp_workspace_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; acados_size_t size = 0; // sqp size += sizeof(ocp_nlp_sqp_workspace); // nlp size += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // tmp qp in size += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // tmp qp out size += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res size += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws size += ocp_qp_res_workspace_calculate_size(dims->qp_solver->orig_dims); } return size; } static void ocp_nlp_sqp_cast_workspace(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_sqp_opts *opts, ocp_nlp_sqp_memory *mem, ocp_nlp_sqp_workspace *work) { ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_memory *nlp_mem = mem->nlp_mem; // sqp char *c_ptr = (char *) work; c_ptr += sizeof(ocp_nlp_sqp_workspace); // nlp work->nlp_work = ocp_nlp_workspace_assign(config, dims, nlp_opts, nlp_mem, c_ptr); c_ptr += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // tmp qp in work->tmp_qp_in = ocp_qp_in_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // tmp qp out work->tmp_qp_out = ocp_qp_out_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res work->qp_res = ocp_qp_res_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws work->qp_res_ws = ocp_qp_res_workspace_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_workspace_calculate_size(dims->qp_solver->orig_dims); } assert((char *) work + ocp_nlp_sqp_workspace_calculate_size(config, dims, opts) >= c_ptr); return; } /************************************************ * functions ************************************************/ int ocp_nlp_sqp(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { acados_timer timer0, timer1; acados_tic(&timer0); ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; // zero timers double total_time = 0.0; double tmp_time; mem->time_qp_sol = 0.0; mem->time_qp_solver_call = 0.0; mem->time_qp_xcond = 0.0; mem->time_lin = 0.0; mem->time_reg = 0.0; mem->time_tot = 0.0; mem->time_glob = 0.0; mem->time_sim = 0.0; mem->time_sim_la = 0.0; mem->time_sim_ad = 0.0; int N = dims->N; int ii; int qp_iter = 0; int qp_status = 0; #if defined(ACADOS_WITH_OPENMP) // backup number of threads int num_threads_bkp = omp_get_num_threads(); // set number of threads omp_set_num_threads(opts->nlp_opts->num_threads); #pragma omp parallel { // beginning of parallel region #endif // alias to dynamics_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for #endif for (ii = 0; ii < N; ii++) { config->dynamics[ii]->memory_set_ux_ptr(nlp_out->ux+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_ux_ptr(nlp_work->tmp_nlp_out->ux+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_ux1_ptr(nlp_out->ux+ii+1, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_ux1_ptr(nlp_work->tmp_nlp_out->ux+ii+1, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_pi_ptr(nlp_out->pi+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_pi_ptr(nlp_work->tmp_nlp_out->pi+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_BAbt_ptr(nlp_mem->qp_in->BAbt+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_RSQrq_ptr(nlp_mem->qp_in->RSQrq+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_dzduxt_ptr(nlp_mem->dzduxt+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_sim_guess_ptr(nlp_mem->sim_guess+ii, nlp_mem->set_sim_guess+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_z_alg_ptr(nlp_mem->z_alg+ii, nlp_mem->dynamics[ii]); } // alias to cost_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for #endif for (ii = 0; ii <= N; ii++) { config->cost[ii]->memory_set_ux_ptr(nlp_out->ux+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_tmp_ux_ptr(nlp_work->tmp_nlp_out->ux+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_z_alg_ptr(nlp_mem->z_alg+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_dzdux_tran_ptr(nlp_mem->dzduxt+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_RSQrq_ptr(nlp_mem->qp_in->RSQrq+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_Z_ptr(nlp_mem->qp_in->Z+ii, nlp_mem->cost[ii]); } // alias to constraints_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for #endif for (ii = 0; ii <= N; ii++) { config->constraints[ii]->memory_set_ux_ptr(nlp_out->ux+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_tmp_ux_ptr(nlp_work->tmp_nlp_out->ux+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_lam_ptr(nlp_out->lam+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_tmp_lam_ptr(nlp_work->tmp_nlp_out->lam+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_z_alg_ptr(nlp_mem->z_alg+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_dzdux_tran_ptr(nlp_mem->dzduxt+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_DCt_ptr(nlp_mem->qp_in->DCt+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_RSQrq_ptr(nlp_mem->qp_in->RSQrq+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxb_ptr(nlp_mem->qp_in->idxb[ii], nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxs_rev_ptr(nlp_mem->qp_in->idxs_rev[ii], nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxe_ptr(nlp_mem->qp_in->idxe[ii], nlp_mem->constraints[ii]); } // alias to regularize memory config->regularize->memory_set_RSQrq_ptr(dims->regularize, nlp_mem->qp_in->RSQrq, nlp_mem->regularize_mem); config->regularize->memory_set_rq_ptr(dims->regularize, nlp_mem->qp_in->rqz, nlp_mem->regularize_mem); config->regularize->memory_set_BAbt_ptr(dims->regularize, nlp_mem->qp_in->BAbt, nlp_mem->regularize_mem); config->regularize->memory_set_b_ptr(dims->regularize, nlp_mem->qp_in->b, nlp_mem->regularize_mem); config->regularize->memory_set_idxb_ptr(dims->regularize, nlp_mem->qp_in->idxb, nlp_mem->regularize_mem); config->regularize->memory_set_DCt_ptr(dims->regularize, nlp_mem->qp_in->DCt, nlp_mem->regularize_mem); config->regularize->memory_set_ux_ptr(dims->regularize, nlp_mem->qp_out->ux, nlp_mem->regularize_mem); config->regularize->memory_set_pi_ptr(dims->regularize, nlp_mem->qp_out->pi, nlp_mem->regularize_mem); config->regularize->memory_set_lam_ptr(dims->regularize, nlp_mem->qp_out->lam, nlp_mem->regularize_mem); // copy sampling times into dynamics model #if defined(ACADOS_WITH_OPENMP) #pragma omp for #endif // NOTE(oj): this will lead in an error for irk_gnsf, T must be set in precompute; // -> remove here and make sure precompute is called everywhere. for (ii = 0; ii < N; ii++) { config->dynamics[ii]->model_set(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], "T", nlp_in->Ts+ii); } #if defined(ACADOS_WITH_OPENMP) } // end of parallel region #endif // if (opts->initialize_t_slacks > 0) ocp_nlp_initialize_t_slacks(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // initialize QP ocp_nlp_initialize_qp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // main sqp loop int sqp_iter = 0; nlp_mem->sqp_iter = &sqp_iter; for (; sqp_iter < opts->max_iter; sqp_iter++) { // linearizate NLP and update QP matrices acados_tic(&timer1); ocp_nlp_approximate_qp_matrices(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); mem->time_lin += acados_toc(&timer1); #ifdef MEASURE_TIMINGS // get timings from integrator for (ii=0; ii<N; ii++) { config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim", &tmp_time); mem->time_sim += tmp_time; config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim_la", &tmp_time); mem->time_sim_la += tmp_time; config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim_ad", &tmp_time); mem->time_sim_ad += tmp_time; } #endif // MEASURE_TIMINGS // update QP rhs for SQP (step prim var, abs dual var) ocp_nlp_approximate_qp_vectors_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // compute nlp residuals ocp_nlp_res_compute(dims, nlp_in, nlp_out, nlp_mem->nlp_res, nlp_mem); nlp_out->inf_norm_res = nlp_mem->nlp_res->inf_norm_res_stat; nlp_out->inf_norm_res = (nlp_mem->nlp_res->inf_norm_res_eq > nlp_out->inf_norm_res) ? nlp_mem->nlp_res->inf_norm_res_eq : nlp_out->inf_norm_res; nlp_out->inf_norm_res = (nlp_mem->nlp_res->inf_norm_res_ineq > nlp_out->inf_norm_res) ? nlp_mem->nlp_res->inf_norm_res_ineq : nlp_out->inf_norm_res; nlp_out->inf_norm_res = (nlp_mem->nlp_res->inf_norm_res_comp > nlp_out->inf_norm_res) ? nlp_mem->nlp_res->inf_norm_res_comp : nlp_out->inf_norm_res; if (opts->print_level > sqp_iter + 1) print_ocp_qp_in(nlp_mem->qp_in); // save statistics if (sqp_iter < mem->stat_m) { mem->stat[mem->stat_n*sqp_iter+0] = nlp_mem->nlp_res->inf_norm_res_stat; mem->stat[mem->stat_n*sqp_iter+1] = nlp_mem->nlp_res->inf_norm_res_eq; mem->stat[mem->stat_n*sqp_iter+2] = nlp_mem->nlp_res->inf_norm_res_ineq; mem->stat[mem->stat_n*sqp_iter+3] = nlp_mem->nlp_res->inf_norm_res_comp; } // exit conditions on residuals if ((nlp_mem->nlp_res->inf_norm_res_stat < opts->tol_stat) & (nlp_mem->nlp_res->inf_norm_res_eq < opts->tol_eq) & (nlp_mem->nlp_res->inf_norm_res_ineq < opts->tol_ineq) & (nlp_mem->nlp_res->inf_norm_res_comp < opts->tol_comp)) { // save sqp iterations number mem->sqp_iter = sqp_iter; nlp_out->sqp_iter = sqp_iter; // stop timer total_time += acados_toc(&timer0); // save time nlp_out->total_time = total_time; mem->time_tot = total_time; #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif mem->status = ACADOS_SUCCESS; if (opts->print_level > 0) { printf("%i\t%e\t%e\t%e\t%e.\n", sqp_iter, nlp_mem->nlp_res->inf_norm_res_stat, nlp_mem->nlp_res->inf_norm_res_eq, nlp_mem->nlp_res->inf_norm_res_ineq, nlp_mem->nlp_res->inf_norm_res_comp ); printf("\n\n"); } return mem->status; } // regularize Hessian acados_tic(&timer1); config->regularize->regularize_hessian(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); // (typically) no warm start at first iteration if (sqp_iter == 0 && !opts->warm_start_first_qp) { int tmp_int = 0; config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "warm_start", &tmp_int); } // solve qp acados_tic(&timer1); qp_status = qp_solver->evaluate(qp_solver, dims->qp_solver, nlp_mem->qp_in, nlp_mem->qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); mem->time_qp_sol += acados_toc(&timer1); qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_solver_call", &tmp_time); mem->time_qp_solver_call += tmp_time; qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_xcond", &tmp_time); mem->time_qp_xcond += tmp_time; // compute correct dual solution in case of Hessian regularization acados_tic(&timer1); config->regularize->correct_dual_sol(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); // restore default warm start if (sqp_iter==0) { config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "warm_start", &opts->qp_warm_start); } // TODO move into QP solver memory ??? qp_info *qp_info_; ocp_qp_out_get(nlp_mem->qp_out, "qp_info", &qp_info_); nlp_out->qp_iter = qp_info_->num_iter; // printf("\nqp_iter = %d, sqp_iter = %d, max_sqp_iter = %d\n", nlp_out->qp_iter, sqp_iter, opts->max_iter); qp_iter = qp_info_->num_iter; // save statistics of last qp solver call if (sqp_iter+1 < mem->stat_m) { mem->stat[mem->stat_n*(sqp_iter+1)+4] = qp_status; mem->stat[mem->stat_n*(sqp_iter+1)+5] = qp_iter; } // compute external QP residuals (for debugging) if (opts->ext_qp_res) { ocp_qp_res_compute(nlp_mem->qp_in, nlp_mem->qp_out, work->qp_res, work->qp_res_ws); if (sqp_iter+1 < mem->stat_m) ocp_qp_res_compute_nrm_inf(work->qp_res, mem->stat+(mem->stat_n*(sqp_iter+1)+6)); } if ((qp_status!=ACADOS_SUCCESS) & (qp_status!=ACADOS_MAXITER)) { // print_ocp_qp_in(nlp_mem->qp_in); if (opts->print_level > 0) { printf("%i\t%e\t%e\t%e\t%e.\n", sqp_iter, nlp_mem->nlp_res->inf_norm_res_stat, nlp_mem->nlp_res->inf_norm_res_eq, nlp_mem->nlp_res->inf_norm_res_ineq, nlp_mem->nlp_res->inf_norm_res_comp ); printf("\n\n"); } // increment sqp_iter to return full statistics and improve output below. sqp_iter++; // save sqp iterations number mem->sqp_iter = sqp_iter; nlp_out->sqp_iter = sqp_iter; // stop timer total_time += acados_toc(&timer0); // save time mem->time_tot = total_time; nlp_out->total_time = total_time; #ifndef ACADOS_SILENT printf("\nQP solver returned error status %d in SQP iteration %d, QP iteration %d.\n", qp_status, sqp_iter, qp_iter); #endif #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif if (opts->print_level > 1) { printf("\n Failed to solve the following QP:\n"); if (opts->print_level > sqp_iter + 1) print_ocp_qp_in(nlp_mem->qp_in); } mem->status = ACADOS_QP_FAILURE; return mem->status; } // globalization acados_tic(&timer1); double alpha = ocp_nlp_line_search(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); mem->time_glob += acados_toc(&timer1); // update variables ocp_nlp_update_variables_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work, alpha); // ocp_nlp_dims_print(nlp_out->dims); // ocp_nlp_out_print(nlp_out); // exit(1); // ??? @rien // for (int_t i = 0; i < N; i++) // { // ocp_nlp_dynamics_opts *dynamics_opts = opts->dynamics[i]; // sim_opts *opts = dynamics_opts->sim_solver; // if (opts->scheme == NULL) // continue; // opts->sens_adj = (opts->scheme->type != exact); // if (nlp_in->freezeSens) { // // freeze inexact sensitivities after first SQP iteration !! // opts->scheme->freeze = true; // } // } if (opts->print_level > 0) { if (sqp_iter%10 == 0) { printf("# it\tstat\t\teq\t\tineq\t\tcomp\n"); } printf("%i\t%e\t%e\t%e\t%e.\n", sqp_iter, nlp_mem->nlp_res->inf_norm_res_stat, nlp_mem->nlp_res->inf_norm_res_eq, nlp_mem->nlp_res->inf_norm_res_ineq, nlp_mem->nlp_res->inf_norm_res_comp ); } } // stop timer total_time += acados_toc(&timer0); if (opts->print_level > 0) printf("\n\n"); // ocp_nlp_out_print(nlp_out); // save sqp iterations number mem->sqp_iter = sqp_iter; nlp_out->sqp_iter = sqp_iter; // save time mem->time_tot = total_time; nlp_out->total_time = total_time; // maximum number of iterations reached #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif mem->status = ACADOS_MAXITER; #ifndef ACADOS_SILENT printf("\n ocp_nlp_sqp: maximum iterations reached\n"); #endif return mem->status; } int ocp_nlp_sqp_precompute(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; // ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; int N = dims->N; int status = ACADOS_SUCCESS; int ii; // TODO(all) add flag to enable/disable checks for (ii = 0; ii <= N; ii++) { int module_val; config->constraints[ii]->dims_get(config->constraints[ii], dims->constraints[ii], "ns", &module_val); if (dims->ns[ii] != module_val) { printf("ocp_nlp_sqp_precompute: inconsistent dimension ns for stage %d with constraint module, got %d, module: %d.", ii, dims->ns[ii], module_val); exit(1); } } // precompute for (ii = 0; ii < N; ii++) { // set T config->dynamics[ii]->model_set(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], "T", nlp_in->Ts+ii); // dynamics precompute status = config->dynamics[ii]->precompute(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], opts->nlp_opts->dynamics[ii], nlp_mem->dynamics[ii], nlp_work->dynamics[ii]); if (status != ACADOS_SUCCESS) return status; } return status; } void ocp_nlp_sqp_eval_param_sens(void *config_, void *dims_, void *opts_, void *mem_, void *work_, char *field, int stage, int index, void *sens_nlp_out_) { acados_timer timer0; acados_tic(&timer0); ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_out *sens_nlp_out = sens_nlp_out_; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; d_ocp_qp_copy_all(nlp_mem->qp_in, work->tmp_qp_in); d_ocp_qp_set_rhs_zero(work->tmp_qp_in); double one = 1.0; if ((!strcmp("ex", field)) & (stage==0)) { d_ocp_qp_set_el("lbx", stage, index, &one, work->tmp_qp_in); d_ocp_qp_set_el("ubx", stage, index, &one, work->tmp_qp_in); // d_ocp_qp_print(work->tmp_qp_in->dim, work->tmp_qp_in); config->qp_solver->eval_sens(config->qp_solver, dims->qp_solver, work->tmp_qp_in, work->tmp_qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); // d_ocp_qp_sol_print(work->tmp_qp_out->dim, work->tmp_qp_out); // exit(1); /* copy tmp_qp_out into sens_nlp_out */ int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; // int *nz = dims->nz; for (i = 0; i <= N; i++) { blasfeo_dveccp(nv[i], work->tmp_qp_out->ux + i, 0, sens_nlp_out->ux + i, 0); if (i < N) blasfeo_dveccp(nx[i + 1], work->tmp_qp_out->pi + i, 0, sens_nlp_out->pi + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->lam + i, 0, sens_nlp_out->lam + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->t + i, 0, sens_nlp_out->t + i, 0); } } else { printf("\nerror: field %s at stage %d not available in ocp_nlp_sqp_eval_param_sens\n", field, stage); exit(1); } mem->time_solution_sensitivities = acados_toc(&timer0); return; } // TODO rename memory_get ??? void ocp_nlp_sqp_get(void *config_, void *dims_, void *mem_, const char *field, void *return_value_) { ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; ocp_nlp_sqp_memory *mem = mem_; if (!strcmp("sqp_iter", field)) { int *value = return_value_; *value = mem->sqp_iter; } else if (!strcmp("status", field)) { int *value = return_value_; *value = mem->status; } else if (!strcmp("time_tot", field) || !strcmp("tot_time", field)) { double *value = return_value_; *value = mem->time_tot; } else if (!strcmp("time_qp_sol", field) || !strcmp("time_qp", field)) { double *value = return_value_; *value = mem->time_qp_sol; } else if (!strcmp("time_qp_solver", field) || !strcmp("time_qp_solver_call", field)) { double *value = return_value_; *value = mem->time_qp_solver_call; } else if (!strcmp("time_qp_xcond", field)) { double *value = return_value_; *value = mem->time_qp_xcond; } else if (!strcmp("time_lin", field)) { double *value = return_value_; *value = mem->time_lin; } else if (!strcmp("time_reg", field)) { double *value = return_value_; *value = mem->time_reg; } else if (!strcmp("time_glob", field)) { double *value = return_value_; *value = mem->time_glob; } else if (!strcmp("time_solution_sensitivities", field)) { double *value = return_value_; *value = mem->time_solution_sensitivities; } else if (!strcmp("time_sim", field)) { double *value = return_value_; *value = mem->time_sim; } else if (!strcmp("time_sim_la", field)) { double *value = return_value_; *value = mem->time_sim_la; } else if (!strcmp("time_sim_ad", field)) { double *value = return_value_; *value = mem->time_sim_ad; } else if (!strcmp("stat", field)) { double **value = return_value_; *value = mem->stat; } else if (!strcmp("statistics", field)) { int n_row = mem->stat_m<mem->sqp_iter+1 ? mem->stat_m : mem->sqp_iter+1; double *value = return_value_; for (int ii=0; ii<n_row; ii++) { value[ii+0] = ii; for (int jj=0; jj<mem->stat_n; jj++) value[ii+(jj+1)*n_row] = mem->stat[jj+ii*mem->stat_n]; } } else if (!strcmp("stat_m", field)) { int *value = return_value_; *value = mem->stat_m; } else if (!strcmp("stat_n", field)) { int *value = return_value_; *value = mem->stat_n; } else if (!strcmp("nlp_mem", field)) { void **value = return_value_; *value = mem->nlp_mem; } else if (!strcmp("qp_xcond_dims", field)) { void **value = return_value_; *value = dims->qp_solver->xcond_dims; } else if (!strcmp("nlp_res", field)) { ocp_nlp_res **value = return_value_; *value = mem->nlp_mem->nlp_res; } else if (!strcmp("qp_xcond_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_in; } else if (!strcmp("qp_xcond_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_out; } else if (!strcmp("qp_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_in; } else if (!strcmp("qp_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_out; } else if (!strcmp("qp_iter", field)) { config->qp_solver->memory_get(config->qp_solver, mem->nlp_mem->qp_solver_mem, "iter", return_value_); } else if (!strcmp("res_stat", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_stat; } else if (!strcmp("res_eq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_eq; } else if (!strcmp("res_ineq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_ineq; } else if (!strcmp("res_comp", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_comp; } else if (!strcmp("cost_value", field)) { double *value = return_value_; *value = mem->nlp_mem->cost_value; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_get\n", field); exit(1); } } void ocp_nlp_sqp_opts_get(void *config_, void *dims_, void *opts_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; if (!strcmp("nlp_opts", field)) { void **value = return_value_; *value = opts->nlp_opts; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_opts_get\n", field); exit(1); } } void ocp_nlp_sqp_work_get(void *config_, void *dims_, void *work_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_workspace *work = work_; if (!strcmp("nlp_work", field)) { void **value = return_value_; *value = work->nlp_work; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_work_get\n", field); exit(1); } } void ocp_nlp_sqp_config_initialize_default(void *config_) { ocp_nlp_config *config = (ocp_nlp_config *) config_; config->opts_calculate_size = &ocp_nlp_sqp_opts_calculate_size; config->opts_assign = &ocp_nlp_sqp_opts_assign; config->opts_initialize_default = &ocp_nlp_sqp_opts_initialize_default; config->opts_update = &ocp_nlp_sqp_opts_update; config->opts_set = &ocp_nlp_sqp_opts_set; config->opts_set_at_stage = &ocp_nlp_sqp_opts_set_at_stage; config->memory_calculate_size = &ocp_nlp_sqp_memory_calculate_size; config->memory_assign = &ocp_nlp_sqp_memory_assign; config->workspace_calculate_size = &ocp_nlp_sqp_workspace_calculate_size; config->evaluate = &ocp_nlp_sqp; config->eval_param_sens = &ocp_nlp_sqp_eval_param_sens; config->config_initialize_default = &ocp_nlp_sqp_config_initialize_default; config->precompute = &ocp_nlp_sqp_precompute; config->get = &ocp_nlp_sqp_get; config->opts_get = &ocp_nlp_sqp_opts_get; config->work_get = &ocp_nlp_sqp_work_get; return; }
sddmm.h
/*! * Copyright (c) 2020 by Contributors * \file array/cpu/sddmm.h * \brief SDDMM CPU kernel function header. */ #ifndef DGL_ARRAY_CPU_SDDMM_H_ #define DGL_ARRAY_CPU_SDDMM_H_ #include <dgl/array.h> #include <dgl/bcast.h> namespace dgl { namespace aten { namespace cpu { /*! * \brief CPU kernel of g-SDDMM on Csr format. * \param bcast Broadcast information. * \param csr The Csr matrix. * \param ufeat The feature on source nodes. * \param vfeat The feature on destination nodes. * \param out The result feature on edges. * \note it uses node parallel strategy, different threads are responsible * for the computation of different nodes. */ template <typename IdType, typename DType, typename Op> void SDDMMCsr(const BcastOff& bcast, const CSRMatrix& csr, NDArray ufeat, NDArray vfeat, NDArray out) { const bool has_idx = !IsNullArray(csr.data); const IdType* indptr = csr.indptr.Ptr<IdType>(); const IdType* indices = csr.indices.Ptr<IdType>(); const IdType* edges = csr.data.Ptr<IdType>(); const DType* X = ufeat.Ptr<DType>(); const DType* Y = vfeat.Ptr<DType>(); const int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len, reduce_size = bcast.reduce_size; DType* O = out.Ptr<DType>(); #pragma omp parallel for for (IdType rid = 0; rid < csr.num_rows; ++rid) { const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; for (IdType j = row_start; j < row_end; ++j) { const IdType cid = indices[j]; const IdType eid = has_idx? edges[j] : j; DType* out_off = O + eid * dim; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs? X + rid * lhs_dim +\ lhs_add * reduce_size : nullptr; const DType* rhs_off = Op::use_rhs? Y + cid * rhs_dim +\ rhs_add * reduce_size : nullptr; out_off[k] = Op::Call(lhs_off, rhs_off, reduce_size); } } } } /*! * \brief CPU kernel of g-SDDMM on Coo format. * \param bcast Broadcast information. * \param coo The COO matrix. * \param ufeat The feature on source nodes. * \param vfeat The feature on destination nodes. * \param out The result feature on edges. * \note it uses edge parallel strategy, different threads are responsible * for the computation of different edges. */ template <typename IdType, typename DType, typename Op> void SDDMMCoo(const BcastOff& bcast, const COOMatrix& coo, NDArray ufeat, NDArray vfeat, NDArray out) { const bool has_idx = !IsNullArray(coo.data); const IdType* row = coo.row.Ptr<IdType>(); const IdType* col = coo.col.Ptr<IdType>(); const IdType* edges = coo.data.Ptr<IdType>(); const DType* X = ufeat.Ptr<DType>(); const DType* Y = vfeat.Ptr<DType>(); const int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len, reduce_size = bcast.reduce_size; DType* O = out.Ptr<DType>(); const int64_t nnz = coo.row->shape[0]; #pragma omp parallel for for (IdType i = 0; i < nnz; ++i) { const IdType rid = row[i]; const IdType cid = col[i]; const IdType eid = has_idx? edges[i] : i; DType* out_off = O + eid * dim; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs? X + rid * lhs_dim +\ lhs_add * reduce_size : nullptr; const DType* rhs_off = Op::use_rhs? Y + cid * rhs_dim +\ rhs_add * reduce_size : nullptr; out_off[k] = Op::Call(lhs_off, rhs_off, bcast.reduce_size); } } } namespace op { //////////////////////////////// binary operators on CPU //////////////////////////////// template <typename DType> struct Add { static constexpr bool use_lhs = true; static constexpr bool use_rhs = true; inline static DType Call(const DType* lhs_off, const DType* rhs_off, int64_t len = 1) { return *lhs_off + *rhs_off; } }; template <typename DType> struct Sub { static constexpr bool use_lhs = true; static constexpr bool use_rhs = true; inline static DType Call(const DType* lhs_off, const DType* rhs_off, int64_t len = 1) { return *lhs_off - *rhs_off; } }; template <typename DType> struct Mul { static constexpr bool use_lhs = true; static constexpr bool use_rhs = true; inline static DType Call(const DType* lhs_off, const DType* rhs_off, int64_t len = 1) { return *lhs_off * *rhs_off; } }; template <typename DType> struct Div { static constexpr bool use_lhs = true; static constexpr bool use_rhs = true; inline static DType Call(const DType* lhs_off, const DType* rhs_off, int64_t len = 1) { return *lhs_off / *rhs_off; } }; template <typename DType> struct CopyLhs { static constexpr bool use_lhs = true; static constexpr bool use_rhs = false; inline static DType Call(const DType* lhs_off, const DType*, int64_t len = 1) { return *lhs_off; } }; template <typename DType> struct CopyRhs { static constexpr bool use_lhs = false; static constexpr bool use_rhs = true; inline static DType Call(const DType* , const DType* rhs_off, int64_t len = 1) { return *rhs_off; } }; template <typename DType> struct Dot { static constexpr bool use_lhs = true; static constexpr bool use_rhs = true; inline static DType Call(const DType* lhs_off, const DType* rhs_off, int64_t len = 1) { DType rst = 0; for (int64_t l = 0; l < len; ++l) { rst += lhs_off[l] * rhs_off[l]; } return rst; } }; #define SWITCH_OP(op, Op, ...) \ do { \ if ((op) == "add") { \ typedef dgl::aten::cpu::op::Add<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "sub") { \ typedef dgl::aten::cpu::op::Sub<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "mul") { \ typedef dgl::aten::cpu::op::Mul<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "div") { \ typedef dgl::aten::cpu::op::Div<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "copy_u") { \ typedef dgl::aten::cpu::op::CopyLhs<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "copy_e") { \ typedef dgl::aten::cpu::op::CopyRhs<DType> Op; \ { __VA_ARGS__ } \ } else if ((op) == "dot") { \ typedef dgl::aten::cpu::op::Dot<DType> Op; \ { __VA_ARGS__ } \ } else { \ LOG(FATAL) << "Unsupported SDDMM binary operator: " << op; \ } \ } while (0) } // namespace op } // namespace cpu } // namespace aten } // namespace dgl #endif // DGL_ARRAY_CPU_SDDMM_H_
config.h
/* Copyright 2015 The math21 Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #pragma once #include "../../../includes/math21_feature_config.h" ///////////////////////////////// OPENMP //////////////////////////////////// #ifdef MATH21_FLAG_USE_OPENMP #include <omp.h> //#pragma omp critical #if !defined(MATH21_FLAG_IS_PARALLEL) #define MATH21_FLAG_IS_PARALLEL #endif #endif ///////////////////////////////// ANDROID //////////////////////////////////// #ifdef MATH21_ANDROID #include <android/log.h> #if 0 #ifdef printf #undef printf #endif #define printf(...) __android_log_print(ANDROID_LOG_INFO,"math21",__VA_ARGS__) #ifdef fprintf #undef fprintf #endif #define fprintf(X, ...) __android_log_print(ANDROID_LOG_INFO,"math21",__VA_ARGS__) #endif #endif
hmacSHA512_fmt_plug.c
/* * This software is Copyright (c) 2012 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * Based on hmac-md5 by Bartavelle */ #if FMT_EXTERNS_H extern struct fmt_main fmt_hmacSHA512; #elif FMT_REGISTERS_H john_register_one(&fmt_hmacSHA512); #else #include "sha2.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #define OMP_SCALE 64 #endif #include "memdbg.h" #define FORMAT_LABEL "HMAC-SHA512" #define FORMAT_NAME "" #if ARCH_BITS >= 64 #define ALGORITHM_NAME "password is key, SHA512 64/" ARCH_BITS_STR " " SHA2_LIB #else #define ALGORITHM_NAME "password is key, SHA512 32/" ARCH_BITS_STR " " SHA2_LIB #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define PAD_SIZE 128 #define BINARY_SIZE (512/8) #define BINARY_ALIGN 4 #define SALT_SIZE PAD_SIZE #define SALT_ALIGN 1 #define CIPHERTEXT_LENGTH (SALT_SIZE + 1 + BINARY_SIZE * 2) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"what do ya want for nothing?#164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737", "Jefe"}, {"Reference hashes are keys to success#73a5eff716d0147a440fdf5aff187c52deab8c4dc55073be3d5742e788a99fd6b53a5894725f0f88f3486b5bb63d2af930a0cf6267af572128273daf8eee4cfa", "The magnum"}, {"Beppe#Grillo#AB08C46822313481D548412A084F08C7CA3BBF8A98D901D14698759F4C36ADB07528348D56CAF4F6AF654E14FC102FF10DCF50794A82544426386C7BE238CEAF", "Io credo nella reincarnazione e sono di Genova; per cui ho fatto testamento e mi sono lasciato tutto a me."}, {NULL} }; static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD (*crypt_key)[BINARY_SIZE / sizeof(ARCH_WORD) + 1]; static unsigned char (*opad)[PAD_SIZE]; static unsigned char (*ipad)[PAD_SIZE]; static unsigned char cursalt[SALT_SIZE]; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_plain = mem_calloc_tiny(sizeof(*saved_plain) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_key = mem_calloc_tiny(sizeof(*crypt_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); opad = mem_calloc_tiny(sizeof(*opad) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); ipad = mem_calloc_tiny(sizeof(*opad) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int valid(char *ciphertext, struct fmt_main *self) { int pos, i; char *p; p = strrchr(ciphertext, '#'); // allow # in salt if (!p || p > &ciphertext[strlen(ciphertext)-1]) return 0; i = (int)(p - ciphertext); if(i > SALT_SIZE) return 0; pos = i+1; if (strlen(ciphertext+pos) != BINARY_SIZE*2) return 0; for (i = pos; i < BINARY_SIZE*2+pos; i++) { if (!( (('0' <= ciphertext[i])&&(ciphertext[i] <= '9')) || (('a' <= ciphertext[i])&&(ciphertext[i] <= 'f')) || (('A' <= ciphertext[i])&&(ciphertext[i] <= 'F')))) return 0; } return 1; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[CIPHERTEXT_LENGTH + 1]; strnzcpy(out, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(strrchr(out, '#')); return out; } static int get_hash_0(int index) { return crypt_key[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_key[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_key[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_key[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_key[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_key[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_key[index][0] & 0x7ffffff; } static void set_salt(void *salt) { memcpy(cursalt, salt, SALT_SIZE); } static void set_key(char *key, int index) { int len; int i; len = strlen(key); memset(ipad[index], 0x36, PAD_SIZE); memset(opad[index], 0x5C, PAD_SIZE); #if PLAINTEXT_LENGTH > PAD_SIZE memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; if (len > PAD_SIZE) { SHA512_CTX ctx; unsigned char k0[BINARY_SIZE]; SHA512_Init( &ctx ); SHA512_Update( &ctx, key, len); SHA512_Final( k0, &ctx); len = BINARY_SIZE; for(i=0;i<len;i++) { ipad[index][i] ^= k0[i]; opad[index][i] ^= k0[i]; } } else #endif /* PLAINTEXT_LENGTH > PAD_SIZE */ for(i=0;i<len;i++) { ipad[index][i] ^= key[i]; opad[index][i] ^= key[i]; } } static char *get_key(int index) { #if PLAINTEXT_LENGTH > PAD_SIZE return saved_plain[index]; #else unsigned int i; for(i=0;i<PLAINTEXT_LENGTH;i++) saved_plain[index][i] = ipad[index][ i ] ^ 0x36; saved_plain[index][i] = 0; return (char*) saved_plain[index]; #endif } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_key[index], BINARY_SIZE)) return 1; return 0; } static int cmp_exact(char *source, int count) { return (1); } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_key[index], BINARY_SIZE); } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { SHA512_CTX ctx; SHA512_Init( &ctx ); SHA512_Update( &ctx, ipad[index], PAD_SIZE ); SHA512_Update( &ctx, cursalt, strlen( (char*) cursalt) ); SHA512_Final( (unsigned char*) crypt_key[index], &ctx); SHA512_Init( &ctx ); SHA512_Update( &ctx, opad[index], PAD_SIZE ); SHA512_Update( &ctx, crypt_key[index], BINARY_SIZE); SHA512_Final( (unsigned char*) crypt_key[index], &ctx); } return count; } static void *binary(char *ciphertext) { static union toalign { unsigned char c[BINARY_SIZE]; ARCH_WORD_32 a[1]; } a; unsigned char *realcipher = a.c; int i,pos; for(i=strlen(ciphertext);ciphertext[i]!='#';i--); // allow # in salt pos=i+1; for(i=0;i<BINARY_SIZE;i++) realcipher[i] = atoi16[ARCH_INDEX(ciphertext[i*2+pos])]*16 + atoi16[ARCH_INDEX(ciphertext[i*2+1+pos])]; return (void*)realcipher; } static void *salt(char *ciphertext) { static unsigned char salt[SALT_SIZE]; memset(salt, 0, sizeof(salt)); // allow # in salt memcpy(salt, ciphertext, strrchr(ciphertext, '#') - ciphertext); return salt; } struct fmt_main fmt_hmacSHA512 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, binary, salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
sw-full-cs.c
/* $Id: sw-full-cs.c,v 1.15 2009/06/16 23:26:21 rumble Exp $ */ #include <assert.h> #include <ctype.h> #include <errno.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <zlib.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include "../common/util.h" #include "../common/fasta.h" #include "../common/sw-full-common.h" #include "../common/sw-full-cs.h" #include "../common/time_counter.h" typedef struct swcell { struct { int score_n; int score_w; int score_nw; int8_t back_n; int8_t back_w; int8_t back_nw; } from[4]; } swcell; #define FROM_A 0x00 #define FROM_B 0x01 #define FROM_C 0x02 #define FROM_D 0x03 #define FROM_NORTH_NORTH 0x01 #define FROM_NORTH_NORTHWEST 0x02 #define FROM_WEST_NORTHWEST 0x03 #define FROM_WEST_WEST 0x04 #define FROM_NORTHWEST_NORTH 0x05 #define FROM_NORTHWEST_NORTHWEST 0x06 #define FROM_NORTHWEST_WEST 0x07 #define FROM_x(_mat, _dir) (int8_t)(((_dir) << 2) | (_mat)) #define FROM_A_NORTH_NORTH FROM_x(FROM_A, FROM_NORTH_NORTH) #define FROM_A_NORTH_NORTHWEST FROM_x(FROM_A, FROM_NORTH_NORTHWEST) #define FROM_A_WEST_NORTHWEST FROM_x(FROM_A, FROM_WEST_NORTHWEST) #define FROM_A_WEST_WEST FROM_x(FROM_A, FROM_WEST_WEST) #define FROM_A_NORTHWEST_NORTH FROM_x(FROM_A, FROM_NORTHWEST_NORTH) #define FROM_A_NORTHWEST_NORTHWEST FROM_x(FROM_A, FROM_NORTHWEST_NORTHWEST) #define FROM_A_NORTHWEST_WEST FROM_x(FROM_A, FROM_NORTHWEST_WEST) #define FROM_B_NORTH_NORTH FROM_x(FROM_B, FROM_NORTH_NORTH) #define FROM_B_NORTH_NORTHWEST FROM_x(FROM_B, FROM_NORTH_NORTHWEST) #define FROM_B_WEST_NORTHWEST FROM_x(FROM_B, FROM_WEST_NORTHWEST) #define FROM_B_WEST_WEST FROM_x(FROM_B, FROM_WEST_WEST) #define FROM_B_NORTHWEST_NORTH FROM_x(FROM_B, FROM_NORTHWEST_NORTH) #define FROM_B_NORTHWEST_NORTHWEST FROM_x(FROM_B, FROM_NORTHWEST_NORTHWEST) #define FROM_B_NORTHWEST_WEST FROM_x(FROM_B, FROM_NORTHWEST_WEST) #define FROM_C_NORTH_NORTH FROM_x(FROM_C, FROM_NORTH_NORTH) #define FROM_C_NORTH_NORTHWEST FROM_x(FROM_C, FROM_NORTH_NORTHWEST) #define FROM_C_WEST_NORTHWEST FROM_x(FROM_C, FROM_WEST_NORTHWEST) #define FROM_C_WEST_WEST FROM_x(FROM_C, FROM_WEST_WEST) #define FROM_C_NORTHWEST_NORTH FROM_x(FROM_C, FROM_NORTHWEST_NORTH) #define FROM_C_NORTHWEST_NORTHWEST FROM_x(FROM_C, FROM_NORTHWEST_NORTHWEST) #define FROM_C_NORTHWEST_WEST FROM_x(FROM_C, FROM_NORTHWEST_WEST) #define FROM_D_NORTH_NORTH FROM_x(FROM_D, FROM_NORTH_NORTH) #define FROM_D_NORTH_NORTHWEST FROM_x(FROM_D, FROM_NORTH_NORTHWEST) #define FROM_D_WEST_NORTHWEST FROM_x(FROM_D, FROM_WEST_NORTHWEST) #define FROM_D_WEST_WEST FROM_x(FROM_D, FROM_WEST_WEST) #define FROM_D_NORTHWEST_NORTH FROM_x(FROM_D, FROM_NORTHWEST_NORTH) #define FROM_D_NORTHWEST_NORTHWEST FROM_x(FROM_D, FROM_NORTHWEST_NORTHWEST) #define FROM_D_NORTHWEST_WEST FROM_x(FROM_D, FROM_NORTHWEST_WEST) enum { BACK_INSERTION = 1, BACK_A_DELETION, BACK_B_DELETION, BACK_C_DELETION, BACK_D_DELETION, BACK_A_MATCH_MISMATCH, BACK_B_MATCH_MISMATCH, BACK_C_MATCH_MISMATCH, BACK_D_MATCH_MISMATCH }; static int initialised; static int8_t *db, *qr[4]; static int dblen, qrlen; static int a_gap_open, a_gap_ext, b_gap_open, b_gap_ext; static int match, mismatch; static int global_xover_penalty; static struct swcell *swmatrix; static uint8_t *backtrace; static char *dbalign, *qralign; static int anchor_width; static int indel_taboo_len; /* statistics */ static uint64_t swcells, swinvocs; static time_counter sw_tc; #pragma omp threadprivate(initialised,db,qr,dblen,qrlen,a_gap_open,a_gap_ext,b_gap_open,b_gap_ext,match,mismatch,global_xover_penalty,\ swmatrix,backtrace,dbalign,qralign,sw_tc,swcells,swinvocs,indel_taboo_len) #define BT_CROSSOVER 0x80 #define BT_CLIPPED 0xf0 #define BT_ISCROSSOVER(_x) ((_x) & BT_CROSSOVER) #define BT_TYPE(_x) ((_x) & 0x0f) #ifdef DEBUG_CROSSOVERS static int _glen; static int _rlen; #endif #ifdef DEBUG_SW static void print_sw(int lena, int lenb) { printf("len a %d, len b %d\n",lena,lenb); int k; for (k=0; k<4; k++) { int i,j; printf(" %5s ","-"); for (j=1; j< lena+1; j++) { printf("%5c ",base_translate(db[j-1],false)); } printf("\n"); //rows for (i=0; i<lenb+1; i++) { //cols if (i==0) { printf(" - "); } else { printf("%5c ",base_translate(qr[k][i-1],false)); } for (j=0; j<lena+1; j++) { swcell curr=swmatrix[i*(lena+1)+j]; int tmp=0; tmp=MAX(curr.from[k].score_n,curr.from[k].score_w); tmp=MAX(tmp,curr.from[k].score_nw); if (tmp<-99) { tmp=-99; } printf("%5d ",tmp); } printf("\n"); } } } #endif /* static void print_sw_backtrace(int lena, int lenb) { int i,j; printf(" %5s ","-"); for (j=1; j< lenb+1; j++) { printf("%5c ",base_translate(qr[j-1],false)); } printf("\n"); //rows for (i=0; i<lena+1; i++) { //cols if (i==0) { printf(" - "); } else { printf("%5c ",base_translate(db[i-1],false)); } for (j=0; j<lenb+1; j++) { swcell curr=swmatrix[j*(lena+1)+i]; int btrace[3]={0,0,0}; int maxscore=0; maxscore=MAX(curr.score_north,curr.score_west); maxscore=MAX(maxscore,curr.score_northwest); if (curr.score_west==maxscore) { btrace[0]=curr.back_west; } if (curr.score_northwest==maxscore) { btrace[1]=curr.back_northwest; } if (curr.score_north==maxscore) { btrace[2]=curr.back_north; } printf("%d/%d/%d ",btrace[0],btrace[1],btrace[2]); 1} printf("\n"); } }*/ inline static void init_cell(int idx, int local_alignment, int xover_penalty) { if (local_alignment) { swmatrix[idx].from[0].score_nw = 0; swmatrix[idx].from[0].score_n = -b_gap_open; swmatrix[idx].from[0].score_w = -a_gap_open; swmatrix[idx].from[1].score_nw = xover_penalty; swmatrix[idx].from[1].score_n = -b_gap_open + xover_penalty; swmatrix[idx].from[1].score_w = -a_gap_open + xover_penalty; swmatrix[idx].from[2].score_nw = xover_penalty; swmatrix[idx].from[2].score_n = -b_gap_open + xover_penalty; swmatrix[idx].from[2].score_w = -a_gap_open + xover_penalty; swmatrix[idx].from[3].score_nw = xover_penalty; swmatrix[idx].from[3].score_n = -b_gap_open + xover_penalty; swmatrix[idx].from[3].score_w = -a_gap_open + xover_penalty; } else { swmatrix[idx].from[0].score_nw = -INT_MAX/2; swmatrix[idx].from[0].score_n = -INT_MAX/2; swmatrix[idx].from[0].score_w = -INT_MAX/2; swmatrix[idx].from[1].score_nw = -INT_MAX/2; swmatrix[idx].from[1].score_n = -INT_MAX/2; swmatrix[idx].from[1].score_w = -INT_MAX/2; swmatrix[idx].from[2].score_nw = -INT_MAX/2; swmatrix[idx].from[2].score_n = -INT_MAX/2; swmatrix[idx].from[2].score_w = -INT_MAX/2; swmatrix[idx].from[3].score_nw = -INT_MAX/2; swmatrix[idx].from[3].score_n = -INT_MAX/2; swmatrix[idx].from[3].score_w = -INT_MAX/2; } swmatrix[idx].from[0].back_nw = 0; swmatrix[idx].from[0].back_n = 0; swmatrix[idx].from[0].back_w = 0; swmatrix[idx].from[1].back_nw = 0; swmatrix[idx].from[1].back_n = 0; swmatrix[idx].from[1].back_w = 0; swmatrix[idx].from[2].back_nw = 0; swmatrix[idx].from[2].back_n = 0; swmatrix[idx].from[2].back_w = 0; swmatrix[idx].from[3].back_nw = 0; swmatrix[idx].from[3].back_n = 0; swmatrix[idx].from[3].back_w = 0; } /* * Perform a full Smith-Waterman alignment. For the colour case, this means * computing each possible letter space read string and doing a four layer * scan. */ //lena - genome length static int full_sw(int lena, int lenb, int threshscore, int *iret, int *jret, int *kret, bool revcmpl, struct anchor * anchors, int anchors_cnt, int local_alignment, int * crossover_score) { int i, j, k, l, max_i, max_j, max_k; int score, ms, tmp, resetval, xover_penalty; //int go, ge; //int sw_band, ne_band; int8_t tmp2; struct anchor rectangle; /* shut up gcc */ max_i = max_j = max_k = j = 0; score = 0; //go = gap_open; //ge = gap_ext; for (j = 0; j < lena + 1; j++) { init_cell(j, 1, global_xover_penalty); } //for (j = 0; j < lenb + 1; j++) { //init_cell(j * (lena + 1)); //} /* * Figure out our band. * We can actually skip computation of a significant number of * cells, which could never be part of an alignment corresponding * to our threshhold score. */ //sw_band = ((lenb * match - threshscore + match - 1) / match) + 1; //ne_band = lena - (lenb - sw_band); if (anchors != NULL && anchor_width >= 0) { anchor_join(anchors, anchors_cnt, &rectangle); anchor_widen(&rectangle, anchor_width); } else { struct anchor tmp_anchors[2]; tmp_anchors[0].x = 0; tmp_anchors[0].y = (lenb * match - threshscore) / match; tmp_anchors[0].length = 1; tmp_anchors[0].width = 1; tmp_anchors[1].x = lena - 1; tmp_anchors[1].y = lenb - 1 - tmp_anchors[0].y; tmp_anchors[1].length = 1; tmp_anchors[1].width = 1; anchor_join(tmp_anchors, 2, &rectangle); } for (i = 0; i < lenb; i++) { /* * computing row i of virtual matrix, stored in row i+1 */ int x_min, x_max; xover_penalty = (crossover_score == NULL? global_xover_penalty : crossover_score[i]); anchor_get_x_range(&rectangle, lena, lenb, i, &x_min, &x_max); if (!local_alignment) { //x_max=MIN(lena,x_max); x_min=MAX(0,x_min-lenb/40); //init_cell(i * (lena + 1) + x_max + 1, 0); //init_cell((i + 1) * (lena + 1) + (x_min - 1) + 1, x_min == 0 ? 1 : 0); init_cell((i + 1) * (lena + 1) + (x_min - 1) + 1, 0, xover_penalty); } else { init_cell((i + 1) * (lena + 1) + (x_min - 1) + 1, 1, xover_penalty); } //if (x_min > 0) { //fprintf(stderr,"INIT cell %d , %d, %d\n",i+1, (x_min-1)+1,x_max); //} swcells += x_max - x_min + 1; for (j = x_min; j <= x_max; j++) { /* * computing column j of virtual matrix, stored in column j+1 */ struct swcell *cell_nw, *cell_n, *cell_w, *cell_cur; cell_nw = &swmatrix[i * (lena + 1) + j]; cell_n = cell_nw + 1; cell_w = cell_nw + (lena + 1); cell_cur = cell_w + 1; /* banding */ //if (i >= sw_band + j) { //memset(cell_cur, 0, sizeof(*cell_cur)); //continue; //} //if (j >= ne_band + i) { //memset(cell_cur, 0, sizeof(*cell_cur)); //break; //} for (k = 0; k < 4; k++) { if (k != 0) resetval = xover_penalty; else resetval = 0; /* * northwest */ if (db[j] == BASE_N || qr[k][i] == BASE_N) ms = 0; else ms = (db[j] == qr[k][i]) ? match : mismatch; if (!revcmpl) { tmp = cell_nw->from[k].score_nw + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_NORTHWEST); // end of an insertion: not in taboo zone if (i < lenb - indel_taboo_len && cell_nw->from[k].score_n + ms > tmp) { tmp = cell_nw->from[k].score_n + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_NORTH); } // end of a deletion if (cell_nw->from[k].score_w + ms > tmp) { tmp = cell_nw->from[k].score_w + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_WEST); } } else { //end of a deletion tmp = cell_nw->from[k].score_w + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_WEST); //end of an insertion: not in taboo zone if (i < lenb - indel_taboo_len && cell_nw->from[k].score_n + ms > tmp) { tmp = cell_nw->from[k].score_n + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_NORTH); } if (cell_nw->from[k].score_nw + ms > tmp) { tmp = cell_nw->from[k].score_nw + ms; tmp2 = FROM_x(k, FROM_NORTHWEST_NORTHWEST); } } /* check neighbours */ for (l = 0; l < 4; l++) { if (l == k) continue; if (!revcmpl) { /* northwest */ if (cell_nw->from[l].score_nw + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_nw + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_NORTHWEST); } /* north */ // end of insertion, not in taboo zone if (i < lenb - indel_taboo_len && cell_nw->from[l].score_n + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_n + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_NORTH); } /* west */ if (cell_nw->from[l].score_w + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_w + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_WEST); } } else { /* west */ if (cell_nw->from[l].score_w + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_w + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_WEST); } /* north */ // end of insertion, not in taboo zone if (i < lenb - indel_taboo_len && cell_nw->from[l].score_n + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_n + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_NORTH); } /* northwest */ if (cell_nw->from[l].score_nw + ms + xover_penalty > tmp) { tmp = cell_nw->from[l].score_nw + ms + xover_penalty; tmp2 = FROM_x(l, FROM_NORTHWEST_NORTHWEST); } } } if (tmp <= resetval && local_alignment) { tmp = resetval; tmp2 = 0; } cell_cur->from[k].score_nw = tmp; cell_cur->from[k].back_nw = tmp2; /* * north */ if (!revcmpl) { // insertion start tmp = cell_n->from[k].score_nw - b_gap_open - b_gap_ext; tmp2 = FROM_x(k, FROM_NORTH_NORTHWEST); if (!(i < lenb - indel_taboo_len) || cell_n->from[k].score_n - b_gap_ext > tmp) { tmp = cell_n->from[k].score_n - b_gap_ext; tmp2 = FROM_x(k, FROM_NORTH_NORTH); } } else { tmp = cell_n->from[k].score_n - b_gap_ext; tmp2 = FROM_x(k, FROM_NORTH_NORTH); // insertion start if (i < lenb - indel_taboo_len && cell_n->from[k].score_nw - b_gap_open - b_gap_ext > tmp) { tmp = cell_n->from[k].score_nw - b_gap_open - b_gap_ext; tmp2 = FROM_x(k, FROM_NORTH_NORTHWEST); } } /* check neighbours */ for (l = 0; l < 4; l++) { if (l == k) continue; if (!revcmpl) { /* northwest */ // insertion start if (i < lenb - indel_taboo_len && cell_n->from[l].score_nw - b_gap_open - b_gap_ext + xover_penalty > tmp) { tmp = cell_n->from[l].score_nw - b_gap_open - b_gap_ext + xover_penalty; tmp2 = FROM_x(l, FROM_NORTH_NORTHWEST); } /* north */ if (cell_n->from[l].score_n - b_gap_ext + xover_penalty > tmp) { tmp = cell_n->from[l].score_n - b_gap_ext + xover_penalty; tmp2 = FROM_x(l, FROM_NORTH_NORTH); } } else { /* north */ if (cell_n->from[l].score_n - b_gap_ext + xover_penalty > tmp) { tmp = cell_n->from[l].score_n - b_gap_ext + xover_penalty; tmp2 = FROM_x(l, FROM_NORTH_NORTH); } /* northwest */ // insertion start if (i < lenb - indel_taboo_len && cell_n->from[l].score_nw - b_gap_open - b_gap_ext + xover_penalty > tmp) { tmp = cell_n->from[l].score_nw - b_gap_open - b_gap_ext + xover_penalty; tmp2 = FROM_x(l, FROM_NORTH_NORTHWEST); } } } if (tmp <= resetval && local_alignment) { tmp = resetval; tmp2 = 0; } cell_cur->from[k].score_n = tmp; cell_cur->from[k].back_n = tmp2; /* * west */ if (!revcmpl) { // deletion start tmp = cell_w->from[k].score_nw - a_gap_open - a_gap_ext; tmp2 = FROM_x(k, FROM_WEST_NORTHWEST); if (!(i < lenb - indel_taboo_len) || cell_w->from[k].score_w - a_gap_ext > tmp) { tmp = cell_w->from[k].score_w - a_gap_ext; tmp2 = FROM_x(k, FROM_WEST_WEST); } } else { tmp = cell_w->from[k].score_w - a_gap_ext; tmp2 = FROM_x(k, FROM_WEST_WEST); // deletion start if (i < lenb - indel_taboo_len && cell_w->from[k].score_nw - a_gap_open - a_gap_ext > tmp) { tmp = cell_w->from[k].score_nw - a_gap_open - a_gap_ext; tmp2 = FROM_x(k, FROM_WEST_NORTHWEST); } } /* * NB: It doesn't make sense to cross over on a * genomic gap, so we won't. */ if (tmp <= resetval && local_alignment) { tmp = resetval; tmp2 = 0; } cell_cur->from[k].score_w = tmp; cell_cur->from[k].back_w = tmp2; /* * max score */ if (local_alignment || i==lenb-1) { if (!revcmpl) { if (cell_cur->from[k].score_nw > score) { score = cell_cur->from[k].score_nw; max_i = i, max_j = j, max_k = k; } if (cell_cur->from[k].score_n > score) { score = cell_cur->from[k].score_n; max_i = i, max_j = j, max_k = k; } if (cell_cur->from[k].score_w > score) { score = cell_cur->from[k].score_w; max_i = i, max_j = j, max_k = k; } } else { if (cell_cur->from[k].score_w > score) { score = cell_cur->from[k].score_w; max_i = i, max_j = j, max_k = k; } if (cell_cur->from[k].score_n > score) { score = cell_cur->from[k].score_n; max_i = i, max_j = j, max_k = k; } if (cell_cur->from[k].score_nw > score) { score = cell_cur->from[k].score_nw; max_i = i, max_j = j, max_k = k; } } } #ifdef DEBUG_SW fprintf(stderr, "i:%d j:%d k:%d score_nw:%d [%u,%s] score_n:%d [%u,%s] score_w:%d [%u,%s] xover_penalty:%d\n", i+1, j+1, k, cell_cur->from[k].score_nw, cell_cur->from[k].back_nw & 0x3, (cell_cur->from[k].back_nw >> 2 == 0 ? "!" : (cell_cur->from[k].back_nw >> 2 == FROM_NORTHWEST_NORTH ? "n" : (cell_cur->from[k].back_nw >> 2 == FROM_NORTHWEST_NORTHWEST ? "nw" : "w"))), cell_cur->from[k].score_n, cell_cur->from[k].back_n & 0x3, (cell_cur->from[k].back_n >> 2 == 0 ? "!" : (cell_cur->from[k].back_n >> 2 == FROM_NORTH_NORTH ? "n" : "nw")), cell_cur->from[k].score_w, cell_cur->from[k].back_w & 0x3, (cell_cur->from[k].back_w >> 2 == 0 ? "!" : (cell_cur->from[k].back_w >> 2 == FROM_WEST_NORTHWEST ? "nw" : "w")), xover_penalty); #endif } } if (i+1 < lenb) { int next_x_min, next_x_max; anchor_get_x_range(&rectangle, lena, lenb, i+1, &next_x_min, &next_x_max); for (j = x_max + 1; j <= next_x_max; j++) { //fprintf(stderr,"Init cell %d , , %d\n",i+1,j+1); init_cell((i + 1) * (lena + 1) + (j + 1), local_alignment, xover_penalty); // still xover on i-th color } } } #ifdef DEBUG_SW fprintf(stderr, "max_i:%d max_j:%d max_k:%d\n", max_i+1, max_j+1, max_k); #endif *iret = max_i; *jret = max_j; *kret = max_k; //print_sw(lena,lenb); return (score); } /* * Fill in the backtrace in order to do a pretty printout. * * Returns the beginning matrix cell (i, j) in 'sfr->read_start' and * 'sfr->genome_start'. * * The return value is the first valid offset in the backtrace buffer. */ static int do_backtrace(int lena, int i, int j, int k, struct sw_full_results *sfr) { struct swcell *cell; int off, from, fromscore; off = (dblen + qrlen) - 1; cell = &swmatrix[(i + 1) * (lena + 1) + j + 1]; from = cell->from[k].back_nw; fromscore = cell->from[k].score_nw; if (cell->from[k].score_w > fromscore) { from = cell->from[k].back_w; fromscore = cell->from[k].score_w; } if (cell->from[k].score_n > fromscore) from = cell->from[k].back_n; if (from == 0) { int l, base; fprintf(stderr, "Assertion failed.\nQr:"); for (l = 1, base = qr[0][0]; l < qrlen; l++) { fprintf(stderr, "%d", lstocs(base, qr[0][l], false)); base = qr[0][l]; } fprintf(stderr, "\n"); } assert(from != 0); /* fill out the backtrace */ while (i >= 0 && j >= 0) { //printf("i %d, j %d\n",i,j); assert(off >= 0); cell = NULL; /* common operations first */ switch (from) { case FROM_A_NORTH_NORTH: case FROM_A_NORTH_NORTHWEST: case FROM_B_NORTH_NORTH: case FROM_B_NORTH_NORTHWEST: case FROM_C_NORTH_NORTH: case FROM_C_NORTH_NORTHWEST: case FROM_D_NORTH_NORTH: case FROM_D_NORTH_NORTHWEST: sfr->deletions++; sfr->read_start = i--; break; case FROM_A_WEST_WEST: case FROM_A_WEST_NORTHWEST: case FROM_B_WEST_WEST: case FROM_B_WEST_NORTHWEST: case FROM_C_WEST_WEST: case FROM_C_WEST_NORTHWEST: case FROM_D_WEST_WEST: case FROM_D_WEST_NORTHWEST: sfr->insertions++; sfr->genome_start = j--; break; case FROM_A_NORTHWEST_NORTH: case FROM_A_NORTHWEST_NORTHWEST: case FROM_A_NORTHWEST_WEST: case FROM_B_NORTHWEST_NORTH: case FROM_B_NORTHWEST_NORTHWEST: case FROM_B_NORTHWEST_WEST: case FROM_C_NORTHWEST_NORTH: case FROM_C_NORTHWEST_NORTHWEST: case FROM_C_NORTHWEST_WEST: case FROM_D_NORTHWEST_NORTH: case FROM_D_NORTHWEST_NORTHWEST: case FROM_D_NORTHWEST_WEST: if (db[j] == qr[k][i] || db[j] == BASE_N || qr[k][i] == BASE_N) sfr->matches++; else sfr->mismatches++; sfr->read_start = i--; sfr->genome_start = j--; break; default: fprintf(stderr, "INTERNAL ERROR: from = %d\n", from); assert(0); } /* handle match/mismatch and north */ switch (from) { case FROM_A_NORTH_NORTH: case FROM_A_NORTH_NORTHWEST: case FROM_B_NORTH_NORTH: case FROM_B_NORTH_NORTHWEST: case FROM_C_NORTH_NORTH: case FROM_C_NORTH_NORTHWEST: case FROM_D_NORTH_NORTH: case FROM_D_NORTH_NORTHWEST: switch(k) { case 0: backtrace[off]= BACK_A_DELETION; break; case 1: backtrace[off]= BACK_B_DELETION; break; case 2: backtrace[off]= BACK_C_DELETION; break; case 3: backtrace[off]= BACK_D_DELETION; break; default: fprintf(stderr, "INTERNAL ERROR: k = %d\n", k); assert(0); } break; case FROM_A_WEST_WEST: case FROM_A_WEST_NORTHWEST: case FROM_B_WEST_WEST: case FROM_B_WEST_NORTHWEST: case FROM_C_WEST_WEST: case FROM_C_WEST_NORTHWEST: case FROM_D_WEST_WEST: case FROM_D_WEST_NORTHWEST: /* doesn't make sense to cross over on a genomic gap */ backtrace[off] = BACK_INSERTION; break; case FROM_A_NORTHWEST_NORTH: case FROM_A_NORTHWEST_NORTHWEST: case FROM_A_NORTHWEST_WEST: case FROM_B_NORTHWEST_NORTH: case FROM_B_NORTHWEST_NORTHWEST: case FROM_B_NORTHWEST_WEST: case FROM_C_NORTHWEST_NORTH: case FROM_C_NORTHWEST_NORTHWEST: case FROM_C_NORTHWEST_WEST: case FROM_D_NORTHWEST_NORTH: case FROM_D_NORTHWEST_NORTHWEST: case FROM_D_NORTHWEST_WEST: switch(k) { case 0: backtrace[off] = BACK_A_MATCH_MISMATCH; break; case 1: backtrace[off] = BACK_B_MATCH_MISMATCH; break; case 2: backtrace[off] = BACK_C_MATCH_MISMATCH; break; case 3: backtrace[off] = BACK_D_MATCH_MISMATCH; break; default: fprintf(stderr, "INTERNAL ERROR: k = %d\n", k); assert(0); } break; default: fprintf(stderr, "INTERNAL ERROR: from = %d\n", from); assert(0); } /* set k */ switch (from) { case FROM_A_NORTH_NORTH: case FROM_A_NORTH_NORTHWEST: case FROM_A_WEST_WEST: case FROM_A_WEST_NORTHWEST: case FROM_A_NORTHWEST_NORTH: case FROM_A_NORTHWEST_NORTHWEST: case FROM_A_NORTHWEST_WEST: if (k != 0) { backtrace[off] |= BT_CROSSOVER; sfr->crossovers++; k = 0; } break; case FROM_B_NORTH_NORTH: case FROM_B_NORTH_NORTHWEST: case FROM_B_WEST_WEST: case FROM_B_WEST_NORTHWEST: case FROM_B_NORTHWEST_NORTH: case FROM_B_NORTHWEST_NORTHWEST: case FROM_B_NORTHWEST_WEST: if (k != 1) { backtrace[off] |= BT_CROSSOVER; sfr->crossovers++; k = 1; } break; case FROM_C_NORTH_NORTH: case FROM_C_NORTH_NORTHWEST: case FROM_C_WEST_WEST: case FROM_C_WEST_NORTHWEST: case FROM_C_NORTHWEST_NORTH: case FROM_C_NORTHWEST_NORTHWEST: case FROM_C_NORTHWEST_WEST: if (k != 2) { backtrace[off] |= BT_CROSSOVER; sfr->crossovers++; k = 2; } break; case FROM_D_NORTH_NORTH: case FROM_D_NORTH_NORTHWEST: case FROM_D_WEST_WEST: case FROM_D_WEST_NORTHWEST: case FROM_D_NORTHWEST_NORTH: case FROM_D_NORTHWEST_NORTHWEST: case FROM_D_NORTHWEST_WEST: if (k != 3) { backtrace[off] |= BT_CROSSOVER; sfr->crossovers++; k = 3; } break; default: fprintf(stderr, "INTERNAL ERROR: from = %d\n", from); assert(0); } /* * Continue backtrace (nb: i,j and k have already been changed). */ cell = &swmatrix[(i + 1) * (lena + 1) + j + 1]; switch (from) { case FROM_A_NORTH_NORTH: case FROM_B_NORTH_NORTH: case FROM_C_NORTH_NORTH: case FROM_D_NORTH_NORTH: from = cell->from[k].back_n; break; case FROM_A_NORTH_NORTHWEST: case FROM_B_NORTH_NORTHWEST: case FROM_C_NORTH_NORTHWEST: case FROM_D_NORTH_NORTHWEST: from = cell->from[k].back_nw; break; case FROM_A_WEST_WEST: case FROM_B_WEST_WEST: case FROM_C_WEST_WEST: case FROM_D_WEST_WEST: from = cell->from[k].back_w; break; case FROM_A_WEST_NORTHWEST: case FROM_B_WEST_NORTHWEST: case FROM_C_WEST_NORTHWEST: case FROM_D_WEST_NORTHWEST: from = cell->from[k].back_nw; break; case FROM_A_NORTHWEST_NORTH: case FROM_B_NORTHWEST_NORTH: case FROM_C_NORTHWEST_NORTH: case FROM_D_NORTHWEST_NORTH: from = cell->from[k].back_n; break; case FROM_A_NORTHWEST_NORTHWEST: case FROM_B_NORTHWEST_NORTHWEST: case FROM_C_NORTHWEST_NORTHWEST: case FROM_D_NORTHWEST_NORTHWEST: from = cell->from[k].back_nw; break; case FROM_A_NORTHWEST_WEST: case FROM_B_NORTHWEST_WEST: case FROM_C_NORTHWEST_WEST: case FROM_D_NORTHWEST_WEST: from = cell->from[k].back_w; break; default: fprintf(stderr, "INTERNAL ERROR: from = %d\n", from); assert(0); } off--; if (from == 0) break; } off++; if (k != 0) { backtrace[off] |= BT_CROSSOVER; sfr->crossovers++; } return (off); } /* * Pretty print our alignment of 'db' and 'qr' in 'dbalign' and 'qralign'. * * i, j represent the beginning cell in the matrix. * k is the first valid offset in the backtrace buffer. */ static void pretty_print(int i, int j, int k) { char *d, *q; int l; d = dbalign; q = qralign; for (l = k; l < (dblen + qrlen); l++) { #ifdef DEBUG_CROSSOVERS int a; if (BT_ISCROSSOVER(backtrace[l]) && (BT_TYPE(backtrace[l]) == BACK_A_DELETION || BT_TYPE(backtrace[l]) == BACK_B_DELETION || BT_TYPE(backtrace[l]) == BACK_C_DELETION || BT_TYPE(backtrace[l]) == BACK_D_DELETION)) { fprintf(stderr, "sw-full-cs: crossover in \"deletion\" (really, insertion):\n"); fprintf(stderr, "db:"); for (a = 0; a < _glen; a++) fprintf(stderr, "%c", base_translate(db[a], false)); fprintf(stderr, "\n"); fprintf(stderr, "qr[0]:"); for (a = 0; a < _rlen; a++) fprintf(stderr, "%c", base_translate(qr[0][a], false)); fprintf(stderr, "\n"); } #endif switch (BT_TYPE(backtrace[l])) { case BACK_A_DELETION: *d++ = '-'; if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[0][i++], false)); else *q++ = base_translate(qr[0][i++], false); break; case BACK_B_DELETION: *d++ = '-'; if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[1][i++], false)); else *q++ = base_translate(qr[1][i++], false); break; case BACK_C_DELETION: *d++ = '-'; if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[2][i++], false)); else *q++ = base_translate(qr[2][i++], false); break; case BACK_D_DELETION: *d++ = '-'; if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[3][i++], false)); else *q++ = base_translate(qr[3][i++], false); break; case BACK_INSERTION: *d++ = base_translate(db[j++], false); *q++ = '-'; break; case BACK_A_MATCH_MISMATCH: *d++ = base_translate(db[j++], false); if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[0][i++], false)); else *q++ = base_translate(qr[0][i++], false); break; case BACK_B_MATCH_MISMATCH: *d++ = base_translate(db[j++], false); if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[1][i++], false)); else *q++ = base_translate(qr[1][i++], false); break; case BACK_C_MATCH_MISMATCH: *d++ = base_translate(db[j++], false); if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[2][i++], false)); else *q++ = base_translate(qr[2][i++], false); break; case BACK_D_MATCH_MISMATCH: *d++ = base_translate(db[j++], false); if (BT_ISCROSSOVER(backtrace[l])) *q++ = (char)tolower((int)base_translate(qr[3][i++], false)); else *q++ = base_translate(qr[3][i++], false); break; default: fprintf(stderr, "INTERNAL ERROR: backtrace[l] = 0x%x\n", backtrace[l]); assert(0); } if ((BT_TYPE(backtrace[l]) == BACK_A_MATCH_MISMATCH || BT_TYPE(backtrace[l]) == BACK_B_MATCH_MISMATCH || BT_TYPE(backtrace[l]) == BACK_C_MATCH_MISMATCH || BT_TYPE(backtrace[l]) == BACK_D_MATCH_MISMATCH) && (*(q-1) == 'n' || *(q-1) == 'N')) { if (BT_ISCROSSOVER(backtrace[l])) *(q-1) = (char)tolower(*(d-1)); else *(q-1) = *(d-1); } } *d = *q = '\0'; } int sw_full_cs_cleanup(void) { free(db); int i; for (i=0; i<4; i++) { free(qr[i]); } free(swmatrix); free(backtrace); free(dbalign); free(qralign); return 0; } int sw_full_cs_setup(int _dblen, int _qrlen, int _a_gap_open, int _a_gap_ext, int _b_gap_open, int _b_gap_ext, int _match, int _mismatch, int _global_xover_penalty, bool reset_stats, int _anchor_width, int _indel_taboo_len) { int i; dblen = _dblen; db = (int8_t *)malloc(dblen * sizeof(db[0])); if (db == NULL) return (1); qrlen = _qrlen; for (i = 0; i < 4; i++) { qr[i] = (int8_t *)malloc(qrlen * sizeof(qr[0])); if (qr[i] == NULL) return (1); } swmatrix = (struct swcell *)malloc((dblen + 1) * (qrlen + 1) * sizeof(swmatrix[0])); if (swmatrix == NULL) return (1); backtrace = (uint8_t *)malloc((dblen + qrlen) * sizeof(backtrace[0])); if (backtrace == NULL) return (1); dbalign = (char *)malloc((dblen + qrlen + 1) * sizeof(dbalign[0])); if (dbalign == NULL) return (1); qralign = (char *)malloc((dblen + qrlen + 1) * sizeof(dbalign[0])); if (qralign == NULL) return (1); a_gap_open = -(_a_gap_open); a_gap_ext = -(_a_gap_ext); b_gap_open = -(_b_gap_open); b_gap_ext = -(_b_gap_ext); match = _match; mismatch = _mismatch; global_xover_penalty = _global_xover_penalty; if (reset_stats) { swcells = swinvocs = 0; sw_tc.type = DEF_FAST_TIME_COUNTER; sw_tc.counter = 0; } anchor_width = _anchor_width; indel_taboo_len = _indel_taboo_len; initialised = 1; return (0); } void sw_full_cs_stats(uint64_t *invocs, uint64_t *cells, double *secs) { if (invocs != NULL) *invocs = swinvocs; if (cells != NULL) *cells = swcells; if (secs != NULL) *secs = time_counter_get_secs(&sw_tc); } void sw_full_cs(uint32_t *genome_ls, int goff, int glen, uint32_t *read, int rlen, int initbp, int threshscore, struct sw_full_results *sfr, bool revcmpl, bool is_rna, struct anchor * anchors, int anchors_cnt, int local_alignment, int * crossover_score) { struct sw_full_results scratch; int i, j, k; //llint before = rdtsc(), after; TIME_COUNTER_START(sw_tc); if (!initialised) abort(); swinvocs++; assert(glen > 0 && glen <= dblen); assert(rlen > 0 && rlen <= qrlen); if (sfr == NULL) { sfr = &scratch; memset(sfr, 0, sizeof(*sfr)); } memset(backtrace, 0, (dblen + qrlen) * sizeof(backtrace[0])); dbalign[0] = qralign[0] = '\0'; for (i = 0; i < glen; i++) db[i] = (int8_t)EXTRACT(genome_ls, goff + i); /* * Generate each possible letter space sequence from the colour space * read. qr[0] corresponds to initbp, which is given initial preference. */ assert(initbp >= 0 && initbp <= 3); for (i = 0; i < 4; i++) { int letter = (i + initbp) % 4; for (j = 0; j < rlen; j++) { int base = EXTRACT(read, j); if (base == BASE_N || base == BASE_X) { qr[i][j] = BASE_N; letter = (i + initbp) % 4; } else { qr[i][j] = (int8_t)cstols(letter, base, is_rna); letter = qr[i][j]; } } } #ifdef DEBUG_SW fprintf(stderr, "db: "); for (j = 0; j < glen; j++) fprintf(stderr, "%c", base_translate(db[j], false)); fprintf(stderr, "\n"); for (i = 0; i < 4; i++) { fprintf(stderr, "qr[%u]: ", i); for (j = 0; j < rlen; j++) fprintf(stderr, "%c", base_translate(qr[i][j], false)); fprintf(stderr, "\n"); } #endif #ifdef DEBUG_CROSSOVERS _glen = glen; _rlen = rlen; #endif sfr->score = full_sw(glen, rlen, threshscore, &i, &j, &k, revcmpl, anchors, anchors_cnt, local_alignment, crossover_score); if (sfr->score >= 0 && sfr->score >= threshscore) { k = do_backtrace(glen, i, j, k, sfr); pretty_print(sfr->read_start, sfr->genome_start, k); sfr->gmapped = j - sfr->genome_start + 1; sfr->genome_start += goff; sfr->rmapped = i - sfr->read_start + 1; sfr->dbalign = xstrdup(dbalign); sfr->qralign = xstrdup(qralign); } else { sfr->score = 0; } #ifdef DEBUG_SW fprintf(stderr, "reported alignment:\n\t%s\n\t%s\n", sfr->dbalign, sfr->qralign); #endif //swcells += (glen * rlen); //after = rdtsc(); //swticks += MAX(after - before, 0); TIME_COUNTER_STOP(sw_tc); }
cartesiangrid.h
#ifndef GRIDGENERATOR_CARTESIANGRID_H #define GRIDGENERATOR_CARTESIANGRID_H #include <gcem.hpp> #include <common/surface.h> #include <set> #include <sfcmm_common.h> #include "cartesiangrid_base.h" #include "common/configuration.h" #include "common/IO.h" #include "geometry.h" #include "globaltimers.h" #ifdef SOLVER_AVAILABLE #include "gridgenerator/cartesiangrid_generation.h" #include "lbm/constants.h" #else #include "cartesiangrid_generation.h" #endif #include "interface/grid_interface.h" template <Debug_Level DEBUG_LEVEL, GInt NDIM> class CartesianGrid : public BaseCartesianGrid<DEBUG_LEVEL, NDIM>, private Configuration { public: /// Underlying enum type for property access using Cell = CellProperties; /// Underlying bitset type for property storage using PropertyBitsetType = grid::cell::BitsetType; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::checkBounds; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::property; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::size; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::noCells; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::empty; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::lengthOnLvl; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::hasParent; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::parent; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::capacity; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::level; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::globalId; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::center; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::checkDir; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::currentHighestLvl; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::partitionLvl; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::setMaxLvl; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::boundingBox; using BaseCartesianGrid<DEBUG_LEVEL, NDIM>::setBoundingBox; CartesianGrid() = default; ~CartesianGrid() override = default; CartesianGrid(const CartesianGrid&) = delete; CartesianGrid(CartesianGrid&&) = delete; auto operator=(const CartesianGrid&) -> CartesianGrid& = delete; auto operator=(CartesianGrid&&) -> CartesianGrid& = delete; inline auto child(const GInt id, const GInt pos) -> GInt& { if(DEBUG_LEVEL >= Debug_Level::debug) { checkChildPos(pos); checkBounds(id); return m_childIds.at(id * cartesian::maxNoChildren<NDIM>() + pos); } // no bound checking return m_childIds[id * cartesian::maxNoChildren<NDIM>() + pos]; } [[nodiscard]] inline auto child(const GInt id, const GInt pos) const -> GInt { if(DEBUG_LEVEL >= Debug_Level::debug) { checkChildPos(pos); checkBounds(id); return m_childIds.at(id * cartesian::maxNoChildren<NDIM>() + pos); } // no bound checking return m_childIds[id * cartesian::maxNoChildren<NDIM>() + pos]; } [[nodiscard]] inline auto hasChild(const GInt id, const GInt pos) const -> GBool { if(DEBUG_LEVEL >= Debug_Level::debug) { checkChildPos(pos); checkBounds(id); return m_childIds.at(id * cartesian::maxNoChildren<NDIM>() + pos) > -1; } // no bound checking return m_childIds[id * cartesian::maxNoChildren<NDIM>() + pos] > -1; } [[nodiscard]] inline auto hasChildren(const GInt id) const -> GBool { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); } return noChildren(id) > 0; } [[nodiscard]] inline auto noChildren(const GInt id) const -> GInt { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); } return std::count_if(&m_childIds[id * cartesian::maxNoChildren<NDIM>() + 0], &m_childIds[id * cartesian::maxNoChildren<NDIM>() + cartesian::maxNoChildren<NDIM>()], [](const GInt childId) { return childId > -1; }); } // Neighbors inline auto neighbor() const -> const auto& { return m_nghbrIds; } // todo: make diagonal neighbors a template parameter [[nodiscard]] inline auto neighbor(const GInt id, const GInt dir) const -> GInt override { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); // checkDir(dir); if(m_diagonalNghbrs) { return m_nghbrIds.at(id * cartesian::maxNoNghbrsDiag<NDIM>() + dir); } return m_nghbrIds.at(id * cartesian::maxNoNghbrs<NDIM>() + dir); } if(m_diagonalNghbrs) { return m_nghbrIds[id * cartesian::maxNoNghbrsDiag<NDIM>() + dir]; } return m_nghbrIds[id * cartesian::maxNoNghbrs<NDIM>() + dir]; } inline auto neighbor(const GInt id, const GInt dir) -> GInt& { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); // checkDir(dir); if(m_diagonalNghbrs) { return m_nghbrIds.at(id * cartesian::maxNoNghbrsDiag<NDIM>() + dir); } return m_nghbrIds.at(id * cartesian::maxNoNghbrs<NDIM>() + dir); } if(m_diagonalNghbrs) { return m_nghbrIds[id * cartesian::maxNoNghbrsDiag<NDIM>() + dir]; } return m_nghbrIds[id * cartesian::maxNoNghbrs<NDIM>() + dir]; } [[nodiscard]] inline auto hasNeighbor(const GInt id, const GInt dir) const -> GBool { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); checkDir(dir); if(m_diagonalNghbrs) { return m_nghbrIds.at(id * cartesian::maxNoNghbrsDiag<NDIM>() + dir) != INVALID_CELLID; } return m_nghbrIds.at(id * cartesian::maxNoNghbrs<NDIM>() + dir) != INVALID_CELLID; } if(m_diagonalNghbrs) { return m_nghbrIds[id * cartesian::maxNoNghbrsDiag<NDIM>() + dir] != INVALID_CELLID; } return m_nghbrIds[id * cartesian::maxNoNghbrs<NDIM>() + dir] != INVALID_CELLID; } [[nodiscard]] inline auto hasAnyNeighbor(const GInt id, const GInt dir) const -> GBool { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); checkDir(dir); } return hasNeighbor(id, dir) || (hasParent(id) && hasNeighbor(parent(id), dir)); } // Other data fields inline auto weight(const GInt id) -> GFloat& { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_weight.at(id); } return m_weight[id]; } [[nodiscard]] inline auto weight(const GInt id) const -> GFloat { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_weight.at(id); } return m_weight[id]; } // Other data fields (subject to change) inline auto noOffsprings(const GInt id) -> GInt& { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_noOffsprings.at(id); } return m_noOffsprings[id]; } [[nodiscard]] inline auto noOffsprings(const GInt id) const -> GInt { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_noOffsprings.at(id); } return m_noOffsprings[id]; } inline auto workload(const GInt id) -> GFloat& { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_workload.at(id); } return m_workload[id]; } [[nodiscard]] inline auto workload(const GInt id) const -> GFloat { if(DEBUG_LEVEL >= Debug_Level::debug) { checkBounds(id); return m_workload.at(id); } return m_workload[id]; } /// Return number of properties defined for each node static constexpr auto noProperties() -> GInt { return grid::cell::p(Cell::NumProperties); } [[nodiscard]] inline auto noLeafCells() const -> GInt { return m_noLeafCells; } [[nodiscard]] inline auto noBndCells() const -> GInt { return m_noBndCells; } void setCapacity(const GInt _capacity) override { if(!empty()) { TERMM(-1, "Invalid operation tree already allocated."); } m_childIds.resize(_capacity * cartesian::maxNoChildren<NDIM>()); m_nghbrIds.resize(_capacity * cartesian::maxNoNghbrsDiag<NDIM>()); m_weight.resize(_capacity); m_noOffsprings.resize(_capacity); m_workload.resize(_capacity); BaseCartesianGrid<DEBUG_LEVEL, NDIM>::setCapacity(_capacity); reset(); } void reset() override { std::fill(m_childIds.begin(), m_childIds.end(), INVALID_CELLID); std::fill(m_nghbrIds.begin(), m_nghbrIds.end(), INVALID_CELLID); std::fill(m_weight.begin(), m_weight.end(), NAN); std::fill(m_noOffsprings.begin(), m_noOffsprings.end(), INVALID_CELLID); std::fill(m_workload.begin(), m_workload.end(), NAN); for(GInt i = 0; i < capacity(); ++i) { property(i).reset(); center(i).fill(NAN); } BaseCartesianGrid<DEBUG_LEVEL, NDIM>::reset(); } void save(const GString& /*fileName*/, const json& /*gridOutConfig*/) const override { TERMM(-1, "Not implemented!"); } auto bndrySurface(const GString& id) -> Surface<DEBUG_LEVEL, NDIM>& { if(DEBUG_LEVEL >= Debug_Level::debug) { if(m_bndrySurfaces.count(id) == 0) { TERMM(-1, "Invalid bndryId \"" + id + "\""); } } return m_bndrySurfaces.at(id); } /// Load the generated grid in-memory and set additional properties /// \param grid Generated grid. void loadGridInplace(const CartesianGridGen<DEBUG_LEVEL, NDIM>& grid, const json& properties) { setConfiguration(properties); // grid.balance(); //todo: implement setCapacity(grid.capacity()); // todo: change for adaptation m_geometry = grid.geometry(); size() = grid.size(); currentHighestLvl() = grid.currentHighestLvl(); partitionLvl() = grid.partitionLvl(); setMaxLvl(grid.maxLvl()); setBoundingBox(grid.boundingBox()); #ifdef _OPENMP #pragma omp parallel default(none) shared(grid) { #endif #ifdef _OPENMP #pragma omp for #endif for(GInt cellId = 0; cellId < noCells(); ++cellId) { globalId(cellId) = grid.globalId(cellId); parent(cellId) = grid.parent(cellId); for(GInt childId = 0; childId < cartesian::maxNoChildren<NDIM>(); ++childId) { child(cellId, childId) = grid.child(cellId, childId); } for(GInt nghbrId = 0; nghbrId < cartesian::maxNoNghbrs<NDIM>(); ++nghbrId) { neighbor(cellId, nghbrId) = grid.neighbor(cellId, nghbrId); } level(cellId) = grid.level(cellId); for(GInt dir = 0; dir < NDIM; ++dir) { center(cellId, dir) = grid.center(cellId, dir); } } #ifdef _OPENMP } #endif m_axisAlignedBnd = opt_config_value<GBool>("assumeAxisAligned", m_axisAlignedBnd); if(!m_axisAlignedBnd) { TERMM(-1, "Not implemented!"); } m_periodic = has_any_key_value("type", "periodic"); setProperties(); determineBoundaryCells(); identifyBndrySurfaces(); setupPeriodicConnections(); // addGhostCells(); addDiagonalNghbrs(); for(auto& [name, srf] : m_bndrySurfaces) { srf.updateNeighbors(); } // if(m_loadBalancing) { // setWorkload(); // calculateOffspringsAndWeights(); // } } /// Add ghost cells void addGhostCells() { // todo: make settable const GBool addGhostLayers = false; if(addGhostLayers) { // check all surfaces and add ghostcells in all missing dist directions for(const auto& [srfName, srf] : m_bndrySurfaces) { for(GInt cellId : srf.getCellList()) { for(GInt nghbrDir = 0; nghbrDir < cartesian::maxNoNghbrs<NDIM>(); ++nghbrDir) { if(neighbor(cellId, nghbrDir) == INVALID_CELLID) { const GInt ghostCellId = size() + m_noGhostsCells; cerr0 << "adding cell " << ghostCellId << " as neighbor to " << cellId << std::endl; // todo: remove neighbor(cellId, nghbrDir) = ghostCellId; neighbor(ghostCellId, cartesian::oppositeDir(nghbrDir)) = cellId; property(ghostCellId, CellProperties::ghost); ++m_noGhostsCells; } } } } } } /// Add the diagonal(2D/3D) and/or tridiagonal (3D) to the neighbor connections of each cell. void addDiagonalNghbrs() { m_diagonalNghbrs = true; auto tmpNghbr = m_nghbrIds; auto tmpN = [&](const GInt cellId, const GInt dir) { return tmpNghbr[cellId * cartesian::maxNoNghbrs<NDIM>() + dir]; }; for(GInt cellId = 0; cellId < size(); ++cellId) { // dirs 0=-x 1=+x 2=-y 3=+y // copy existing neighbor connections for(GInt dir = 0; dir < cartesian::maxNoNghbrs<NDIM>(); ++dir) { neighbor(cellId, dir) = tmpN(cellId, dir); } // add diagonal nghbrs if(NDIM > 1) { const GInt nghbrmX = tmpN(cellId, 0); const GInt nghbrpX = tmpN(cellId, 1); // +x+y const GInt nghbrpXpY = nghbrpX != INVALID_CELLID ? tmpN(nghbrpX, 3) : -1; neighbor(cellId, cartesian::maxNoNghbrs<NDIM>()) = nghbrpXpY; // +x-y const GInt nghbrpXmY = nghbrpX != INVALID_CELLID ? tmpN(nghbrpX, 2) : -1; neighbor(cellId, cartesian::maxNoNghbrs<NDIM>() + 1) = nghbrpXmY; // -x-y const GInt nghbrmXmY = nghbrmX != INVALID_CELLID ? tmpN(nghbrmX, 2) : -1; neighbor(cellId, cartesian::maxNoNghbrs<NDIM>() + 2) = nghbrmXmY; // -x+y const GInt nghbrmXpY = nghbrmX != INVALID_CELLID ? tmpN(nghbrmX, 3) : -1; neighbor(cellId, cartesian::maxNoNghbrs<NDIM>() + 3) = nghbrmXpY; } // add tridiagonal nghbrs if(NDIM > 2) { TERMM(-1, "Not implemented!"); } } } auto getCartesianGridData() const -> CartesianGridData<NDIM> { return CartesianGridData<NDIM>(*this); } auto totalSize() const -> GInt { return size() + m_noGhostsCells; } private: void setProperties() { for(GInt cellId = 0; cellId < noCells(); ++cellId) { const GBool isLeaf = noChildren(cellId) == 0; property(cellId, CellProperties::leaf) = isLeaf; m_noLeafCells += static_cast<GInt>(isLeaf); } }; void determineBoundaryCells() { for(GInt cellId = 0; cellId < noCells(); ++cellId) { // is a partition cell determine for each if it can be a boundary cell (no existent parent) // parent has a cut with the boundary -> possible cut of child! if(parent(cellId) == -1 || property(parent(cellId), CellProperties::bndry)) { const GDouble cellLength = lengthOnLvl(std::to_integer<GInt>(level(cellId))); property(cellId, CellProperties::bndry) = m_geometry->cutWithCell(center(cellId), cellLength); // if(DEBUG_LEVEL > Debug_Level::min_debug && property(cellId, CellProperties::bndry)){ if(property(cellId, CellProperties::bndry)) { GInt noNeighbors = 0; for(GInt nghbrId = 0; nghbrId < cartesian::maxNoNghbrs<NDIM>(); ++nghbrId) { if(neighbor(cellId, nghbrId) != INVALID_CELLID) { ++noNeighbors; } } if(cartesian::maxNoNghbrs<NDIM>() == noNeighbors) { // cerr0 << "Removed boundary property cellId: " << cellId << " (" << center(cellId)[0] << ", " << center(cellId)[1] // << ") L:" << cellLength << std::endl; property(cellId, CellProperties::bndry) = false; logger << "Simplified bndry process!!!" << std::endl; // TERMM(-1, "Cell marked as boundary, but is not on a boundary!"); } } } m_noBndCells += static_cast<GInt>(property(cellId, CellProperties::bndry) && property(cellId, CellProperties::leaf)); } } #ifdef CLANG_COMPILER #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma ide diagnostic ignored "cppcoreguidelines-pro-bounds-constant-array-index" #endif void identifyBndrySurfaces() { if(m_axisAlignedBnd) { for(GInt surfId = 0; surfId < cartesian::maxNoNghbrs<NDIM>(); ++surfId) { m_bndrySurfaces.insert({static_cast<GString>(DirIdString[surfId]), Surface<DEBUG_LEVEL, NDIM>(this->getCartesianGridData())}); } for(GInt cellId = 0; cellId < size(); ++cellId) { if(property(cellId, Cell::bndry)) { for(GInt dir = 0; dir < cartesian::maxNoNghbrs<NDIM>(); ++dir) { if(!hasNeighbor(cellId, dir)) { m_bndrySurfaces.at(static_cast<GString>(DirIdString[dir])).addCell(cellId, dir); } } } } } else { TERMM(-1, "Not implemented"); } } #ifdef CLANG_COMPILER #pragma clang diagnostic pop #endif void setupPeriodicConnections() { if(m_periodic) { std::vector<json> periodicBnds = get_all_items_with_value("periodic"); std::unordered_map<GString, GString> periodicConnections; for(const auto& bnd : periodicBnds) { for(const auto& [surfName, props] : bnd.items()) { // check if periodic boundary should be handled as a boundary condition const auto generateBndry = config::opt_config_value<GBool>(props, "generateBndry", true); // skip if it should be if(!generateBndry) { periodicConnections.emplace(surfName, config::required_config_value<GString>(props, "connection")); } } } if(!periodicConnections.empty()) { logger << "Setting up periodic connections!" << std::endl; for(const auto& connection : periodicConnections) { if(periodicConnections.count(connection.second) != 0) { periodicConnections.erase(connection.second); addPeriodicConnection(bndrySurface(connection.first), bndrySurface(connection.second)); } } } } } // todo: fix for refinement level changes // todo: simplify void addPeriodicConnection(const Surface<DEBUG_LEVEL, NDIM>& surfA, const Surface<DEBUG_LEVEL, NDIM>& surfB) { // connect cells of surfA and surfB for(const GInt cellIdA : surfA.getCellList()) { for(const GInt cellIdB : surfB.getCellList()) { GInt notMatchingDir = -1; const auto& centerA = center(cellIdA); const auto& centerB = center(cellIdB); // find cells of surfA and surfB to connect for(GInt dir = 0; dir < NDIM; ++dir) { // connect cells that have one direction which is identical if(std::abs(centerA[dir] - centerB[dir]) > GDoubleEps) { if(notMatchingDir >= 0) { // periodic connection not possible since two directions don't match (3D) notMatchingDir = -1; break; } notMatchingDir = dir; continue; } } // cells need to be connected if(notMatchingDir >= 0) { // identify periodic direction for each cell const GInt nghbrDir = 2 * notMatchingDir; if(centerA[notMatchingDir] > centerB[notMatchingDir]) { if constexpr(DEBUG_LEVEL >= Debug_Level::debug) { if(neighbor(cellIdB, nghbrDir) != INVALID_CELLID) { TERMM(-1, "Invalid set periodic connection! cellIdB:" + std::to_string(cellIdB) + " dir:" + std::to_string(nghbrDir)); } if(neighbor(cellIdA, nghbrDir + 1) != INVALID_CELLID) { TERMM(-1, "Invalid set periodic connection! cellIdA:" + std::to_string(cellIdA) + " dir:" + std::to_string(nghbrDir + 1)); } } neighbor(cellIdB, nghbrDir) = cellIdA; neighbor(cellIdA, nghbrDir + 1) = cellIdB; } else { if constexpr(DEBUG_LEVEL >= Debug_Level::debug) { if(neighbor(cellIdA, nghbrDir) != INVALID_CELLID) { TERMM(-1, "Invalid set periodic connection! cellIdA:" + std::to_string(cellIdA) + " dir:" + std::to_string(nghbrDir)); } if(neighbor(cellIdB, nghbrDir + 1) != INVALID_CELLID) { TERMM(-1, "Invalid set periodic connection! cellIdB:" + std::to_string(cellIdB) + " dir:" + std::to_string(nghbrDir + 1)); } } neighbor(cellIdA, nghbrDir) = cellIdB; neighbor(cellIdB, nghbrDir + 1) = cellIdA; } } } } } void setWorkload() { TERMM(-1, "Not implemented!"); }; void calculateOffspringsAndWeights() { TERMM(-1, "Not implemented!"); }; void invalidate(const GInt begin, const GInt end) { std::fill(&parent(begin), &parent(end), INVALID_CELLID); std::fill(m_childIds.begin() + begin * cartesian::maxNoChildren<NDIM>(), m_childIds.begin() + end * cartesian::maxNoChildren<NDIM>(), INVALID_CELLID); std::fill(m_nghbrIds.begin() + begin * cartesian::maxNoNghbrsDiag<NDIM>(), m_nghbrIds.begin() + end * cartesian::maxNoNghbrsDiag<NDIM>(), INVALID_CELLID); std::fill(&globalId(begin), &globalId(end), INVALID_CELLID); std::fill(&level(begin), &level(end), std::byte(-1)); std::fill(&center(begin), center(end), NAN); std::fill(m_weight.begin() + begin, m_weight.begin() + end, NAN); std::fill(m_noOffsprings.begin() + begin, m_noOffsprings.begin() + end, INVALID_CELLID); std::fill(m_workload.begin() + begin, m_workload.begin() + end, NAN); for(GInt i = 0; i < capacity(); ++i) { property(i).reset(); } } // template <class Functor, class T> // void rawCopyGeneric(Functor&& c, const T& source, const GInt begin, const GInt end, const GInt destination); void deleteConnectivity(const GInt begin, const GInt end) { for(GInt i = begin; i < end; i++) { // Parent if(hasParent(i)) { const GInt p = parent(i); for(GInt j = 0; j < cartesian::maxNoChildren<NDIM>(); j++) { if(child(p, j) == i) { child(p, j) = -1; } } } // Children for(GInt j = 0; j < cartesian::maxNoChildren<NDIM>(); j++) { if(hasChild(i, j)) { parent(child(i, j)) = -1; } } // Neighbors for(GInt j = 0; j < cartesian::maxNoNghbrs<NDIM>(); j++) { if(hasNeighbor(i, j)) { neighbor(neighbor(i, j), cartesian::oppositeDir(j)) = -1; } } } } void moveConnectivity(const GInt begin, const GInt end, const GInt to) { // Auxiliary method for checking if a given id is within the original range that was moved auto inMovedRange = [begin, end](const GInt id) { return (id >= begin && id < end); }; // General strategy: // 1) Loop over moved nodes and check all tree connections (parents/children/neighbors) // 2) If a given connection is to a node that was moved: apply offset to current node // 3) If a given connection is to a node that was not moved: change connectivity in other node for(GInt from = begin; from < end; ++from) { const GInt distance = to - begin; const GInt destination = from + distance; // Parent if(hasParent(destination)) { const GInt p = parent(destination); if(inMovedRange(p)) { parent(destination) += distance; } else { for(GInt j = 0; j < cartesian::maxNoChildren<NDIM>(); ++j) { if(child(p, j) == from) { child(p, j) = destination; } } } } // Children for(GInt j = 0; j < cartesian::maxNoChildren<NDIM>(); ++j) { if(hasChild(destination, j)) { const GInt c = child(destination, j); if(inMovedRange(c)) { child(destination, j) += distance; } else { parent(c) = destination; } } } // Neighbors for(GInt j = 0; j < cartesian::maxNoNghbrs<NDIM>(); ++j) { if(hasNeighbor(destination, j)) { const GInt n = neighbor(destination, j); if(inMovedRange(n)) { neighbor(destination, j) += distance; } else { neighbor(n, cartesian::oppositeDir(j)) = destination; } } } } } void checkChildPos(const GInt pos) const { if(pos > cartesian::maxNoChildren<NDIM>() || pos < 0) { TERMM(-1, "Invalid child position"); } } // cartesian::Tree<DEBUG_LEVEL, NDIM> m_tree{}; std::shared_ptr<GeometryManager<DEBUG_LEVEL, NDIM>> m_geometry; GInt m_noLeafCells = 0; GInt m_noBndCells = 0; GInt m_noGhostsCells = 0; GBool m_loadBalancing = false; GBool m_diagonalNghbrs = false; GBool m_axisAlignedBnd = false; GBool m_periodic = false; std::unordered_map<GString, Surface<DEBUG_LEVEL, NDIM>> m_bndrySurfaces; // Data containers std::vector<GInt> m_childIds{}; std::vector<GInt> m_nghbrIds{}; std::vector<GInt> m_noOffsprings{}; std::vector<GFloat> m_weight{}; std::vector<GFloat> m_workload{}; }; #endif // GRIDGENERATOR_CARTESIANGRID_H
simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd foo // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd safelen(4) void test_no_clause() { int i; #pragma omp simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp simd' must be a for loop}} #pragma omp simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd; for (i = 0; i < 16; ++i) ; // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd firstprivate(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd safelen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd safelen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, ) for (i = 0; i < 16; ++i) ; // xxpected-error@+1 {{expected expression}} #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a positive integer value}} #pragma omp simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a positive integer value}} #pragma omp simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a positive integer value}} #pragma omp simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd simdlen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd simdlen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a positive integer value}} #pragma omp simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a positive integer value}} #pragma omp simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a positive integer value}} #pragma omp simd simdlen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_safelen_simdlen() { int i; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd simdlen(6) safelen(5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // xxpected-error@+1 {{expected expression}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} #pragma omp simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}} #pragma omp simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}} #pragma omp simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}} #pragma omp simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as reduction}} #pragma omp parallel #pragma omp simd collapse(2) reduction(+ : i) for (i = 0; i < 16; ++i) // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}} for (int j = 0; j < 16; ++j) // expected-error@+3 {{reduction variable must be shared}} // expected-error@+2 {{private variable cannot be reduction}} // expected-error@+1 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd linear(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd linear(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp simd linear(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be linear}} #pragma omp simd linear(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as private}} // expected-error@+1 {{private variable cannot be linear}} #pragma omp simd private(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be private}} #pragma omp simd linear(x) private(x) for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{zero linear step (x and other variables in clause should probably be const)}} #pragma omp simd linear(x, y : 0) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be lastprivate}} #pragma omp simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp simd lastprivate(x) linear(x) for (i = 0; i < 16; ++i) ; } void test_aligned() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as aligned}} // expected-error@+1 {{a variable cannot appear in more than one aligned clause}} #pragma omp simd aligned(x) aligned(z, x) for (i = 0; i < 16; ++i) ; // expected-note@+3 {{defined as aligned}} // expected-error@+2 {{a variable cannot appear in more than one aligned clause}} // expected-error@+1 2 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_firstprivate() { int i; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-error@+1 {{expected expression}} #pragma omp simd firstprivate( for (i = 0; i < 16; ++i) ; } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_reduction() { int i, x, y; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction() for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction( : x) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(, for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(+ for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+: for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ : x, + : y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction(% : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(+ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(* : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(- : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(^ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(&& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(|| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(max : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(min : x) for (i = 0; i < 16; ++i) ; struct X { int x; }; struct X X; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : X.x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : x + x) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void linear_modifiers(int argc) { int f; #pragma omp simd linear(f) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(val(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(foo(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; }
3b9e0840f02a82ecdee6180fa41945a2bfd493d1.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "omp.h" struct dataobj { void *restrict data; int * size; int * npsize; int * dsize; int * hsize; int * hofs; int * oofs; } ; struct profiler { double section0; } ; int initdamp(struct dataobj *restrict damp_vec, const float h_x, const float h_y, const int x_M, const int x_m, const int y_M, const int y_m, const int abc_x_l_ltkn, const int abc_x_r_rtkn, const int abc_y_l_ltkn, const int abc_y_r_rtkn, struct profiler * timers) { float (*restrict damp)[damp_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]]) damp_vec->data; #pragma omp target enter data map(to: damp[0:damp_vec->size[0]][0:damp_vec->size[1]]) struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp target teams distribute parallel for collapse(2) for (int abc_x_l = x_m; abc_x_l <= abc_x_l_ltkn + x_m - 1; abc_x_l += 1) { for (int y = y_m; y <= y_M; y += 1) { damp[abc_x_l + 1][y + 1] += (-4.12276274369678e-2F*sin(6.28318530717959F*fabs(2.5e-2F*x_m - 2.5e-2F*abc_x_l + 1.025F)) + 2.5904082296183e-1F*fabs(2.5e-2F*x_m - 2.5e-2F*abc_x_l + 1.025F))/h_x; } } #pragma omp target teams distribute parallel for collapse(2) for (int abc_x_r = -abc_x_r_rtkn + x_M + 1; abc_x_r <= x_M; abc_x_r += 1) { for (int y = y_m; y <= y_M; y += 1) { damp[abc_x_r + 1][y + 1] += (-4.12276274369678e-2F*sin(6.28318530717959F*fabs(-2.5e-2F*x_M + 2.5e-2F*abc_x_r + 1.025F)) + 2.5904082296183e-1F*fabs(-2.5e-2F*x_M + 2.5e-2F*abc_x_r + 1.025F))/h_x; } } #pragma omp target teams distribute parallel for collapse(1) for (int x = x_m; x <= x_M; x += 1) { for (int abc_y_l = y_m; abc_y_l <= abc_y_l_ltkn + y_m - 1; abc_y_l += 1) { damp[x + 1][abc_y_l + 1] += (-4.12276274369678e-2F*sin(6.28318530717959F*fabs(2.5e-2F*y_m - 2.5e-2F*abc_y_l + 1.025F)) + 2.5904082296183e-1F*fabs(2.5e-2F*y_m - 2.5e-2F*abc_y_l + 1.025F))/h_y; } for (int abc_y_r = -abc_y_r_rtkn + y_M + 1; abc_y_r <= y_M; abc_y_r += 1) { damp[x + 1][abc_y_r + 1] += (-4.12276274369678e-2F*sin(6.28318530717959F*fabs(-2.5e-2F*y_M + 2.5e-2F*abc_y_r + 1.025F)) + 2.5904082296183e-1F*fabs(-2.5e-2F*y_M + 2.5e-2F*abc_y_r + 1.025F))/h_y; } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000; #pragma omp target update from(damp[0:damp_vec->size[0]][0:damp_vec->size[1]]) #pragma omp target exit data map(release: damp[0:damp_vec->size[0]][0:damp_vec->size[1]]) return 0; }
enhance.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.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/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriately. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C L A H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CLAHEImage() is a variant of adaptive histogram equalization in which the % contrast amplification is limited, so as to reduce this problem of noise % amplification. % % Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in % "Graphics Gems IV", Academic Press, 1994. % % The format of the CLAHEImage method is: % % MagickBooleanType CLAHEImage(Image *image,const size_t width, % const size_t height,const size_t number_bins,const double clip_limit, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the tile divisions to use in horizontal direction. % % o height: the height of the tile divisions to use in vertical direction. % % o number_bins: number of bins for histogram ("dynamic range"). % % o clip_limit: contrast limit for localised changes in contrast. A limit % less than 1 results in standard non-contrast limited AHE. % % o exception: return any errors or warnings in this structure. % */ typedef struct _RangeInfo { unsigned short min, max; } RangeInfo; static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins, size_t *histogram) { #define NumberCLAHEGrays (65536) ssize_t i; size_t cumulative_excess, previous_excess, step; ssize_t excess; /* Compute total number of excess pixels. */ cumulative_excess=0; for (i=0; i < (ssize_t) number_bins; i++) { excess=(ssize_t) histogram[i]-(ssize_t) clip_limit; if (excess > 0) cumulative_excess+=excess; } /* Clip histogram and redistribute excess pixels across all bins. */ step=cumulative_excess/number_bins; excess=(ssize_t) (clip_limit-step); for (i=0; i < (ssize_t) number_bins; i++) { if ((double) histogram[i] > clip_limit) histogram[i]=(size_t) clip_limit; else if ((ssize_t) histogram[i] > excess) { cumulative_excess-=histogram[i]-excess; histogram[i]=(size_t) clip_limit; } else { cumulative_excess-=step; histogram[i]+=step; } } /* Redistribute remaining excess. */ do { size_t *p; size_t *q; previous_excess=cumulative_excess; p=histogram; q=histogram+number_bins; while ((cumulative_excess != 0) && (p < q)) { step=number_bins/cumulative_excess; if (step < 1) step=1; for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step) if ((double) *p < clip_limit) { (*p)++; cumulative_excess--; } p++; } } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess)); } static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const size_t number_bins, const unsigned short *lut,const unsigned short *pixels,size_t *histogram) { const unsigned short *p; ssize_t i; /* Classify the pixels into a gray histogram. */ for (i=0; i < (ssize_t) number_bins; i++) histogram[i]=0L; p=pixels; for (i=0; i < (ssize_t) tile_info->height; i++) { const unsigned short *q; q=p+tile_info->width; while (p < q) histogram[lut[*p++]]++; q+=clahe_info->width; p=q-tile_info->width; } } static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12, const size_t *Q22,const size_t *Q11,const size_t *Q21, const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels) { ssize_t y; unsigned short intensity; /* Bilinear interpolate four tiles to eliminate boundary artifacts. */ for (y=(ssize_t) tile->height; y > 0; y--) { ssize_t x; for (x=(ssize_t) tile->width; x > 0; x--) { intensity=lut[*pixels]; *pixels++=(unsigned short) (PerceptibleReciprocal((double) tile->width* tile->height)*(y*((double) x*Q12[intensity]+(tile->width-x)* Q22[intensity])+(tile->height-y)*((double) x*Q11[intensity]+ (tile->width-x)*Q21[intensity]))); } pixels+=(clahe_info->width-tile->width); } } static void GenerateCLAHELut(const RangeInfo *range_info, const size_t number_bins,unsigned short *lut) { ssize_t i; unsigned short delta; /* Scale input image [intensity min,max] to [0,number_bins-1]. */ delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1); for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++) lut[i]=(unsigned short) ((i-range_info->min)/delta); } static void MapCLAHEHistogram(const RangeInfo *range_info, const size_t number_bins,const size_t number_pixels,size_t *histogram) { double scale, sum; ssize_t i; /* Rescale histogram to range [min-intensity .. max-intensity]. */ scale=(double) (range_info->max-range_info->min)/number_pixels; sum=0.0; for (i=0; i < (ssize_t) number_bins; i++) { sum+=histogram[i]; histogram[i]=(size_t) (range_info->min+scale*sum); if (histogram[i] > range_info->max) histogram[i]=range_info->max; } } static MagickBooleanType CLAHE(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const RangeInfo *range_info, const size_t number_bins,const double clip_limit,unsigned short *pixels) { MemoryInfo *tile_cache; unsigned short *p; size_t limit, *tiles; ssize_t y; unsigned short *lut; /* Constrast limited adapted histogram equalization. */ if (clip_limit == 1.0) return(MagickTrue); tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y, number_bins*sizeof(*tiles)); if (tile_cache == (MemoryInfo *) NULL) return(MagickFalse); lut=(unsigned short *) AcquireQuantumMemory(NumberCLAHEGrays,sizeof(*lut)); if (lut == (unsigned short *) NULL) { tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickFalse); } tiles=(size_t *) GetVirtualMemoryBlob(tile_cache); limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins); if (limit < 1UL) limit=1UL; /* Generate greylevel mappings for each tile. */ GenerateCLAHELut(range_info,number_bins,lut); p=pixels; for (y=0; y < (ssize_t) clahe_info->y; y++) { ssize_t x; for (x=0; x < (ssize_t) clahe_info->x; x++) { size_t *histogram; histogram=tiles+(number_bins*(y*clahe_info->x+x)); GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram); ClipCLAHEHistogram((double) limit,number_bins,histogram); MapCLAHEHistogram(range_info,number_bins,tile_info->width* tile_info->height,histogram); p+=tile_info->width; } p+=clahe_info->width*(tile_info->height-1); } /* Interpolate greylevel mappings to get CLAHE image. */ p=pixels; for (y=0; y <= (ssize_t) clahe_info->y; y++) { OffsetInfo offset; RectangleInfo tile; ssize_t x; tile.height=tile_info->height; tile.y=y-1; offset.y=tile.y+1; if (y == 0) { /* Top row. */ tile.height=tile_info->height >> 1; tile.y=0; offset.y=0; } else if (y == (ssize_t) clahe_info->y) { /* Bottom row. */ tile.height=(tile_info->height+1) >> 1; tile.y=clahe_info->y-1; offset.y=tile.y; } for (x=0; x <= (ssize_t) clahe_info->x; x++) { tile.width=tile_info->width; tile.x=x-1; offset.x=tile.x+1; if (x == 0) { /* Left column. */ tile.width=tile_info->width >> 1; tile.x=0; offset.x=0; } else if (x == (ssize_t) clahe_info->x) { /* Right column. */ tile.width=(tile_info->width+1) >> 1; tile.x=clahe_info->x-1; offset.x=tile.x; } InterpolateCLAHE(clahe_info, tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */ tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */ tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */ tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */ &tile,lut,p); p+=tile.width; } p+=clahe_info->width*(tile.height-1); } lut=(unsigned short *) RelinquishMagickMemory(lut); tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickTrue); } MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width, const size_t height,const size_t number_bins,const double clip_limit, ExceptionInfo *exception) { #define CLAHEImageTag "CLAHE/Image" CacheView *image_view; ColorspaceType colorspace; MagickBooleanType status; MagickOffsetType progress; MemoryInfo *pixel_cache; RangeInfo range_info; RectangleInfo clahe_info, tile_info; size_t n; ssize_t y; unsigned short *pixels; /* Configure CLAHE parameters. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); range_info.min=0; range_info.max=NumberCLAHEGrays-1; tile_info.width=width; if (tile_info.width == 0) tile_info.width=image->columns >> 3; tile_info.height=height; if (tile_info.height == 0) tile_info.height=image->rows >> 3; tile_info.x=0; if ((image->columns % tile_info.width) != 0) tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width); tile_info.y=0; if ((image->rows % tile_info.height) != 0) tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height); clahe_info.width=image->columns+tile_info.x; clahe_info.height=image->rows+tile_info.y; clahe_info.x=(ssize_t) clahe_info.width/tile_info.width; clahe_info.y=(ssize_t) clahe_info.height/tile_info.height; pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height* sizeof(*pixels)); if (pixel_cache == (MemoryInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache); colorspace=image->colorspace; if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse) { pixel_cache=RelinquishVirtualMemory(pixel_cache); return(MagickFalse); } /* Initialize CLAHE pixels. */ image_view=AcquireVirtualCacheView(image,exception); progress=0; status=MagickTrue; n=0; for (y=0; y < (ssize_t) clahe_info.height; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y- (tile_info.y >> 1),clahe_info.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) clahe_info.width; x++) { pixels[n++]=ScaleQuantumToShort(p[0]); p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ? (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); /* Push CLAHE pixels to CLAHE image. */ image_view=AcquireAuthenticCacheView(image,exception); n=clahe_info.width*(tile_info.y >> 1); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } n+=tile_info.x >> 1; for (x=0; x < (ssize_t) image->columns; x++) { q[0]=ScaleShortToQuantum(pixels[n++]); q+=GetPixelChannels(image); } n+=(clahe_info.width-image->columns-(tile_info.x >> 1)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); pixel_cache=RelinquishVirtualMemory(pixel_cache); if (TransformImageColorspace(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); status=InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); if (status == MagickFalse) break; } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; (void) GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black)); white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); 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++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastStretchImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(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 *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced 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); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(enhance_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_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,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); 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++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=(double) p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(intensity))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) memset(black,0,sizeof(*black)); (void) memset(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,PerceptibleReciprocal(gamma)))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GammaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double area, offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; pixel2=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel3=zero; area=point.y; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.y < 0.5) ? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel3); offset+=cube_size; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel4); pixel=zero; area=point.z; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.z < 0.5)? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, area,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; scale=PerceptibleReciprocal(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), PerceptibleReciprocal(gamma)); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly 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 % appropriately. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if (grayscale != MagickFalse) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; if (IsPixelGray(image,q) == MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e B a l a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteBalanceImage() applies white balancing to an image according to a % grayworld assumption in the LAB colorspace. % % The format of the WhiteBalanceImage method is: % % MagickBooleanType WhiteBalanceImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteBalanceImage(Image *image, ExceptionInfo *exception) { #define WhiteBalanceImageTag "WhiteBalance/Image" CacheView *image_view; const char *artifact; double a_mean, b_mean; MagickOffsetType progress; MagickStatusType status; ssize_t y; /* White balance image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=TransformImageColorspace(image,LabColorspace,exception); a_mean=0.0; b_mean=0.0; image_view=AcquireAuthenticCacheView(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 == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { a_mean+=QuantumScale*GetPixela(image,p)-0.5; b_mean+=QuantumScale*GetPixelb(image,p)-0.5; p+=GetPixelChannels(image); } } a_mean/=((double) image->columns*image->rows); b_mean/=((double) image->columns*image->rows); progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; /* Scale the chroma distance shifted according to amount of luminance. */ a=(double) GetPixela(image,q)-1.1*GetPixelL(image,q)*a_mean; b=(double) GetPixelb(image,q)-1.1*GetPixelL(image,q)*b_mean; SetPixela(image,ClampToQuantum(a),q); SetPixelb(image,ClampToQuantum(b),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,WhiteBalanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); artifact=GetImageArtifact(image,"white-balance:vibrance"); if (artifact != (const char *) NULL) { ChannelType channel_mask; double black_point; GeometryInfo geometry_info; MagickStatusType flags; /* Level the a & b channels. */ flags=ParseGeometry(artifact,&geometry_info); black_point=geometry_info.rho; if ((flags & PercentValue) != 0) black_point*=(double) (QuantumRange/100.0); channel_mask=SetImageChannelMask(image,(ChannelType) (aChannel | bChannel)); status&=LevelImage(image,black_point,(double) QuantumRange-black_point, 1.0,exception); (void) SetImageChannelMask(image,channel_mask); } status&=TransformImageColorspace(image,sRGBColorspace,exception); return(status != 0 ? MagickTrue : MagickFalse); }
convolution_1x1_packnto1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv1x1s1_sgemm_packnto1_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_packnto1_fp16sa_rvv(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s2_packnto1_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = (w - 2 * outw + w) * packn; Mat bottom_blob_shrinked; bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < channels; p++) { const __fp16* r0 = bottom_blob.channel(p); __fp16* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat16m1_t _val = vle16_v_f16m1(r0, vl); vse16_v_f16m1(outptr, _val, vl); r0 += packn * 2; outptr += packn; } r0 += tailstep; } } conv1x1s1_sgemm_packnto1_fp16sa_rvv(bottom_blob_shrinked, top_blob, kernel, _bias, opt); }
GB_binop__isne_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_int16) // A.*B function (eWiseMult): GB (_AemultB_08__isne_int16) // A.*B function (eWiseMult): GB (_AemultB_02__isne_int16) // A.*B function (eWiseMult): GB (_AemultB_04__isne_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_int16) // A*D function (colscale): GB (_AxD__isne_int16) // D*A function (rowscale): GB (_DxB__isne_int16) // C+=B function (dense accum): GB (_Cdense_accumB__isne_int16) // C+=b function (dense accum): GB (_Cdense_accumb__isne_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_int16) // C=scalar+B GB (_bind1st__isne_int16) // C=scalar+B' GB (_bind1st_tran__isne_int16) // C=A+scalar GB (_bind2nd__isne_int16) // C=A'+scalar GB (_bind2nd_tran__isne_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_INT16 || GxB_NO_ISNE_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isne_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_int16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isne_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isne_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
RandOpt.c
/* kcollins - RandomAccess core_single_cpu kernel from HPCC */ /* with C driver for standalone testing */ /* * This code has been contributed by the DARPA HPCS program. Contact * David Koester <dkoester@mitre.org> or Bob Lucas <rflucas@isi.edu> * if you have questions. * * GUPS (Giga UPdates per Second) is a measurement that profiles the memory * architecture of a system and is a measure of performance similar to MFLOPS. * The HPCS HPCchallenge RandomAccess benchmark is intended to exercise the * GUPS capability of a system, much like the LINPACK benchmark is intended to * exercise the MFLOPS capability of a computer. In each case, we would * expect these benchmarks to achieve close to the "peak" capability of the * memory system. The extent of the similarities between RandomAccess and * LINPACK are limited to both benchmarks attempting to calculate a peak system * capability. * * GUPS is calculated by identifying the number of memory locations that can be * randomly updated in one second, divided by 1 billion (1e9). The term "randomly" * means that there is little relationship between one address to be updated and * the next, except that they occur in the space of one half the total system * memory. An update is a read-modify-write operation on a table of 64-bit words. * An address is generated, the value at that address read from memory, modified * by an integer operation (add, and, or, xor) with a literal value, and that * new value is written back to memory. * * We are interested in knowing the GUPS performance of both entire systems and * system subcomponents --- e.g., the GUPS rating of a distributed memory * multiprocessor the GUPS rating of an SMP node, and the GUPS rating of a * single processor. While there is typically a scaling of FLOPS with processor * count, a similar phenomenon may not always occur for GUPS. * * For additional information on the GUPS metric, the HPCchallenge RandomAccess * Benchmark,and the rules to run RandomAccess or modify it to optimize * performance -- see http://icl.cs.utk.edu/hpcc/ * */ /* * This file contains the computational core of the single cpu version * of GUPS. The inner loop should easily be vectorized by compilers * with such support. * * This core is used by both the single_cpu and star_single_cpu tests. */ /* Number of updates to table (suggested: 4x number of table entries) */ #include <sys/types.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <omp.h> #include <string.h> #include "hif.h" #define POLY 0x0000000000000007UL #define PERIOD 1317624576693539401L #define NUPDATE (4 * TableSize) #define NUM_THREADS 32 uint64_t HPCC_starts(int64_t); static void RandomAccessUpdate(uint64_t TableSize, uint64_t *Table) { uint64_t i; uint64_t *ran; int j; uint32_t unitCnt = __htc_get_unit_count(); uint64_t ranSize = unitCnt * NUM_THREADS; ran = (uint64_t *)malloc(ranSize*sizeof(uint64_t)); if (! ran) { printf( "Failed to allocate memory for the ran array (%ld).\n", ranSize); exit(1); } #pragma omp parallel for for (j=0; j<ranSize; j++) { ran[j] = HPCC_starts ((NUPDATE/ranSize) * j); } fprintf(stderr,"ran array has been initialized\n"); fflush(stderr); uint32_t updates_per_unit = NUPDATE/unitCnt; printf("will use %d units and %d threads per unit, %d total threads\n",unitCnt,NUM_THREADS,unitCnt*NUM_THREADS); printf("NUPDATE is %ld updates_per_unit is %ld\n", NUPDATE, updates_per_unit); #pragma omp parallel num_threads(unitCnt) { int unit = omp_get_thread_num(); uint64_t *unitran = ran + (unit * NUM_THREADS); #pragma omp target device(unit) { #pragma omp parallel num_threads(NUM_THREADS) { uint64_t pran = unitran[omp_get_thread_num()]; #pragma omp for schedule(static, 1) nowait for (i=0; i< updates_per_unit; i++) { pran = (pran << 1) ^ ((int64_t) pran < 0 ? POLY : 0); Table[pran & (TableSize-1)] ^= pran; } } } } } /* Utility routine to start random number generator at Nth step */ uint64_t HPCC_starts(int64_t n) { int i, j; uint64_t m2[64]; uint64_t temp, ran; while (n < 0) n += PERIOD; while (n > PERIOD) n -= PERIOD; if (n == 0) return 0x1; temp = 0x1; for (i=0; i<64; i++) { m2[i] = temp; temp = (temp << 1) ^ ((int64_t) temp < 0 ? POLY : 0); temp = (temp << 1) ^ ((int64_t) temp < 0 ? POLY : 0); } for (i=62; i>=0; i--) if ((n >> i) & 1) break; ran = 0x2; while (i > 0) { temp = 0; for (j=0; j<64; j++) if ((ran >> j) & 1) temp ^= m2[j]; ran = temp; i -= 1; if ((n >> i) & 1) ran = (ran << 1) ^ ((int64_t) ran < 0 ? POLY : 0); } return ran; } /*kcollins timers*/ #include <sys/time.h> #include <sys/resource.h> double RTSEC() { struct timeval tp; struct timezone tzp; gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } double CPUSEC() { struct rusage ru; getrusage(RUSAGE_SELF,&ru); return( (double) ru.ru_utime.tv_sec + (double) ru.ru_utime.tv_usec * 1.e-6 ); } int main (int argc, char **argv) { uint64_t i; uint64_t temp; double cputime; /* CPU time to update table */ double realtime; /* Real time to update table */ double GUPs; uint64_t *Table; uint64_t *cp_Table; uint64_t TableSize; pers_attach(); int power = 24; if(argc > 1) { power = atoi(argv[1]); } TableSize = 1<<power; Table = (uint64_t *)calloc( TableSize, sizeof(uint64_t) ); if (! Table) { printf( "Failed to allocate memory for the update table (%ld).\n", TableSize); return 1; } cp_Table = ((uint64_t *)(pers_cp_malloc(TableSize*sizeof(uint64_t )))); if (!cp_Table) { printf("Failed to allocate memory for the cp update table (%ld).\n",TableSize); return 1; } /* Print parameters for run */ printf( "Main table size = %ld words\n", TableSize); printf( "Number of updates = %ld\n", NUPDATE); /* Initialize main table */ for (i=0; i<TableSize; i++) Table[i] = i; pers_cp_memcpy(cp_Table, Table, TableSize*sizeof(uint64_t )); /* Begin timing here */ cputime = -CPUSEC(); realtime = -RTSEC(); // RandomAccessUpdate(TableSize,Table); RandomAccessUpdate(TableSize,cp_Table); /* End timed section */ cputime += CPUSEC(); realtime += RTSEC(); pers_cp_memcpy(Table, cp_Table, TableSize*sizeof(uint64_t )); /* make sure no division by zero */ GUPs = (realtime > 0.0 ? 1.0 / realtime : -1.0); GUPs *= 1e-9*NUPDATE; /* Print timing results */ printf( "CPU time used = %.6f seconds\n", cputime); printf( "Real time used = %.6f seconds\n", realtime); printf( "%.9f Billion(10^9) Updates per second [GUP/s]\n", GUPs ); /* Verification of results (in serial or "safe" mode; optional) */ temp = 0x1; for (i=0; i<NUPDATE; i++) { temp = (temp << 1) ^ (((int64_t) temp < 0) ? POLY : 0); Table[temp & (TableSize-1)] ^= temp; } temp = 0; for (i=0; i<TableSize; i++) if (Table[i] != i) temp++; printf( "Found %ld errors in %ld locations (%s).\n", temp, TableSize, (temp <= 0.01*TableSize) ? "passed" : "failed"); free( Table ); pers_detach(); return 0; }
mutation.h
void mutation(Chromo *population, int prob, int N, int inicio, int fin) { int aux, i, p1 = 0, p2 = 0; #pragma omp for for (i = inicio; i < fin; i++) { srand(time(NULL)); if (rand() % (101) <= prob) { do { p1 = rand() % (N + 1); p2 = rand() % (N + 1); } while (p1 == p2); aux = population[i].config[p1]; population[i].config[p1] = population[i].config[p2]; population[i].config[p2] = aux; } } }
NEC_scheme.c
/* ============================================================================= Copyright (c) 2013, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaWD - The Vienna Wigner Decoherence Algorithms Ensemble Monte Carlo Simulator ----------------- authors: Marek Pobjecky Mihail Nedjalkov nedjalkov@iue.tuwien.ac.at license: see file LICENSE in the base directory ============================================================================= */ #include <math.h> #include "emc.h" #include <omp.h> /********************************************************************/ /* NEC method for the charge assignment at the node points */ /********************************************************************/ int oooChargeAssignmentNEC(const_t constpar, geometry_t *geometry, scatpar_t *scatpar, el_data_t *particles, phys_quant_t *phys_quantities) { static int i, j, n; static double denn, teglo, elecNumber[MAXNX][MAXNY], normFactor; /*=== Evaluate multiplication constant ===*/ normFactor = 1.0 / (geometry->cellVolume * constpar.Ni); /*=== Reset the charge vector ===*/ for (i = 0; i <= geometry->nxmax; ++i) for (j = 0; j <= geometry->nymax; ++j) elecNumber[i][j] = 0.0; // #pragma omp parallel // #pragma omp for #pragma omp for schedule(static, 1) /*=== Charge assignment part ===*/ for (n = 0; n <= scatpar->n_used; ++n) { i = (int) (particles[n].p[5] / geometry->meshSize); j = (int) (particles[n].p[6] / geometry->meshSize); teglo = particles[n].p[7] * 0.25; elecNumber[i] [j] += teglo; elecNumber[i] [j+1] += teglo; elecNumber[i+1][j] += teglo; elecNumber[i+1][j+1] += teglo; } /*=== Calculate electron density ===*/ for (i = 0; i <= geometry->nxmax; ++i) for (j = 0; j <= geometry->nymax; ++j) { denn = elecNumber[i][j]; if (i == 0 || i == geometry->nxmax) denn *= 2.0; if (j == 0 || j == geometry->nymax) denn *= 2.0; phys_quantities->elecDensity[i][j] = denn * normFactor; } return 0; }
pipar.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 4 static long steps = 100; double step; int main(int argc, const char* argv[]) { double pi = 0.0; int nthreads; step = 1.0 / (double)steps; double start, delta, sum[NUM_THREADS]; start = omp_get_wtime(); omp_set_num_threads(NUM_THREADS); #pragma omp parallel { double x; int id, i; id = omp_get_thread_num(); for (i = id, sum[id] = 0.0; i < steps; i = i + NUM_THREADS) { x = (i + 0.5) * step; sum[id] += 4.0 / (1.0 + x * x); } } for (int i = 0; i < NUM_THREADS; i++) pi += sum[i] * step; delta = omp_get_wtime() - start; printf("PI = %.16g computed in %.4g seconds with %d threads.\n", pi, delta, NUM_THREADS); }
gemv_c_coo_conj.c
#include "alphasparse/kernel.h" #include "alphasparse/kernel_plain.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t gemv_c_coo_conj_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->cols; const ALPHA_INT nnz = A->nnz; const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number **tmp = (ALPHA_Number **)malloc(sizeof(ALPHA_Number *) * thread_num); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (int i = 0; i < thread_num; ++i) { tmp[i] = malloc(sizeof(ALPHA_Number) * m); memset(tmp[i], 0, sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < nnz; i++) { const ALPHA_INT threadId = alpha_get_thread_id(); const ALPHA_INT r = A->row_indx[i]; const ALPHA_INT c = A->col_indx[i]; ALPHA_Number v; alpha_mul_2c(v, A->values[i], x[r]); alpha_madde(tmp[threadId][c], alpha, v); } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); for (ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(y[i], y[i], tmp[j][i]); } } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT thread_num = alpha_get_thread_num(); return gemv_c_coo_conj_omp(alpha, A, x, beta, y); }
omp_privateshared.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> /* compile with gcc -o PrivateShared -fopenmp PrivateShared.c */ int main(int argc, char** argv) { int i = 0; int tid; int size = 20; int * a = (int *)calloc(size, sizeof(int)); int * b = (int *)calloc(size, sizeof(int)); int * c; int * tids = (int *)calloc(size, sizeof(int)); printf("BEFORE\n"); for (i = 0; i < size; ++i) { a[i] = b[i] = i; printf("a[%d] = %d, b[%d] = %d\n", i, a[i], i, b[i]); } #pragma omp parallel shared(a, b, tids) private(c, i, tid) { tid = omp_get_thread_num(); c = (int *)malloc(sizeof(int)); #pragma omp for for (i = 0; i < size; ++i) { c[0] = tid * a[i]; a[i] = c[0]; b[i] += c[0]; tids[i] = tid; } free(c); } printf("AFTER\n"); for (i = 0; i < size; ++i) { printf("tid = %d, a[%d] = %d, b[%d] = %d\n", tids[i], i, a[i], i, b[i]); } free(a); free(b); free(tids); return 0; }
conv_kernel_rv64.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: ddzhao@openailab.com */ #include <stdint.h> #include <stdlib.h> #include <math.h> #include "conv_kernel_rv64.h" // #include "wino_conv_kernel_arm.h" // FIXME: add wino support // #include "wino_conv_kernel_1_arm.h" // FIXME: add wino support #define PER_OUT_CHAN 16 void sgemm_4x16_rv64(float* biases, float* input, float* kernel, long kernel_size, float* output, long output_xy, int activation, int layout); void sgemm_4x4_rv64(float* biases, float* input, float* kernel, long kernel_size, float* output, long output_xy, int activation, int layout); void im2col_fp32_1x1(float* input, int input_xy, float* col, int col_cnt, int input_chan); void im2col_fp32_3x3(float* input, int w, int h, int channel, float* cur_col, int stride); static void interleave_kernel(float* kernel, float* kernel_interleaved, int kernel_chan, int kernel_size) { int i, j, k; float* cur_kernel[PER_OUT_CHAN]; float* cur_kernel_interleaved = kernel_interleaved; // interleave PER_OUT_CHAN kernels for (i = 0; i + PER_OUT_CHAN - 1 < kernel_chan; i += PER_OUT_CHAN) { for (k = 0; k < PER_OUT_CHAN; k++) cur_kernel[k] = kernel + kernel_size * (i + k); for (j = 0; j < kernel_size; j++) { for (k = 0; k < PER_OUT_CHAN; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; } } for (; i < (kernel_chan & -4); i += 4) { for (k = 0; k < 4; k++) cur_kernel[k] = kernel + kernel_size * (i + k); for (j = 0; j < kernel_size; j++) { for (k = 0; k < 4; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; } } // last 4 kernel for (k = 0; k < 3; k++) cur_kernel[k] = kernel + kernel_size * (i + k); if ((kernel_chan & 0x3) == 3) { for (j = 0; j < kernel_size; j++) { for (k = 0; k < 3; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; *(cur_kernel_interleaved++) = 0.f; } } else if ((kernel_chan & 0x3) == 2) { for (j = 0; j < kernel_size; j++) { for (k = 0; k < 2; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; } } else if ((kernel_chan & 0x3) == 1) { for (j = 0; j < kernel_size; j++) { *(cur_kernel_interleaved++) = cur_kernel[0][j]; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; } } } /* kernel interleave */ static void interleave(struct ir_tensor* filter, struct conv_priv_info* priv_info, struct conv_param* param) { int group = param->group; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size_algin = kernel_size * out_chan_align4; int kernel_size_group = kernel_size * out_chan; float* kernel = filter->data; float* interleave_buf = priv_info->interleave_buffer; for (int g = 0; g < group; g++) { float* cur_kernel = kernel + g * kernel_size_group; float* cur_interleave = interleave_buf + g * kernel_size_algin; interleave_kernel(cur_kernel, cur_interleave, out_chan, kernel_size); } } static void im2col(float* input, float* col, int in_c, int in_w, int in_h, int k_w, int k_h, int s_w, int s_h, int d_w, int d_h, int pad_w0, int pad_w1, int pad_h0, int pad_h1, int out_w, int out_h, int num_thread) { if (k_w == 1 && k_h == 1 && s_w == 1 && s_h == 1) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int out_xy = out_w * out_h; int col_end3 = out_xy & 3; #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < out_xy - 3; col_i += 4) { float* cur_col = col + col_i * kernel_size; float* cur_input = input + col_i; im2col_fp32_1x1(cur_input, in_xy, cur_col, 4, in_c); } int col_i = out_xy & -4; float* cur_col; // final 4 input if (col_end3) { cur_col = col + col_i * kernel_size; for (int col_j = 0; col_j < kernel_size; col_j++) { for (int i = 0; i < 4; i++) { if (i < col_end3) *cur_col++ = *(input + col_j * in_xy + col_i + i); else *cur_col++ = 0; } } } } else if (d_w == 1 && d_h == 1 && k_w == 3 && k_h == 3 && s_w == s_h) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int out_xy = out_w * out_h; int col_end3 = out_xy & 3; int is_pad0 = (pad_w0 == 0) && (pad_h0 == 0) && (pad_w1 == 0) && (pad_h1 == 0); #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < (out_xy & -4); col_i += 4) { float* cur_col = col + col_i * kernel_size; int imy0 = col_i / out_w; int imy3 = (col_i + 3) / out_w; int imx0 = col_i - imy0 * out_w; int imx3 = (col_i + 3) - imy3 * out_w; if ((imy0 == imy3) && (is_pad0 || (imy0 != 0 && imx0 != 0 && imy0 != (out_h - 1) && imx3 != (out_w - 1)))) { float* l0 = input + (imy0 * s_h - pad_h0) * in_w + (imx0 * s_w - pad_w0); { im2col_fp32_3x3(l0, in_w, in_h, in_c, cur_col, s_w); // add im2col 3x3 cur_col += 4 * kernel_size; } } else { int cnt_y[4] = {imy0, (col_i + 1) / out_w, (col_i + 2) / out_w, imy3}; int cnt_x[4] = {imx0, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, imx3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < 3; ky++) for (int kx = 0; kx < 3; kx++) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } // final 4 input int col_i = out_xy & -4; if (col_end3) { float* cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) { for (int ky = 0; ky < 3; ky++) { for (int kx = 0; kx < 3; kx++) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (i < col_end3 && imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } } } else { int out_xy = out_w * out_h; #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < out_xy - 3; col_i += 4) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int col_end3 = out_xy & 3; float* cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < (k_h * d_h); ky += d_h) for (int kx = 0; kx < (k_w * d_w); kx += d_w) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } int col_i = out_xy & -4; float* cur_col; int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int col_end3 = out_xy & 3; if (col_end3) { cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < (k_h * d_h); ky += d_h) for (int kx = 0; kx < (k_w * d_w); kx += d_w) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (i < col_end3 && imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } } static void sgemm_set(float* col, float* kernel, float* biases, float* output, int kernel_size, int ch_start, int ch_end, int output_xy, int activation, int num_thread, int cpu_affinity) { int nn_outch = ch_end / PER_OUT_CHAN; int col_end3 = output_xy & 0x3; if (col_end3) { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * PER_OUT_CHAN; float* biasptr = biases ? ( float* )(biases + p) : NULL; float* kernel_tmp = ( float* )(kernel + p * kernel_size); float* output_tmp = ( float* )(output + p * output_xy); int col_line = 0; for (col_line = 0; col_line + 3 < output_xy; col_line += 4) { float* col_tmp = ( float* )(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, output_tmp + col_line, output_xy, activation, 0); // FIXME: replace with sgemm_4x16_rv64 } { float result[64]; float* col_tmp = ( float* )(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, result, 4, activation, 0); // FIXME: replace with sgemm_4x16_rv64 for (int i = 0; i < 16; i++) { for (int j = 0; j < (col_end3); j++) *(output + (p + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } } else { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * PER_OUT_CHAN; float* biasptr = biases ? ( float* )(biases + p) : NULL; float* kernel_tmp = ( float* )(kernel + p * kernel_size); float* output_tmp = ( float* )(output + p * output_xy); for (int col_line = 0; col_line + 3 < output_xy; col_line += 4) { float* col_tmp = ( float* )(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, output_tmp + col_line, output_xy, activation, 0); // FIXME: replace with sgemm_4x16_rv64 } } } } static void sgemm4x4(float* col, float* kernel, float* biases, float* output, int kernel_size, int ch_start, int ch_end, int output_xy, int activation, int num_thread, int cpu_affinity) { float result[16]; int col_end3 = output_xy & 0x3; int kernel_end3 = ch_end & 0x3; #pragma omp parallel for num_threads(num_thread) private(result) for (int kernel_num = ch_start; kernel_num < ((ch_end & -4)-3); kernel_num += 4) { float* cur_biases = NULL; float *cur_col, *cur_kernel, *cur_output; int col_line; if (biases) cur_biases = ( float* )(biases + kernel_num); cur_kernel = ( float* )(kernel + kernel_num * kernel_size); cur_output = ( float* )(output + kernel_num * output_xy); for (col_line = 0; col_line < (output_xy & -4); col_line += 4) { cur_col = ( float* )(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, cur_output + col_line, output_xy, activation, 0); } if (col_end3) { cur_col = ( float* )(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < 4; i++) { for (int j = 0; j < (col_end3); j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } if (kernel_end3) { int kernel_num = (ch_end & -4); float* cur_biases = NULL; if (biases) cur_biases = ( float* )(biases + kernel_num); float* cur_kernel = ( float* )(kernel + kernel_num * kernel_size); #pragma omp parallel for num_threads(num_thread) private(result) for (int col_line = 0; col_line < (output_xy & -4); col_line += 4) { float* cur_col = ( float* )(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < kernel_end3; i++) for (int j = 0; j < 4; j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } int col_line = output_xy & -4; if (col_end3) { float* cur_col = ( float* )(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < (kernel_end3); i++) { for (int j = 0; j < (col_end3); j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } } /* check the conv wheather need to be using winograd */ static int winograd_support(struct conv_param* param, int in_h, int in_w) { int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int output_chan = param->output_channel; int group = param->group; if (in_h < 7 && in_w < 7) return 0; if (in_h < 10 && in_w < 10 && output_chan < 16) return 0; if (group != 1 || kernel_h != 3 || kernel_w != 3) return 0; if (dilation_h != 1 || dilation_w != 1 || stride_h != 1 || stride_w != 1) return 0; return 1; } /* * get the memory size for im2col of input tensor */ int conv_hcl_get_shared_mem_size(struct ir_tensor* input, struct ir_tensor* output, struct conv_param* param) { int in_h = input->dims[2]; int in_w = input->dims[3]; int out_h = output->dims[2]; int out_w = output->dims[3]; int group = param->group; int input_chan = param->input_channel / group; int kernel_size = input_chan * param->kernel_h * param->kernel_w; int out_cstep = out_h * out_w; // channel cstep, output_h * output_w int elem_size = input->elem_size; // uint8/int8 is 1 byte, fp32 is 4 bytes out_cstep = (out_cstep + 3) / 4 * 4; int mem_size = elem_size * kernel_size * out_cstep + 128; return mem_size; } /* * get the memory size for im2col + sgemm of kernel tensor interleave */ static int get_private_mem_size(struct ir_tensor* filter, struct conv_param* param) { int group = param->group; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int mem_size = kernel_size * filter->elem_size * out_chan_align4 * group + 128; // caution return mem_size; } int conv_hcl_set_shared_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_mem = 1; priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; return 0; } int conv_hcl_set_shared_pack4_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_pack4_mem = 0; priv_info->im2col_buffer_pack4 = NULL; priv_info->im2col_buffer_pack4_size = 0; return 0; } int conv_hcl_get_shared_pack4_mem_size(struct ir_tensor* filter, struct ir_tensor* output, struct conv_param* param) { return 0; } int conv_hcl_prerun(struct ir_tensor* input_tensor, struct ir_tensor* filter_tensor, struct ir_tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param) { int in_c = input_tensor->dims[1]; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; /* check winograd implement, only for conv3x3s1 */ // priv_info->winograd = winograd_support(param, in_h, in_w); // if (priv_info->winograd) // { // if(in_c >= 256) // // return wino_conv_hcl_prerun_1(input_tensor, filter_tensor, output_tensor, priv_info, param); // FIXME: add wino support // else // // return wino_conv_hcl_prerun(input_tensor, filter_tensor, output_tensor, priv_info, param); // FIXME: add wino support // } /* alloc mem of im2col */ if (!priv_info->external_im2col_mem) { int mem_size = conv_hcl_get_shared_mem_size(input_tensor, output_tensor, param); void* mem = sys_malloc(mem_size); priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; } /* alloc mem of kernel interleave */ if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor, param); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } /* kernel interleave */ interleave(filter_tensor, priv_info, param); return 0; } int conv_hcl_postrun(struct conv_priv_info* priv_info) { // if (priv_info->winograd) // { // wino_conv_hcl_postrun(priv_info); // FIXME: add wino support // } if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } if (!priv_info->external_im2col_mem && priv_info->im2col_buffer != NULL) { sys_free(priv_info->im2col_buffer); priv_info->im2col_buffer = NULL; } return 0; } int conv_hcl_run(struct ir_tensor* input_tensor, struct ir_tensor* filter_tensor, struct ir_tensor* bias_tensor, struct ir_tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param, int num_thread, int cpu_affinity) { /* param */ int group = param->group; int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int pad_h0 = param->pad_h0; int pad_h1 = param->pad_h1; int pad_w0 = param->pad_w0; int pad_w1 = param->pad_w1; int act_type = param->activation; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int input_image_size = input_tensor->dims[1] * input_tensor->dims[2] * input_tensor->dims[3]; // if (priv_info->winograd) // { // if(in_c >= 256) // return wino_conv_hcl_run_1(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, num_thread, cpu_affinity); // FIXME: add wino support // else // return wino_conv_hcl_run(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, num_thread, cpu_affinity); // FIXME: add wino support // } int out_c = output_tensor->dims[1] / group; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); int output_image_size = output_tensor->dims[1] * output_tensor->dims[2] * output_tensor->dims[3]; /* buffer addr */ float* input_buf = ( float* )input_tensor->data; float* output_buf = ( float* )output_tensor->data; float* biases_buf = NULL; if (bias_tensor != NULL) biases_buf = ( float* )bias_tensor->data; float* col_buf = ( float* )priv_info->im2col_buffer; float* interleave_buf = ( float* )priv_info->interleave_buffer; int sgemm_set_chan = out_c / PER_OUT_CHAN * PER_OUT_CHAN; int sgemm_set_remain = out_c % PER_OUT_CHAN; for (int n = 0; n < batch; n++) // batch size { for (int g = 0; g < group; g++) { /* im2col */ float* cur_input = input_buf + n * input_image_size + g * input_size; im2col(cur_input, col_buf, in_c, in_w, in_h, kernel_w, kernel_h, stride_w, stride_h, dilation_w, dilation_h, pad_w0, pad_w1, pad_h0, pad_h1, out_w, out_h, num_thread); /* gemm */ float* cur_kernel = interleave_buf + g * kernel_size * out_c_align; float* cur_output = output_buf + n * output_image_size + g * output_size; float* cur_bias = biases_buf ? (biases_buf + g * out_c) : NULL; sgemm_set(col_buf, cur_kernel, cur_bias, cur_output, kernel_size, 0, sgemm_set_chan, out_hw, act_type, num_thread, cpu_affinity); if (sgemm_set_remain) sgemm4x4(col_buf, cur_kernel, cur_bias, cur_output, kernel_size, sgemm_set_chan, out_c, out_hw, act_type, num_thread, cpu_affinity); } } return 0; }
raw2iq.c
// raw2iq.c - A tool for converting RASDRstreamer .raw files to interleaved I,Q // // Acknowledgements: // http://stackoverflow.com/questions/14386/fopen-deprecated-warning #if defined(_MSC_VER) #define _CRT_SECURE_NO_DEPRECATE #endif #include <stdio.h> #include <stdlib.h> #include <ctype.h> // for tolower() #include <limits.h> #include <stdint.h> // for uint16_t, etc. //#include <errno.h> //#include <time.h> // for clock() #include <string.h> #ifdef _OPENMP #include <omp.h> #endif // http://stackoverflow.com/questions/1546789/clean-code-to-printf-size-t-in-c-or-nearest-equivalent-of-c99s-z-in-c #if defined(_MSC_VER) || defined(__MINGW32__) //__MINGW32__ should go before __GNUC__ #define __SIZE_T_SPECIFIER "%Iu" #define __SSIZE_T_SPECIFIER "%Id" #define __PTRDIFF_T_SPECIFIER "%Id" #else //elif defined(__GNUC__) #define __SIZE_T_SPECIFIER "%zu" #define __SSIZE_T_SPECIFIER "%zd" #define __PTRDIFF_T_SPECIFIER "%zd" #endif #if defined(_MSC_VER) #define strcasecmp _stricmp #define snprintf _snprintf static FILE *_fopen(const char *f, const char *m) { FILE *fp = NULL; int e = fopen_s(&fp, f, m); return fp; } #define fopen(F,M) _fopen(F,M) #else #include <strings.h> // POSIX #endif struct _global { const char *infile; const char *outfile; const char *ofmt; FILE *infd; FILE *outfd; int threads; int verbose; uint16_t otm_polarity; uint16_t flag_mask; uint16_t flag_value; uint16_t iq_polarity; } g = { NULL, NULL, "wb", NULL, NULL, 0, 0, 1, 3, 3, 0 }; typedef union _sample { struct _b { int16_t sample : 12; uint16_t iqsel : 1; uint16_t flag : 2; uint16_t pps : 1; } s; uint16_t ui; int16_t i; } sample_t; void usage( const char *argv0 ) { printf("Convert RASDRstreamer raw stream into a I/Q output" "\n" "\nUsage:" "\n%s [OPTIONS]" "\nWhere:" "\n -i, --input-file FILE Full path to file to be read or - for stdin" "\n -o, --output-file FILE Full path to file to be written or - for stdout" "\n --iq-polarity N Define starting I/Q polarity level" "\n (0=I sample first, 1=Q sample first, default=0)" "\n --pps-polarity N Define OTM/PPS polarity level" "\n (0=active low, 1=active high, default=0)" "\n --flag-value HEX Define FLAGs code for valid data" "\n (two bits, default=3)" "\n --flag-mask HEX Define FLAGs mask (two bits, default=3)" "\n -v Increment verbosity level" "\n --verbose N Define verbosity level (0=quiet, 1=info, 2=trace)" "\n -h, --help Print this help" "\n\nExamples:" "\n\n%s < RASDRviewer.raw > test.dat" "\nConverts the .raw file to a binary interleaved 16-bit signed I/Q format file." "\n\n%s < RASDRviewer.raw -o test.csv" "\nConverts the .raw file to an ASCII 16-bit signed I/Q comma separated file." "\n\n", argv0, argv0, argv0); exit(1); } // http://stackoverflow.com/questions/5309471/getting-file-extension-in-c const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return ""; return dot + 1; } const char *get_filename_format(const char *ext) { if(!ext) return "wb"; else if(strcasecmp(ext,"csv")==0) return "w"; else if(strcasecmp(ext,"txt")==0) return "w"; return "wb"; } void argparse( int argc, char *argv[], char *envp[] ) { int i; // dependency-free simple argument parsing for (i = 1; i < argc; i++) { const char *key = argv[i]; if (strcmp(key,"--") == 0) break; // stop parsing arguments else if (strncmp(key, "-h", 2) == 0 || strncmp(key, "--help", 6) == 0) { usage(argv[0]); } else if (strcmp(key, "-i") == 0 || strncmp(key, "--input-file", 12) == 0) { if ((i + 1) >= argc) break; g.infile = argv[++i]; } else if (strncmp(key, "-o", 2) == 0 || strncmp(key, "--output-file", 13) == 0) { if ((i + 1) >= argc) break; g.outfile = argv[++i]; } else if (strncmp(key, "--pps-polarity", 14) == 0) { if ((i + 1) >= argc) break; g.otm_polarity = atoi(argv[++i])? 1 : 0; } else if (strncmp(key, "--iq-polarity", 13) == 0) { if ((i + 1) >= argc) break; g.iq_polarity = atoi(argv[++i])? 1 : 0; } else if (strncmp(key, "--flag-mask", 11) == 0) { if ((i + 1) >= argc) break; g.flag_mask = atoi(argv[++i]); } else if (strncmp(key, "--flag-value", 12) == 0) { if ((i + 1) >= argc) break; g.flag_value = atoi(argv[++i]); } else if (strncmp(key, "-v", 2) == 0) g.verbose++; else if (strncmp(key, "--verbose", 9) == 0) { if ((i + 1) >= argc) break; g.verbose = atoi(argv[++i]); } } if (g.infile == NULL || strcmp(g.infile,"-") == 0) { g.infd = stdin; g.infile = "stdin"; } else { g.infd = fopen(g.infile, "rb"); // NB: input stream must be labeled binary if (g.infd == NULL) { perror("cannot open input file"); exit(1); } } if (g.outfile == NULL || strcmp(g.outfile,"-") == 0) { g.outfd = stdout; g.outfile = "stdout"; } else { g.ofmt = get_filename_format(get_filename_ext(g.outfile)); g.outfd = fopen(g.outfile, g.ofmt); if (g.outfd == NULL) { perror("cannot open output file"); exit(1); } } #ifdef _OPENMP g.threads = omp_get_max_threads(); #else g.threads = 1; #endif } // http://stackoverflow.com/questions/1644868/c-define-macro-for-debug-printing // http://stackoverflow.com/questions/7788850/macro-definition // http://blog.mellenthin.de/archives/2010/10/26/portable-__va_args__-macros-for-linux-hp-ux-solaris-and-aix/comment-page-1/ #define LOG(fmt, ...) \ do { fprintf(stderr, fmt, ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ if (g.verbose>0) { fprintf(stderr, fmt, ##__VA_ARGS__); } #define TRACE(fmt, ...) \ if (g.verbose>1) { fprintf(stderr, fmt, ##__VA_ARGS__); } #define PAGE 4096 int main(int argc, char *argv[], char *envp[]) { argparse(argc,argv,envp); INFO("input=%s\n",g.infile); INFO("output=%s, fmt=%s\n", g.outfile, g.ofmt); INFO("CPU Threads=%d\n", g.threads); TRACE("sizeof(sample_t)="__SIZE_T_SPECIFIER"\n", sizeof(sample_t)); TRACE("polarity otm,iq=%hu,%hu\n", g.otm_polarity, g.iq_polarity); TRACE("flag_mask,value=%hu,%hu\n", g.flag_mask, g.flag_value); //exit(1); { uint8_t *b = (uint8_t *)malloc(g.threads*PAGE); // Binary output buffer char *a = (char *)malloc(g.threads*PAGE*8); // ASCII output buffer char *t = (char *)malloc(g.threads*PAGE); // On-Time-Marker (OTM) indicator char *x = (char *)malloc(g.threads*PAGE); // Invalid Sample indicator // shared scalars for diagnostics/reductions size_t t_count = 0, x_count = 0; size_t n_count = 0, r_count = 0; // private loop counters int i, j; //#pragma omp parallel //{ // apply first-touch principle to initialize memory #pragma omp parallel for private(i) for (i=0; i < g.threads; i++) { memset(&b[i*PAGE], 0, PAGE); memset(&a[i*PAGE*8], 0, PAGE*8); memset(&t[i*PAGE], 0, PAGE); memset(&x[i*PAGE], 0, PAGE); } // read input stream in strict sequence ordering while ( !feof(g.infd) ) { size_t n, r; //#pragma omp master n = fread(b, PAGE, g.threads, g.infd); //#pragma omp barrier //TRACE("n="__SIZE_T_SPECIFIER", err=%d%s\n", n, ferror(g.infd), feof(g.infd)?" EOF":""); if (ferror(g.infd)) { perror(g.infile); } if ( n < 1 ) TRACE("did not read enough bytes to process a full PAGE\n"); if ( n < 1 ) break; // TODO: inspect first sample of each block to determine I/Q mismatch, // if so, convert the last sample of each block and place in a // hold buffer to be used by the next block. This will properly // re-align I/Q mismatches once they occur. // remove control bits and handle I,Q exceptions #pragma omp parallel for private(i,j) for (i=0; i < g.threads; i++) { sample_t *in = (sample_t *)&b[i*PAGE]; int16_t *out = (int16_t *)in; char *otm = (char *)&t[i*PAGE]; char *xcc = (char *)&x[i*PAGE]; //http://stackoverflow.com/questions/7661114/the-openmp-master-pragma-must-not-be-enclosed-by-the-parallel-for-pragma //#pragma omp master it is error //#pragma omp critical it is right #ifdef _OPENMP if (g.verbose > 2 && omp_get_thread_num() == 0) #else if (g.verbose > 2) #endif { sample_t *_iq = in; char _tag[6]; int _s; TRACE("--- Coded input block ---\n"); for (_s = 0; _s<32; _s++, _iq++) // N=number of samples to dump { snprintf(_tag, sizeof(_tag), "%c%04d", _s % 2 ? 'q' : 'i', _s / 2); _tag[5] = '\0'; TRACE("%s=0x%04x, sample=%+5d, iqsel=%u, flag=%#x, pps=%u\n", _tag, _iq->ui, _iq->s.sample, _iq->s.iqsel, _iq->s.flag, _iq->s.pps); } } memset(otm, 0, PAGE); // OTM is cleared in each block memset(xcc, 0, PAGE); // invalid is cleared in each block if ( (unsigned)i >= n ) continue; // this thread did get a block read - does no work for (j=0; j < PAGE/2; j+=2, in+=2) // PAGE/sizeof(sample_t) { sample_t *_i, *_q; if ( g.iq_polarity ) { _q = &in[0]; _i = &in[1]; } else { _i = &in[0]; _q = &in[1]; } if ( _i->s.iqsel || (_i->s.flag & g.flag_mask) != g.flag_value ) { xcc[j] = 1; } if ( _i->s.pps == g.otm_polarity ) { otm[j] = 1; } *out++ = _i->s.sample; if ( !_q->s.iqsel || (_q->s.flag & g.flag_mask) != g.flag_value ) { xcc[j + 1] = 1; } if ( _q->s.pps == g.otm_polarity) { otm[j + 1] = 1; } *out++ = _q->s.sample; // DEBUG #ifdef _OPENMP if ( g.verbose > 1 && (otm[j] || xcc[j]) && omp_get_thread_num() == 0 ) #else if ( g.verbose > 1 && (otm[j] || xcc[j]) ) #endif { char _tag[6]; static int _max = 10; if (_max > 0) { snprintf(_tag, sizeof(_tag), "%c%04d", j % 2 ? 'q' : 'i', j / 2); _tag[5] = '\0'; TRACE("block="__SIZE_T_SPECIFIER",%s=0x%04x%s%s\n", n_count, _tag, _i->ui, xcc[j]?",INVALID":"", otm[j]?",OTM":""); _max--; if (_max==0) TRACE("*** MAX I sample diagnostic output\n"); } } #ifdef _OPENMP if ( g.verbose > 1 && (otm[j+1] || xcc[j+1]) && omp_get_thread_num() == 0 ) #else if ( g.verbose > 1 && (otm[j+1] || xcc[j+1]) ) #endif { char _tag[6]; static int _max = 10; if (_max > 0) { snprintf(_tag, sizeof(_tag), "%c%04d", (j+1) % 2 ? 'q' : 'i', (j+1) / 2); _tag[5] = '\0'; TRACE("block="__SIZE_T_SPECIFIER",%s=0x%04x%s%s\n", n_count, _tag, _q->ui, xcc[j+1]?",INVALID":"", otm[j+1]?",OTM":""); _max--; if (_max==0) TRACE("*** MAX Q sample diagnostic output\n"); } } } //http://stackoverflow.com/questions/7661114/the-openmp-master-pragma-must-not-be-enclosed-by-the-parallel-for-pragma //#pragma omp master it is error //#pragma omp critical it is right #ifdef _OPENMP if (g.verbose > 3 && omp_get_thread_num() == 0) #else if (g.verbose > 3) #endif { int16_t *_iq = (int16_t *)&b[i*PAGE]; char _tag[6]; int _s; TRACE("--- Decoded input block ---\n"); for (_s = 0; _s<32; _s++, _iq++) // N=number of samples to dump { snprintf(_tag, sizeof(_tag), "%c%04d", _s % 2 ? 'q' : 'i', _s / 2); _tag[5] = '\0'; TRACE("%s, sample=%+5d, otm=%d, xcc=%d\n", _tag, *_iq, otm[_s], xcc[_s]); } } } // render ASCII output if( g.ofmt[1] == '\0' ) { // TODO: figure out why we get a blob of NUL characters every 1024 samples #pragma omp parallel for private(i,j) for (i=0; i < g.threads; i++) { int16_t *in = (int16_t *)&b[i*PAGE]; char *out = (char *)&a[i*PAGE*8]; char *otm = (char *)&t[i*PAGE]; char *xcc = (char *)&x[i*PAGE]; if ( (unsigned)i >= n ) continue; // this thread did get a block read - does no work for (j=0; j < PAGE/2; j+=2) // PAGE/sizeof(sample_t) { const char f1 = (xcc[j] || xcc[j + 1]) ? 'X' : ' '; const char f2 = (otm[j] || otm[j + 1]) ? 'T' : ' '; //#pragma warning(disable:4996) snprintf(&out[j * 8], 16, "%+5d,%+5d,%c%c\r\n",*in++, *in++, f1, f2); } } #ifdef _OPENMP if (g.verbose > 3 && omp_get_thread_num() == 0) #else if (g.verbose > 3) #endif { char _s[(32*16)+1]; memcpy(_s,a,32*16); _s[sizeof(_s)-1] = '\0'; TRACE("--- ASCII output block ---\n"); TRACE("%s\n",_s); } // TODO: refine the timestamp for the first sample of the output block // and figure out a way to express it in the ASCII output stream //#pragma omp master r = fwrite(a,PAGE*8,n,g.outfd); // NB: output is *exactly* 8 times larger than the input buffer //#pragma omp barrier } // render BINARY output else if( g.ofmt[1] == 'b' ) { // TODO: refine the timestamp for the first sample of the output block // TODO: produce the ASCII index file correlating sample with timestamp #ifdef _OPENMP if (g.verbose > 3 && omp_get_thread_num() == 0) #else if (g.verbose > 3) #endif { uint16_t *_hex = (uint16_t *)b; int16_t *_iq = (int16_t *)b; char _tag[6]; int _s; TRACE("--- Binary output block ---\n"); for (_s = 0; _s<32; _s++, _hex++, _iq++) // N=number of samples to dump { snprintf(_tag, sizeof(_tag), "%c%04d", _s % 2 ? 'q' : 'i', _s / 2); _tag[5] = '\0'; TRACE("%s=0x%04x, sample=%+5d\n", _tag, *_hex, *_iq); } } //#pragma omp master r = fwrite(b,PAGE,n,g.outfd); //#pragma omp barrier } // render NO output else { #ifdef _OPENMP if (g.verbose > 3 && omp_get_thread_num() == 0) #else if (g.verbose > 3) #endif { TRACE("--- Render No Output ---\n"); } //#pragma omp master r = n; //#pragma omp barrier } //TRACE("r="__SIZE_T_SPECIFIER"\n", r); //#pragma omp master n_count = n_count + n; r_count = r_count + r; //#pragma omp barrier // Diagnostics #pragma omp parallel for private(i,j) reduction(+:t_count,x_count) for (i=0; i < g.threads; i++) { char *otm = (char *)&t[i*PAGE]; char *xcc = (char *)&x[i*PAGE]; if ( (unsigned)i >= n ) continue; for (j=0; j < PAGE; j++) { t_count = t_count + otm[j]; x_count = x_count + xcc[j]; } } //TRACE("t_count="__SIZE_T_SPECIFIER"\n", t_count); //TRACE("x_count="__SIZE_T_SPECIFIER"\n", x_count); } // while(!feof) //} // parallel LOG(__SIZE_T_SPECIFIER" records in\n",n_count); LOG(__SIZE_T_SPECIFIER" records out\n",r_count); if (t_count > 0) INFO(__SIZE_T_SPECIFIER" On-Time-Markers\n", t_count); if (x_count > 0) INFO(__SIZE_T_SPECIFIER" Invalid Samples\n", x_count); if (n_count > 0) INFO(__SIZE_T_SPECIFIER" Total Samples\n", n_count * (PAGE/2)); } if( g.infd ) fclose(g.infd); if( g.outfd ) fclose(g.outfd); return 0; }
krb5pa-sha1_fmt_plug.c
/* * Kerberos 5 "PA ENC TIMESTAMP" by magnum (modified by Dhiru) * * Pcap file -> input file: * 1. tshark -r capture.pcapng -T pdml > ~/capture.pdml * 2. krbng2john.py ~/capture.pdml > krb5.in * 3. Run john on krb5.in * * http://www.ietf.org/rfc/rfc4757.txt * http://www.securiteam.com/windowsntfocus/5BP0H0A6KM.html * * Input format is 'user:$krb5pa$etype$user$realm$salt$timestamp+checksum' * * NOTE: Checksum implies last 12 bytes of PA_ENC_TIMESTAMP value in AS-REQ * packet. * * Default Salt: realm + user * * AES-256 encryption & decryption of AS-REQ timestamp in Kerberos v5 * See the following RFC for more details about the crypto & algorithms used: * * RFC3961 - Encryption and Checksum Specifications for Kerberos 5 * RFC3962 - Advanced Encryption Standard (AES) Encryption for Kerberos 5 * * march 09 / kevin devine <wyse101 0x40 gmail.com> * * This software is Copyright (c) 2011 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * This software is Copyright (c) 2012 Dhiru Kholia (dhiru at openwall.com) and * released under same terms as above */ #if FMT_EXTERNS_H extern struct fmt_main fmt_krb5pa; #elif FMT_REGISTERS_H john_register_one(&fmt_krb5pa); #else #include <errno.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #define OMP_SCALE 64 #endif #include "arch.h" #include "misc.h" #include "formats.h" #include "options.h" #include "common.h" #include "unicode.h" #include "johnswap.h" #include "aes/aes.h" #include "gladman_fileenc.h" #include "pbkdf2_hmac_sha1.h" #include "loader.h" #include "memdbg.h" #define FORMAT_LABEL "krb5pa-sha1" #define FORMAT_NAME "Kerberos 5 AS-REQ Pre-Auth etype 17/18" /* aes-cts-hmac-sha1-96 */ #ifdef MMX_COEF #define ALGORITHM_NAME SHA1_N_STR MMX_TYPE #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 12 #define BINARY_ALIGN 4 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #ifdef MMX_COEF #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define MAX_SALTLEN 128 #define MAX_REALMLEN 64 #define MAX_USERLEN 64 #define TIMESTAMP_SIZE 44 #define CHECKSUM_SIZE BINARY_SIZE #define TOTAL_LENGTH (14 + 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) + MAX_REALMLEN + MAX_USERLEN + MAX_SALTLEN) #define HEXCHARS "0123456789abcdefABCDEF" static struct fmt_tests tests[] = { {"$krb5pa$18$user1$EXAMPLE.COM$$2a0e68168d1eac344da458599c3a2b33ff326a061449fcbc242b212504e484d45903c6a16e2d593912f56c93883bf697b325193d62a8be9c", "openwall"}, {"$krb5pa$18$user1$EXAMPLE.COM$$a3918bd0381107feedec8db0022bdf3ac56e534ed54d13c62a7013a47713cfc31ef4e7e572f912fa4164f76b335e588bf29c2d17b11c5caa", "openwall"}, {"$krb5pa$18$l33t$EXAMPLE.COM$$98f732b309a1d7ef2355a974842a32894d911e97150f5d57f248e1c2632fbd3735c5f156532ccae0341e6a2d779ca83a06021fe57dafa464", "openwall"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$64dfeee04be2b2e0423814e0df4d0f960885aca4efffe6cb5694c4d34690406071c4968abd2c153ee42d258c5e09a41269bbcd7799f478d3", "password@123"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$AD.EXAMPLE.COMaduser$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, /* etype 17 hash obtained using MiTM etype downgrade attack */ {"$krb5pa$17$user1$EXAMPLE.COM$$c5461873dc13665771b98ba80be53939e906d90ae1ba79cf2e21f0395e50ee56379fbef4d0298cfccfd6cf8f907329120048fd05e8ae5df4", "openwall"}, {NULL}, }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { int etype; unsigned char realm[64]; unsigned char user[64]; unsigned char salt[128]; /* realm + user */ unsigned char ct[44]; } *cur_salt; static unsigned char constant[16]; static unsigned char ke_input[16]; static unsigned char ki_input[16]; /* n-fold(k-bits): * l = lcm(n,k) * r = l/k * s = k-bits | k-bits rot 13 | k-bits rot 13*2 | ... | k-bits rot 13*(r-1) * compute the 1's complement sum: * n-fold = s[0..n-1]+s[n..2n-1]+s[2n..3n-1]+..+s[(k-1)*n..k*n-1] */ /* representation: msb first, assume n and k are multiples of 8, and * that k>=16. this is the case of all the cryptosystems which are * likely to be used. this function can be replaced if that * assumption ever fails. */ /* input length is in bits */ static void nfold(unsigned int inbits, const unsigned char *in, unsigned int outbits,unsigned char *out) { int a,b,c,lcm; int byte, i, msbit; /* the code below is more readable if I make these bytes * instead of bits */ inbits >>= 3; outbits >>= 3; /* first compute lcm(n,k) */ a = outbits; b = inbits; while (b != 0) { c = b; b = a % b; a = c; } lcm = outbits*inbits/a; /* now do the real work */ memset(out, 0, outbits); byte = 0; /* this will end up cycling through k lcm(k,n)/k times, which * is correct */ for (i = lcm - 1; i >= 0; i--) { /* compute the msbit in k which gets added into this byte */ msbit = (/* first, start with the msbit in the first, unrotated byte */ ((inbits << 3) - 1) /* then, for each byte, shift to the right for each * repetition */ +(((inbits << 3) + 13) * (i / inbits)) /* last, pick out the correct byte within that * shifted repetition */ +((inbits - (i % inbits)) << 3) ) % (inbits << 3); /* pull out the byte value itself */ byte += (((in[((inbits - 1) - (msbit >> 3)) % inbits] << 8)| (in[((inbits) - (msbit>>3)) % inbits])) >>((msbit & 7) + 1)) & 0xff; /* do the addition */ byte += out[i % outbits]; out[i % outbits] = byte & 0xff; /* keep around the carry bit, if any */ byte >>= 8; } /* if there's a carry bit left over, add it back in */ if (byte) { for (i = outbits - 1; i >= 0; i--) { /* do the addition */ byte += out[i]; out[i] = byte & 0xff; /* keep around the carry bit, if any */ byte >>= 8;\ } } } static void init(struct fmt_main *self) { unsigned char usage[5]; #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); // generate 128 bits from 40 bits of "kerberos" string nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0xAA; // used to derive Ke nfold(sizeof(usage)*8,usage,sizeof(ke_input)*8,ke_input); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0x55; // used to derive Ki nfold(sizeof(usage)*8,usage,sizeof(ki_input)*8,ki_input); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext; int type, saltlen = 0; // tag is mandatory if (strncmp(ciphertext, "$krb5pa$", 8) != 0) return 0; data += 8; // etype field, 17 or 18 p = strchr(data, '$'); if (!p || p - data != 2) return 0; type = atoi(data); if (type < 17 || type > 18) return 0; data = p + 1; // user field p = strchr(data, '$'); if (!p || p - data > MAX_USERLEN) return 0; saltlen += p - data; data = p + 1; // realm field p = strchr(data, '$'); if (!p || p - data > MAX_REALMLEN) return 0; saltlen += p - data; data = p + 1; // salt field p = strchr(data, '$'); if (!p) return 0; // if salt is empty, realm.user is used instead if (p - data) saltlen = p - data; data = p + 1; // We support a max. total salt length of 52. // We could opt to emit a warning if rejected here. if(saltlen > MAX_SALTLEN) { static int warned = 0; if (!ldr_in_pot) if (!warned++) fprintf(stderr, "%s: One or more hashes rejected due to salt length limitation\n", FORMAT_LABEL); return 0; } // 56 bytes (112 hex chars) encrypted timestamp + checksum if (strlen(data) != 2 * (TIMESTAMP_SIZE + CHECKSUM_SIZE) || strspn(data, HEXCHARS) != strlen(data)) return 0; return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; ctcopy += 8; p = strtok(ctcopy, "$"); cs.etype = atoi(p); p = strtok(NULL, "$"); if (p[-1] == '$') cs.user[0] = 0; else { strcpy((char*)cs.user, p); p = strtok(NULL, "$"); } if (p[-1] == '$') cs.realm[0] = 0; else { strcpy((char*)cs.realm, p); p = strtok(NULL, "$"); } if (p[-1] == '$') { strcpy((char*)cs.salt, (char*)cs.realm); strcat((char*)cs.salt, (char*)cs.user); } else { strcpy((char*)cs.salt, p); p = strtok(NULL, "$"); } for (i = 0; i < TIMESTAMP_SIZE; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void set_key(char *key, int index) { int saved_key_length = strlen(key); if (saved_key_length > PLAINTEXT_LENGTH) saved_key_length = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_key_length); saved_key[index][saved_key_length] = 0; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[TOTAL_LENGTH + 1]; char in[TOTAL_LENGTH + 1]; char salt[MAX_SALTLEN + 1]; char *data; char *e, *u, *r, *s, *tc; strnzcpy(in, ciphertext, sizeof(in)); tc = strrchr(in, '$'); *tc++ = 0; s = strrchr(in, '$'); *s++ = 0; r = strrchr(in, '$'); *r++ = 0; u = strrchr(in, '$'); *u++ = 0; e = in + 8; /* Default salt is user.realm */ if (!*s) { snprintf(salt, sizeof(salt), "%s%s", r, u); s = salt; } snprintf(out, sizeof(out), "$krb5pa$%s$%s$%s$%s$%s", e, u, r, s, tc); data = out + strlen(out) - 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) - 1; strlwr(data); return out; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1 + TIMESTAMP_SIZE * 2; /* skip to checksum field */ for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static char *get_key(int index) { return saved_key[index]; } static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void AES_cts_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec, const int encryptp) { unsigned char tmp[AES_BLOCK_SIZE]; unsigned int i; if (encryptp) { while(len > AES_BLOCK_SIZE) { for (i = 0; i < AES_BLOCK_SIZE; i++) tmp[i] = in[i] ^ ivec[i]; AES_encrypt(tmp, out, key); memcpy(ivec, out, AES_BLOCK_SIZE); len -= AES_BLOCK_SIZE; in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; } for (i = 0; i < len; i++) tmp[i] = in[i] ^ ivec[i]; for (; i < AES_BLOCK_SIZE; i++) tmp[i] = 0 ^ ivec[i]; AES_encrypt(tmp, out - AES_BLOCK_SIZE, key); memcpy(out, ivec, len); memcpy(ivec, out - AES_BLOCK_SIZE, AES_BLOCK_SIZE); } else { unsigned char tmp2[AES_BLOCK_SIZE]; unsigned char tmp3[AES_BLOCK_SIZE]; while(len > AES_BLOCK_SIZE * 2) { memcpy(tmp, in, AES_BLOCK_SIZE); AES_decrypt(in, out, key); for (i = 0; i < AES_BLOCK_SIZE; i++) out[i] ^= ivec[i]; memcpy(ivec, tmp, AES_BLOCK_SIZE); len -= AES_BLOCK_SIZE; in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; } len -= AES_BLOCK_SIZE; memcpy(tmp, in, AES_BLOCK_SIZE); /* save last iv */ AES_decrypt(in, tmp2, key); memcpy(tmp3, in + AES_BLOCK_SIZE, len); memcpy(tmp3 + len, tmp2 + len, AES_BLOCK_SIZE - len); /* xor 0 */ for (i = 0; i < len; i++) out[i + AES_BLOCK_SIZE] = tmp2[i] ^ tmp3[i]; AES_decrypt(tmp3, out, key); for (i = 0; i < AES_BLOCK_SIZE; i++) out[i] ^= ivec[i]; memcpy(ivec, tmp, AES_BLOCK_SIZE); } } // keysize = 32 for 256 bits, 16 for 128 bits static void dk(unsigned char key_out[], unsigned char key_in[], size_t key_size, unsigned char ptext[], size_t ptext_size) { unsigned char iv[32]; unsigned char plaintext[32]; AES_KEY ekey; memset(iv,0,sizeof(iv)); memset(plaintext,0,sizeof(plaintext)); memcpy(plaintext,ptext,16); AES_set_encrypt_key(key_in,key_size*8,&ekey); AES_cbc_encrypt(plaintext,key_out,key_size,&ekey,iv,AES_ENCRYPT); } static void krb_decrypt(const unsigned char ciphertext[], size_t ctext_size, unsigned char plaintext[], const unsigned char key[], size_t key_size) { unsigned char iv[32]; AES_KEY ekey; memset(iv,0,sizeof(iv)); AES_set_decrypt_key(key,key_size*8,&ekey); AES_cts_encrypt(ciphertext,plaintext,ctext_size,&ekey,iv,AES_DECRYPT); } #if 0 /* This is not used */ static void krb_encrypt(const unsigned char ciphertext[], size_t ctext_size, unsigned char plaintext[], const unsigned char key[], size_t key_size) { unsigned char iv[32]; AES_KEY ekey; memset(iv,0,sizeof(iv)); AES_set_encrypt_key(key,key_size*8,&ekey); AES_cts_encrypt(ciphertext,plaintext,ctext_size,&ekey,iv,AES_ENCRYPT); } #endif static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { unsigned char tkey[MAX_KEYS_PER_CRYPT][32]; unsigned char base_key[32]; unsigned char Ke[32]; unsigned char plaintext[44]; int key_size, i; int len[MAX_KEYS_PER_CRYPT]; #ifdef MMX_COEF unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { len[i] = strlen(saved_key[i+index]); pin[i] = (unsigned char*)saved_key[i+index]; pout[i] = tkey[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, len, cur_salt->salt,strlen((char*)cur_salt->salt), 4096, pout, 32, 0); #else for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { len[i] = strlen(saved_key[index+i]); } pbkdf2_sha1((const unsigned char*)saved_key[index], len[0], cur_salt->salt,strlen((char*)cur_salt->salt), 4096, tkey[0], 32, 0); #if !ARCH_LITTLE_ENDIAN { int i; for (i = 0; i < 32/sizeof(ARCH_WORD_32); ++i) { ((ARCH_WORD_32*)tkey[0])[i] = JOHNSWAP(((ARCH_WORD_32*)tkey[0])[i]); } } #endif #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { // generate 128 bits from 40 bits of "kerberos" string // This is precomputed in init() //nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); if (cur_salt->etype == 17) key_size = 16; else key_size = 32; dk(base_key, tkey[i], key_size, constant, 32); /* The "well-known constant" used for the DK function is the key usage number, * expressed as four octets in big-endian order, followed by one octet indicated below. * Kc = DK(base-key, usage | 0x99); * Ke = DK(base-key, usage | 0xAA); * Ki = DK(base-key, usage | 0x55); */ // derive Ke for decryption/encryption // This is precomputed in init() //memset(usage,0,sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0xAA; // used to derive Ke //nfold(sizeof(usage)*8,usage,sizeof(ke_input)*8,ke_input); dk(Ke, base_key, key_size, ke_input, 32); // decrypt the AS-REQ timestamp encrypted with 256-bit AES // here is enough to check the string, further computation below is required // to fully verify the checksum krb_decrypt(cur_salt->ct,44,plaintext,Ke, key_size); // Check a couple bytes from known plain (YYYYMMDDHHMMSSZ) and // bail out if we are out of luck. if (plaintext[22] == '2' && plaintext[23] == '0' && plaintext[36] == 'Z') { unsigned char Ki[32]; unsigned char checksum[20]; // derive Ki used in HMAC-SHA-1 checksum // This is precomputed in init() //memset(usage,0,sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0x55; // used to derive Ki //nfold(sizeof(usage)*8,usage,sizeof(ki_input)*8,ki_input); dk(Ki,base_key, key_size, ki_input, 32); // derive checksum of plaintext hmac_sha1(Ki, key_size, plaintext, 44, checksum, 20); memcpy(crypt_out[index+i], checksum, BINARY_SIZE); } else { memset(crypt_out[index+i], 0, BINARY_SIZE); } } } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], BINARY_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_krb5pa = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, get_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
not_enough_threads.c
// RUN: %libomp-compile && env OMP_THREAD_LIMIT=2 %libomp-run | FileCheck %s // RUN: %libomp-compile && env OMP_THREAD_LIMIT=2 %libomp-run | %sort-threads \ // RUN: | FileCheck --check-prefix=THREADS %s // REQUIRES: ompt #include "callback.h" int main() { #pragma omp parallel num_threads(4) { print_ids(0); print_ids(1); } print_fuzzy_address(1); // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback // Make sure initial data pointers are null. // CHECK-NOT: 0: parallel_data initially not null // CHECK-NOT: 0: task_data initially not null // CHECK-NOT: 0: thread_data initially not null // Only check callback names, arguments are verified in THREADS below. // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // Note that we cannot ensure that the worker threads have already called // barrier_end and implicit_task_end before parallel_end! // CHECK-DAG: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin // CHECK-DAG: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end // THREADS: 0: NULL_POINTER=[[NULL:.*$]] // THREADS: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_thread_begin // THREADS-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin // THREADS-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]] // THREADS-SAME: parent_task_frame.exit=[[NULL]] // THREADS-SAME: parent_task_frame.reenter={{0x[0-f]+}} // THREADS-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=4 // THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin // THREADS-SAME: parallel_id=[[PARALLEL_ID]] // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // THREADS: {{^}}[[MASTER_ID]]: task level 0 // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: task level 1 // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]] // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS-NOT: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // parallel_id is 0 because the region ended in the barrier! // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end // THREADS-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // THREADS-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_end // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_thread_begin // THREADS-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_begin // THREADS-SAME: parallel_id=[[PARALLEL_ID]] // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // THREADS: {{^}}[[THREAD_ID]]: task level 0 // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: task level 1 // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]] // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // parallel_id is 0 because the region ended in the barrier! // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end // THREADS-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]] return 0; }
GB_unaryop__minv_fp64_uint16.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__minv_fp64_uint16 // op(A') function: GB_tran__minv_fp64_uint16 // C type: double // A type: uint16_t // cast: double cij = (double) aij // unaryop: cij = 1./aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./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_MINV || GxB_NO_FP64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp64_uint16 ( double *restrict Cx, const uint16_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__minv_fp64_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
points.c
#include "image.h" #include <stdlib.h> #include <memory.h> #include <assert.h> #include <limits.h> #include <kazmath/vec2.h> // Transforms even the sequence 0,1,2,3,... into reasonably good random numbers. unsigned int randhash(unsigned int seed) { unsigned int i = (seed ^ 12345391u) * 2654435769u; i ^= (i << 6) ^ (i >> 26); i *= 2654435769u; i += (i << 5) ^ (i >> 12); return i; } float randhashf(unsigned int seed, float a, float b) { return (b - a) * randhash(seed) / (float) UINT_MAX + a; } heman_image* heman_points_create(HEMAN_FLOAT* xy, int npoints, int nbands) { heman_points* img = malloc(sizeof(heman_image)); img->width = npoints; img->height = 1; img->nbands = nbands; int nbytes = sizeof(HEMAN_FLOAT) * npoints * nbands; img->data = malloc(nbytes); memcpy(img->data, xy, nbytes); return img; } void heman_points_destroy(heman_points* img) { free(img->data); free(img); } heman_points* heman_points_from_grid(HEMAN_FLOAT width, HEMAN_FLOAT height, HEMAN_FLOAT cellsize, HEMAN_FLOAT jitter) { int cols = width / cellsize; int rows = height / cellsize; int ncells = cols * rows; heman_points* result = heman_image_create(ncells, 1, 2); HEMAN_FLOAT rscale = 2.0 * jitter / (HEMAN_FLOAT) RAND_MAX; // TODO it would be good to avoid ANSI rand() and add some determinism // in a thread-safe way. Maybe we should add a seed argument and use // Bridson's randhash? int j; #pragma omp parallel for for (j = 0; j < rows; j++) { HEMAN_FLOAT* dst = result->data + j * cols * 2; HEMAN_FLOAT y = cellsize * 0.5 + cellsize * j; HEMAN_FLOAT x = cellsize * 0.5; for (int i = 0; i < cols; i++) { HEMAN_FLOAT rx = rand() * rscale - jitter; HEMAN_FLOAT ry = rand() * rscale - jitter; *dst++ = x + rx; *dst++ = y + ry; x += cellsize; } } return result; } kmVec2 sample_annulus(float radius, kmVec2 center, unsigned int* seedptr) { unsigned int seed = *seedptr; kmVec2 r; float rscale = 1.0f / UINT_MAX; while (1) { r.x = 4 * rscale * randhash(seed++) - 2; r.y = 4 * rscale * randhash(seed++) - 2; float r2 = kmVec2LengthSq(&r); if (r2 > 1 && r2 <= 4) { break; } } *seedptr = seed; kmVec2Scale(&r, &r, radius); kmVec2Add(&r, &r, &center); return r; } #define GRIDF(vec) \ grid[(int) (vec.x * invcell) + ncols * (int) (vec.y * invcell)] #define GRIDI(vec) grid[(int) vec.y * ncols + (int) vec.x] heman_points* heman_points_from_poisson( HEMAN_FLOAT width, HEMAN_FLOAT height, HEMAN_FLOAT radius) { int maxattempts = 30; float rscale = 1.0f / UINT_MAX; unsigned int seed = 0; kmVec2 rvec; rvec.x = rvec.y = radius; float r2 = radius * radius; // Acceleration grid. float cellsize = radius / sqrtf(2); float invcell = 1.0f / cellsize; int ncols = ceil(width * invcell); int nrows = ceil(height * invcell); int maxcol = ncols - 1; int maxrow = nrows - 1; int ncells = ncols * nrows; int* grid = malloc(ncells * sizeof(int)); for (int i = 0; i < ncells; i++) { grid[i] = -1; } // Active list and resulting sample list. int* actives = malloc(ncells * sizeof(int)); int nactives = 0; heman_points* result = heman_image_create(ncells, 1, 2); kmVec2* samples = (kmVec2*) result->data; int nsamples = 0; // First sample. kmVec2 pt; pt.x = width * randhash(seed++) * rscale; pt.y = height * randhash(seed++) * rscale; GRIDF(pt) = actives[nactives++] = nsamples; samples[nsamples++] = pt; while (nsamples < ncells) { int aindex = MIN(randhashf(seed++, 0, nactives), nactives - 1); int sindex = actives[aindex]; int found = 0; kmVec2 j, minj, maxj, delta; int attempt; for (attempt = 0; attempt < maxattempts && !found; attempt++) { pt = sample_annulus(radius, samples[sindex], &seed); // Check that this sample is within bounds. if (pt.x < 0 || pt.x >= width || pt.y < 0 || pt.y >= height) { continue; } // Test proximity to nearby samples. minj = maxj = pt; kmVec2Add(&maxj, &maxj, &rvec); kmVec2Subtract(&minj, &minj, &rvec); kmVec2Scale(&minj, &minj, invcell); kmVec2Scale(&maxj, &maxj, invcell); minj.x = CLAMP((int) minj.x, 0, maxcol); maxj.x = CLAMP((int) maxj.x, 0, maxcol); minj.y = CLAMP((int) minj.y, 0, maxrow); maxj.y = CLAMP((int) maxj.y, 0, maxrow); int reject = 0; for (j.y = minj.y; j.y <= maxj.y && !reject; j.y++) { for (j.x = minj.x; j.x <= maxj.x && !reject; j.x++) { int entry = GRIDI(j); if (entry > -1 && entry != sindex) { kmVec2Subtract(&delta, &samples[entry], &pt); if (kmVec2LengthSq(&delta) < r2) { reject = 1; } } } } if (reject) { continue; } found = 1; } if (found) { GRIDF(pt) = actives[nactives++] = nsamples; samples[nsamples++] = pt; } else { if (--nactives <= 0) { break; } actives[aindex] = actives[nactives]; } } // The following line probably isn't necessary. Paranoia. result->width = nsamples; free(grid); free(actives); return result; } #undef GRIDF #undef GRIDI #define NGRID_INDEX(fpt) \ ((int) (fpt.x * invcell) + ncols * (int) (fpt.y * invcell)) #define GRID_INDEX(fpt) (gcapacity * NGRID_INDEX(fpt)) #define GRID_INSERT(fpt, sindex) \ gindex = NGRID_INDEX(fpt); \ grid[gcapacity * gindex + ngrid[gindex]] = sindex; \ ngrid[gindex]++ #define NGRID_BEGIN(ipt) ((int) ipt.y * ncols + (int) ipt.x) #define GRID_BEGIN(ipt) (NGRID_BEGIN(ipt) * gcapacity) #define GRID_END(ipt) (GRID_BEGIN(ipt) + ngrid[NGRID_BEGIN(ipt)]) heman_points* heman_points_from_density( heman_image* density, HEMAN_FLOAT minradius, HEMAN_FLOAT maxradius) { assert(density->nbands == 1); float width = 1, height = 1; int maxattempts = 30; float rscale = 1.0f / UINT_MAX; unsigned int seed = 0; kmVec2 rvec; rvec.x = rvec.y = maxradius; int gindex; // Acceleration grid. float cellsize = maxradius / sqrtf(2); float invcell = 1.0f / cellsize; int ncols = ceil(width * invcell); int nrows = ceil(height * invcell); int maxcol = ncols - 1; int maxrow = nrows - 1; int ncells = ncols * nrows; int ntexels = cellsize * density->width; int gcapacity = ntexels * ntexels; int* grid = malloc(ncells * sizeof(int) * gcapacity); int* ngrid = malloc(ncells * sizeof(int)); for (int i = 0; i < ncells; i++) { ngrid[i] = 0; } // Active list and resulting sample list. int* actives = malloc(ncells * sizeof(int)); int nactives = 0; int maxsamples = ncells * gcapacity; heman_points* result = heman_image_create(maxsamples, 1, 2); kmVec2* samples = (kmVec2*) result->data; int nsamples = 0; // First sample. kmVec2 pt; pt.x = width * randhash(seed++) * rscale; pt.y = height * randhash(seed++) * rscale; actives[nactives++] = nsamples; GRID_INSERT(pt, nsamples); samples[nsamples++] = pt; while (nsamples < maxsamples) { int aindex = MIN(randhashf(seed++, 0, nactives), nactives - 1); int sindex = actives[aindex]; int found = 0; kmVec2 j, minj, maxj, delta; int attempt; for (attempt = 0; attempt < maxattempts && !found; attempt++) { pt = sample_annulus(maxradius, samples[sindex], &seed); // Check that this sample is within bounds. if (pt.x < 0 || pt.x >= width || pt.y < 0 || pt.y >= height) { continue; } // Test proximity to nearby samples. minj = maxj = pt; kmVec2Add(&maxj, &maxj, &rvec); kmVec2Subtract(&minj, &minj, &rvec); kmVec2Scale(&minj, &minj, invcell); kmVec2Scale(&maxj, &maxj, invcell); minj.x = CLAMP((int) minj.x, 0, maxcol); maxj.x = CLAMP((int) maxj.x, 0, maxcol); minj.y = CLAMP((int) minj.y, 0, maxrow); maxj.y = CLAMP((int) maxj.y, 0, maxrow); int reject = 0; HEMAN_FLOAT densityval; heman_image_sample(density, pt.x, pt.y, &densityval); // The following square root seems to lead to more satisfying // results, although we should perhaps let the client decide... densityval = sqrt(densityval); float mindist = maxradius - densityval * (maxradius - minradius); float r2 = mindist * mindist; for (j.y = minj.y; j.y <= maxj.y && !reject; j.y++) { for (j.x = minj.x; j.x <= maxj.x && !reject; j.x++) { for (int g = GRID_BEGIN(j); g < GRID_END(j); ++g) { int entry = grid[g]; if (entry != sindex) { kmVec2Subtract(&delta, &samples[entry], &pt); if (kmVec2LengthSq(&delta) < r2) { reject = 1; } } } } } if (reject) { continue; } found = 1; } if (found && ngrid[NGRID_INDEX(pt)] >= gcapacity) { found = 0; } if (found) { actives[nactives++] = nsamples; GRID_INSERT(pt, nsamples); samples[nsamples++] = pt; } else { if (--nactives <= 0) { break; } actives[aindex] = actives[nactives]; } } // We don't usually fill the pre-allocated buffer, since it was // allocated for the worst case, so adjust the size: result->width = nsamples; free(grid); free(ngrid); free(actives); return result; }
hello_omp_private.c
#include <stdio.h> #include <omp.h> int main(int argc, char** argv){ int thread_id; #pragma omp parallel private(thread_id) { thread_id = omp_get_thread_num(); printf("Hello from process: %d\n", thread_id ); } return 0; }
Matrix.h
#pragma once #include <algorithm> #include <exception> #include <functional> #include <iostream> #include <omp.h> #include <stdexcept> #include <type_traits> #include <vector> namespace cppmath { template <typename T> class Matrix { static_assert(std::is_floating_point_v<T>, "An specilization of the matrix class has be of a floating point type!"); public: using MatrixDataType = std::vector<std::vector<T>>; Matrix() = delete; Matrix(std::size_t rows, std::size_t cols); Matrix(std::size_t rows, std::size_t cols, const T &value); ~Matrix() noexcept = default; Matrix(const Matrix &other) = default; Matrix &operator=(const Matrix &other) = default; Matrix(Matrix &&other) noexcept = default; Matrix &operator=(Matrix &&other) noexcept = default; Matrix operator+(const Matrix &rhs); Matrix &operator+=(const Matrix &rhs); Matrix operator-(const Matrix &rhs); Matrix &operator-=(const Matrix &rhs); Matrix operator*(const T &scalar); Matrix &operator*=(const T &scalar); Matrix operator/(const T &scalar); Matrix &operator/=(const T &scalar); Matrix operator*(const Matrix &rhs); Matrix &operator*=(const Matrix &rhs); void dot(const Matrix &matrixA, const Matrix &matrixB, Matrix &result); void parallel_dot(const Matrix &matrixA, const Matrix &matrixB, Matrix &result); void print_matrix() const; std::size_t num_rows() const; std::size_t num_cols() const; private: std::size_t m_rows; std::size_t m_cols; MatrixDataType m_data; }; template <typename T> Matrix<T>::Matrix(std::size_t rows, std::size_t cols) : m_rows(rows), m_cols(cols), m_data(m_rows, std::vector<T>(m_cols, 0)) { } template <typename T> Matrix<T>::Matrix(std::size_t rows, std::size_t cols, const T &value) : m_rows(rows), m_cols(cols), m_data(m_rows, std::vector<T>(m_cols, value)) { } template <typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T> &rhs) { if (m_rows != rhs.m_rows) { throw(std::invalid_argument("Number of rows are not equal!")); } if (m_cols != rhs.m_cols) { throw(std::invalid_argument("Number of cols are not equal!")); } Matrix<T> result(m_rows, m_cols); for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), rhs.m_data[i].begin(), result.m_data[i].begin(), std::plus<T>()); } return result; } template <typename T> Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &rhs) { if (m_rows != rhs.m_rows) { throw(std::invalid_argument("Number of rows are not equal!")); } if (m_cols != rhs.m_cols) { throw(std::invalid_argument("Number of cols are not equal!")); } for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), rhs.m_data[i].begin(), m_data[i].begin(), std::plus<T>()); } return *this; } template <typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T> &rhs) { if (m_rows != rhs.m_rows) { throw(std::invalid_argument("Number of rows are not equal!")); } if (m_cols != rhs.m_cols) { throw(std::invalid_argument("Number of cols are not equal!")); } Matrix<T> result(m_rows, m_cols); for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), rhs.m_data[i].begin(), result.m_data[i].begin(), std::minus<T>()); } return result; } template <typename T> Matrix<T> &Matrix<T>::operator-=(const Matrix<T> &rhs) { if (m_rows != rhs.m_rows) { throw(std::invalid_argument("Number of rows are not equal!")); } if (m_cols != rhs.m_cols) { throw(std::invalid_argument("Number of cols are not equal!")); } for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), rhs.m_data[i].begin(), m_data[i].begin(), std::minus<T>()); } return *this; } template <typename T> Matrix<T> Matrix<T>::operator*(const T &scalar) { Matrix<T> result(m_rows, m_cols); for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), result.m_data[i].begin(), [scalar](const T val) -> T { return val * scalar; }); } return result; } template <typename T> Matrix<T> &Matrix<T>::operator*=(const T &scalar) { for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), m_data[i].begin(), [scalar](const T val) -> T { return val * scalar; }); } return *this; } template <typename T> Matrix<T> Matrix<T>::operator/(const T &scalar) { if (scalar == 0) { throw(std::overflow_error("You cannot divide by a scalar value of zero!")); } Matrix<T> result(m_rows, m_cols); for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), result.m_data[i].begin(), [scalar](const T val) -> T { return val / scalar; }); } return result; } template <typename T> Matrix<T> &Matrix<T>::operator/=(const T &scalar) { for (std::size_t i = 0; i != m_rows; ++i) { std::transform(m_data[i].begin(), m_data[i].end(), m_data[i].begin(), [scalar](const T val) -> T { return val / scalar; }); } return *this; } template <typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T> &rhs) { if (m_cols != rhs.m_rows) { throw(std::invalid_argument("Number of cols are not equal!")); } Matrix<T> result(m_rows, rhs.m_cols); if (m_rows < 250 && m_cols < 250) { dot(*this, rhs, result); } else { parallel_dot(*this, rhs, result); } return result; } template <typename T> Matrix<T> &Matrix<T>::operator*=(const Matrix<T> &rhs) { if (m_cols != rhs.m_rows) { throw(std::invalid_argument("Number of cols are not equal!")); } *this = (*this) * rhs; return *this; } template <typename T> void Matrix<T>::dot(const Matrix<T> &matrixA, const Matrix<T> &matrixB, Matrix<T> &result) { for (std::size_t i = 0; i != matrixA.m_rows; ++i) { for (std::size_t j = 0; j != matrixB.m_cols; ++j) { for (std::size_t k = 0; k != matrixB.m_rows; ++k) { result.m_data[i][j] = result.m_data[i][j] + matrixA.m_data[i][k] * matrixB.m_data[k][j]; } } } } template <typename T> void Matrix<T>::parallel_dot(const Matrix<T> &matrixA, const Matrix<T> &matrixB, Matrix<T> &result) { std::size_t i = 0; std::size_t j = 0; std::size_t k = 0; #pragma omp parallel for shared(result) private(i, j, k) num_threads(12) for (i = 0; i != matrixA.m_rows; ++i) { for (j = 0; j != matrixB.m_cols; ++j) { for (k = 0; k != matrixB.m_rows; ++k) { result.m_data[i][j] = result.m_data[i][j] + matrixA.m_data[i][k] * matrixB.m_data[k][j]; } } } } template <typename T> void Matrix<T>::print_matrix() const { for (std::size_t i = 0; i < m_rows; ++i) { for (std::size_t j = 0; j < m_cols; ++j) { std::cout << m_data[i][j] << " "; } std::cout << std::endl; } std::cout << std::endl; } template <typename T> std::size_t Matrix<T>::num_rows() const { return m_rows; } template <typename T> std::size_t Matrix<T>::num_cols() const { return m_cols; } } // namespace cppmath
collapse_2.c
#include<stdio.h> #ifdef _OPENMP #include <omp.h> #endif int a[11][11]; int main(void) { int i, j; int m = 10; int n = 10; for(i = 0; i < 11; i ++) { for(j = 0; j < 11; j ++) { a[i][j] = 0; } } #pragma omp target map(to: m, n) map(tofrom:a[0:11][0:11]) #pragma omp parallel for collapse(2) private(j,i)// nowait for (i=1;i<m;i+=1) { for (j=1;j<n;j+=1) { int k=3; int l=3; int z=3; a[i][j]=i+j+l+k+z; } } /* for(i = 0; i < 11; i ++) { for(j = 0; j < 11; j ++) { fprintf(stderr, "%d\n", a[i][j]); } } */ return 0; }
GB_binop__lxor_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lxor_fp32 // A.*B function (eWiseMult): GB_AemultB__lxor_fp32 // A*D function (colscale): GB_AxD__lxor_fp32 // D*A function (rowscale): GB_DxB__lxor_fp32 // C+=B function (dense accum): GB_Cdense_accumB__lxor_fp32 // C+=b function (dense accum): GB_Cdense_accumb__lxor_fp32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_fp32 // C=scalar+B GB_bind1st__lxor_fp32 // C=scalar+B' GB_bind1st_tran__lxor_fp32 // C=A+scalar GB_bind2nd__lxor_fp32 // C=A'+scalar GB_bind2nd_tran__lxor_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = ((x != 0) != (y != 0)) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_FP32 || GxB_NO_LXOR_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__lxor_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__lxor_fp32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__lxor_fp32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lxor_fp32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__lxor_fp32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__lxor_fp32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lxor_fp32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lxor_fp32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; float bij = Bx [p] ; Cx [p] = ((x != 0) != (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lxor_fp32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = Ax [p] ; Cx [p] = ((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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lxor_fp32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lxor_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
broadcast_reduce_customized-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015-2017 by Contributors * \file broadcast_reduce_customized-inl.h * \brief CPU-specific Function definition of broadcast and reduce operators */ #ifndef MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_ #define MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_ #include "../../tensor/broadcast_reduce-inl.h" namespace mxnet { namespace op { namespace broadcast { using namespace mshadow; template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, OType *small, const Shape<ndim>& bshape, const Shape<ndim>& sshape, const Shape<ndim>& rshape, const Shape<ndim>& rstride, Reducer* reducer) { Shape<ndim> coord = unravel(idx, sshape); index_t j = ravel(coord, bshape); AType val, residual; reducer->SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { coord = unravel(k, rshape); reducer->Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual); } reducer->Finalize(val, residual); assign(&small[idx], addto, OType(val)); } #ifdef __CUDACC__ #include "broadcast_reduce_customized-inl.cuh" #include "../../tensor/broadcast_reduce-inl.cuh" #else template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto, const DType *big, OType *small, const Shape<ndim> bshape, const Shape<ndim> sshape, const Shape<ndim> rshape, const Shape<ndim> rstride, Reducer* reducer) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign_wr<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small, bshape, sshape, rshape, rstride, reducer); } } template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false> void ReduceWithReducer(Stream<cpu>* s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big, Reducer* reducer) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(), M = rshape.Size(); if (!safe_acc) { seq_reduce_compute_wr<Reducer, ndim, DType, DType, DType, OP>( N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer); } else { MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, { typedef typename std::conditional<safe_acc, AType, DataType>::type AccType; MSHADOW_TYPE_SWITCH_WITH_BOOL(small.type_flag_, OType, { typedef typename std::conditional<safe_acc, OType, DataType>::type OutType; seq_reduce_compute_wr<Reducer, ndim, AccType, DataType, OutType, OP>( N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer); }); }); } } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, const DType* __restrict lhs, const DType* __restrict rhs, DType *small, const Shape<ndim>& big_shape, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0, const Shape<ndim>& small_shape, const Shape<ndim>& rshape, const Shape<ndim>& lhs_shape, const Shape<ndim>& rhs_shape, const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride, const Shape<ndim>& rhs_stride, Reducer* reducer) { Shape<ndim> coord = unravel(idx, small_shape); const index_t idx_big0 = ravel(coord, big_shape); const index_t idx_lhs0 = ravel(coord, lhs_shape0); const index_t idx_rhs0 = ravel(coord, rhs_shape0); DType val, residual; reducer->SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { Shape<ndim> coord_big = unravel(k, rshape); index_t idx_big = idx_big0 + dot(coord_big, rstride); Shape<ndim> coord_lhs = unravel(k, lhs_shape); index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride); Shape<ndim> coord_rhs = unravel(k, rhs_shape); index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride); reducer->Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual); } reducer->Finalize(val, residual); assign(&small[idx], addto, val); } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto, const DType *big, const DType *lhs, const DType *rhs, DType *small, const Shape<ndim> big_shape, const Shape<ndim> small_shape, const Shape<ndim> rshape, const Shape<ndim> rstride, const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride, const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0, Reducer* reducer) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign_wr<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small, big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride, lhs_stride, rhs_stride, reducer); } } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void ReduceWithReducer(Stream<cpu> *s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs, const TBlob& rhs, Reducer* reducer) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(); size_t M = rshape.Size(); Shape<ndim> lhs_shape, lhs_stride; diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride); Shape<ndim> rhs_shape, rhs_stride; diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride); seq_reduce_compute_wr<Reducer, ndim, DType, OP1, OP2>( N, M, req == kAddTo, big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, lhs_shape, lhs_stride, rhs_shape, rhs_stride, lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(), reducer); } #endif } // namespace broadcast } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
broadcast_binary_operation.h
/* Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __NUMPY_BROADCAST_BINARY_OPERATION_H__ #define __NUMPY_BROADCAST_BINARY_OPERATION_H__ #include "point_task.h" namespace legate { namespace numpy { #if defined(LEGATE_USE_CUDA) && defined(__CUDACC__) template <int DIM, typename BinaryFunction, typename Args> __global__ void __launch_bounds__(THREADS_PER_BLOCK, MIN_CTAS_PER_SM) gpu_broadcast_binary_op(const Args args, const bool dense) { const size_t idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx >= args.volume) return; BinaryFunction func; if (dense) { args.outptr[idx] = func(args.inptr[idx], args.scalar); } else { const Legion::Point<DIM> point = args.pitches.unflatten(idx, args.rect.lo); args.out[point] = func(args.in[point], args.scalar); } } #endif // Base class for all Legate's binary operation tasks template <class Derived, class BinaryFunction> class BroadcastBinaryOperationTask : public PointTask<Derived> { private: using first_argument_type = typename BinaryFunction::first_argument_type; using second_argument_type = typename BinaryFunction::second_argument_type; using result_type = std::result_of_t<BinaryFunction(first_argument_type, second_argument_type)>; public: static_assert(std::is_same<first_argument_type, second_argument_type>::value, "BroadcastBinaryOperation currently requires first_argument_type and " "second_argument_type to be the same type."); static const int TASK_ID = task_id<BinaryFunction::op_code, NUMPY_BROADCAST_VARIANT_OFFSET, result_type, first_argument_type, second_argument_type>; // out_region = in_region1 op scalar static const int REGIONS = 2; template <int N> struct DeserializedArgs { Legion::Rect<N> rect; AccessorWO<result_type, N> out; AccessorRO<first_argument_type, N> in; Pitches<N - 1> pitches; size_t volume; second_argument_type scalar; result_type* outptr; const first_argument_type* inptr; bool deserialize(LegateDeserializer& derez, const Legion::Task* task, const std::vector<Legion::PhysicalRegion>& regions) { rect = NumPyProjectionFunctor::unpack_shape<N>(task, derez); out = derez.unpack_accessor_WO<result_type, N>(regions[0], rect); in = derez.unpack_accessor_RO<first_argument_type, N>(regions[1], rect); scalar = task->futures[0].get_result<second_argument_type>(true /*silence warnings*/); volume = pitches.flatten(rect); #ifndef LEGION_BOUNDS_CHECKS // Check to see if this is dense or not return out.accessor.is_dense_row_major(rect) && in.accessor.is_dense_row_major(rect) && (outptr = out.ptr(rect)) && (inptr = in.ptr(rect)); #else // No dense execution if we're doing bounds checks return false; #endif } }; template <int DIM> static void dispatch_cpu(const Legion::Task* task, const std::vector<Legion::PhysicalRegion>& regions, LegateDeserializer& derez) { DeserializedArgs<DIM> args; const bool dense = args.deserialize(derez, task, regions); if (args.volume == 0) return; BinaryFunction func; if (dense) { for (size_t idx = 0; idx < args.volume; ++idx) args.outptr[idx] = func(args.inptr[idx], args.scalar); } else { const Scalar<second_argument_type, DIM> scalar(args.scalar); CPULoop<DIM>::binary_loop(func, args.out, args.in, scalar, args.rect); } } #ifdef LEGATE_USE_OPENMP template <int DIM> static void dispatch_omp(const Legion::Task* task, const std::vector<Legion::PhysicalRegion>& regions, LegateDeserializer& derez) { DeserializedArgs<DIM> args; const bool dense = args.deserialize(derez, task, regions); if (args.volume == 0) return; BinaryFunction func; if (dense) { #pragma omp parallel for schedule(static) for (size_t idx = 0; idx < args.volume; ++idx) args.outptr[idx] = func(args.inptr[idx], args.scalar); } else { const Scalar<second_argument_type, DIM> scalar(args.scalar); OMPLoop<DIM>::binary_loop(func, args.out, args.in, scalar, args.rect); } } #endif #if defined(LEGATE_USE_CUDA) && defined(__CUDACC__) template <int DIM> static void dispatch_gpu(const Legion::Task* task, const std::vector<Legion::PhysicalRegion>& regions, LegateDeserializer& derez) { DeserializedArgs<DIM> args; const bool dense = args.deserialize(derez, task, regions); if (args.volume == 0) return; const size_t blocks = (args.volume + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK; gpu_broadcast_binary_op<DIM, BinaryFunction, DeserializedArgs<DIM>> <<<blocks, THREADS_PER_BLOCK>>>(args, dense); } #elif defined(LEGATE_USE_CUDA) template <int DIM> static void dispatch_gpu(const Legion::Task* task, const std::vector<Legion::PhysicalRegion>& regions, LegateDeserializer& derez); #endif }; } // namespace numpy } // namespace legate #endif // __NUMPY_BROADCAST_BINARY_OPERATION_H__
arb_fermidirac.c
/* Based on: https://github.com/fredrik-johansson/arb/blob/master/examples/integrals.c A. Odrzywołek, 2022-02-16, andrzej.odrzywolek@uj.edu.pl Install Arb https://arblib.org/ sudo apt install libflint-arb-dev sudo apt install libflint-arb2 sudo apt install libflint-dev Compile with: gcc arb_fermidirac.c -o arb_fd -lflint -lflint-arb -lm -lfermidirac -lquadmath dfermi200.o fedi_cpc.o -lgfortran */ /* Generalized Fermi–Dirac functions and derivatives: properties and evaluation Published: 1 June 2001 | Version 1 | DOI: 10.17632/57tnc6sby7.1 Contributors: Zhigang Gong, Ladislav Zejda, Werner Däppen, Josep M. Aparicio DOWNLOAD CODE FROM: https://elsevier.digitalcommonsdata.com/datasets/57tnc6sby7/1 Compile instructions: gfortran -c fedi_cpc.for gfortran -c dfermi200.for Copy files fedi_cpc.o, dfermi200.o to test/ subdir */ #include <string.h> #include <acb_calc.h> #include <arb.h> #include <acb_hypgeom.h> //#include "double_interval.h" // Require the most recent Arb, I'm unable to install it A.O. #include <fermidirac.h> #include <quadmath.h> #include <omp.h> double dfermi200_(int *, double *,double *,double *); //Gong GFDI int idx, gong_idx[4][4] = {{0, 2, 5, 9}, {1, 4, 8, -1}, {3, 7, -1, -1}, {6, -1, -1, -1}}; //Gong et. al, Table 1. p. 299, CPC 136 (2001) int main(int argc, char *argv[]) { double fd_quad,fd_double; acb_t fd_arb, fd; arb_t fd_real, rel_err, MachineEpsilon, MaxMachineNumber, MinMachineNumber; int m,n, i,j, sign, counter=0, underflow=0, overflow=0, failed=0, lg2_max; double k, eta, theta, GONG, Arb; //di_t interval; Require the most recent Arb, I'm unable to install it A.O. flint_printf("Computed with arb-%s\n", arb_version); acb_init(fd_arb); acb_init(fd); arb_init(fd_real); arb_init(rel_err); arb_init(MachineEpsilon); arb_one(MachineEpsilon); arb_mul_2exp_si(MachineEpsilon, MachineEpsilon, -52); arb_init(MaxMachineNumber); arb_one(MaxMachineNumber); arb_mul_2exp_si(MaxMachineNumber, MaxMachineNumber, 1024); arb_init(MinMachineNumber); arb_one(MinMachineNumber); arb_mul_2exp_si(MinMachineNumber, MinMachineNumber, -1022); sscanf(argv[1],"%lf",&k); sscanf(argv[2],"%d",&lg2_max); #if 1 for(m=0;m<=3;m++) for(n=0;n<=3;n++) { if(m+n>3) continue; printf("Testing derivative %d%d\n\n",m,n); //#pragma omp parallel for collapse(3) private(idx, eta,theta, fd, fd_real, fd_arb, fd_quad, rel_err, GONG, sign,i,j) shared(lg2_max,m,n) reduction(+ :counter, overflow, underflow, failed) for(sign=-1;sign<=1;sign=sign+2) for(i=-lg2_max;i<=lg2_max;i=i+1) for(j=-lg2_max;j<=lg2_max;j=j+1) { counter++; eta = sign*pow(2,i); theta = pow(2,j); if(!(counter%1024)) printf("Total tested = %d, overflow=%d, underflow=%d, failed=%d\n",counter, overflow, underflow, failed); Ffermi_derivatives_m_n_arb(fd_arb, k, eta, theta, m, n); acb_get_real(fd_real,fd_arb); if( arb_ge(fd_real, MaxMachineNumber) ){ overflow++;continue;} if( arb_le(fd_real, MinMachineNumber) ){ underflow++;continue;} fd_quad = (double) Ffermi_derivatives_m_n_quad((__float128) k, (__float128) eta, (__float128) theta, m, n); //fd_quad = (double) Ffermi_sommerfeld_derivatives_m_n_quad(k, eta, theta, m, n,powq(2.0q,-64.0q),11); //fd_quad = (double) Ffermi_dblexp_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 128*DBL_EPSILON, MAX_REFINE); //fd_double = Ffermi_derivatives_m_n_internal_arb(0.5, sign*pow(2,i), pow(2,j), m, n); //fd_quad = Ffermi_derivatives_m_n(k, eta, theta, m, n); //printf("%e\n", fd_quad/fd_double-1.0); acb_set_d(fd, fd_quad); acb_div(fd, fd, fd_arb, 128); acb_add_si(fd, fd, -1, 128); acb_abs(rel_err, fd, 128); if( arb_ge(rel_err, MachineEpsilon) || (!acb_is_finite(fd_arb)) ) { failed++; printf("\nArb= "); //acb_print(fd_arb);printf("\n"); //acb_printd(fd_arb, 128);printf("\n"); acb_printn(fd_arb, 128, 0);printf("\n"); printf("libfermidirac=%.18e\n", fd_quad); idx = gong_idx[m][n]; GONG = dfermi200_(&idx,&k, &eta, &theta); printf("GONG =%.18e\n",GONG); printf("%d %d\t%d\t",sign,i,j); printf("k=%.1lf eta=%e theta=%e m=%d n=%d\n", k, eta, theta, m, n); printf("Relative error:\t");arb_printn(rel_err, 128, 0); acb_set_d(fd, GONG); acb_div(fd, fd, fd_arb, 128); acb_add_si(fd, fd, -1, 128); acb_abs(rel_err, fd, 128); printf("\nRelative error:\t");arb_printn(rel_err, 128, 0); printf("\n0.5*eta*theta=%e\n", eta*theta*0.5); printf("\n------------------------------------------------------------------------------\n\n"); } } } #endif #if 0 m=3;n=0; printf("Testing derivative %d%d\n\n",m,n); sign=1; k=0.5; theta = pow(2.0,38); for(eta=32.0;eta<=128.0;eta=eta+0.125) { Arb = Ffermi_derivatives_m_n_internal_arb(k, eta, theta, m, n); fd_quad = (double) Ffermi_dblexp_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 8*DBL_EPSILON, MAX_REFINE); fd_double = (double) Ffermi_sommerfeld_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 8*DBL_EPSILON, MAX_REFINE); //fd_double = (double) Ffermi_derivatives_m_n_quad(k,eta,theta, m, n); idx = gong_idx[m][n]; GONG = dfermi200_(&idx,&k, &eta, &theta); printf("%lf\t%.18e\t%.18e\t%.18e\t%.18e\n",eta,Arb,fd_quad,GONG,fd_double); } #endif acb_clear(fd_arb); acb_clear(fd); arb_clear(fd_real); arb_clear(rel_err); arb_clear(MachineEpsilon); arb_clear(MaxMachineNumber); arb_clear(MinMachineNumber); printf("Finally tested = %d, overflow=%d, underflow=%d, failed=%d\n",counter, overflow, underflow, failed); return 0; }
functions.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "functions.h" #include <omp.h> //compute a*b mod p safely unsigned int modprod(unsigned int a, unsigned int b, unsigned int p) { unsigned int za = a; unsigned int ab = 0; while (b > 0) { if (b%2 == 1) ab = (ab + za) % p; za = (2 * za) % p; b /= 2; } return ab; } //compute a^b mod p safely unsigned int modExp(unsigned int a, unsigned int b, unsigned int p) { unsigned int z = a; unsigned int aExpb = 1; while (b > 0) { if (b%2 == 1) aExpb = modprod(aExpb, z, p); z = modprod(z, z, p); b /= 2; } return aExpb; } //returns either 0 or 1 randomly unsigned int randomBit() { return rand()%2; } //returns a random integer which is between 2^{n-1} and 2^{n} unsigned int randXbitInt(unsigned int n) { unsigned int r = 1; for (unsigned int i=0; i<n-1; i++) { r = r*2 + randomBit(); } return r; } //tests for primality and return 1 if N is probably prime and 0 if N is composite unsigned int isProbablyPrime(unsigned int N) { if (N%2==0) return 0; //not interested in even numbers (including 2) unsigned int NsmallPrimes = 168; unsigned int smallPrimeList[168] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}; //before using a probablistic primality check, check directly using the small primes list for (unsigned int n=1;n<NsmallPrimes;n++) { if (N==smallPrimeList[n]) return 1; //true if (N%smallPrimeList[n]==0) return 0; //false } //if we're testing a large number switch to Miller-Rabin primality test unsigned int r = 0; unsigned int d = N-1; while (d%2 == 0) { d /= 2; r += 1; } for (unsigned int n=0;n<NsmallPrimes;n++) { unsigned int k = smallPrimeList[n]; unsigned int x = modExp(k,d,N); if ((x==1) || (x==N-1)) continue; for (unsigned int i=1;i<r-1;i++) { x = modprod(x,x,N); if (x == 1) return 0; //false if (x == N-1) break; } // see whether we left the loop becasue x==N-1 if (x == N-1) continue; return 0; //false } return 1; //true } //Finds a generator of Z_p using the assumption that p=2*q+1 unsigned int findGenerator(unsigned int p) { unsigned int g; unsigned int q = (p-1)/2; do { //make a random number 1<= g < p g = randXbitInt(32)%p; //could also have passed n to findGenerator } while (g==0 || (modExp(g,q,p)==1) || (modExp(g,2,p)==1)); return g; } void setupElGamal(unsigned int n, unsigned int *p, unsigned int *g, unsigned int *h, unsigned int *x) { /* Use isProbablyPrime and randomXbitInt to find a new random n-bit prime number which satisfies p=2*q+1 where q is also prime */ unsigned int q; do { *p = randXbitInt(n); q = (*p-1)/2; } while (!isProbablyPrime(*p) || !isProbablyPrime(q)); /* Use the fact that p=2*q+1 to quickly find a generator */ *g = findGenerator(*p); //pick a secret key, x *x = randXbitInt(n)%(*p); //compute h *h = modExp(*g,*x,*p); printf("ElGamal Setup successful.\n"); printf("p = %u. \n", *p); printf("g = %u is a generator of Z_%u \n", *g, *p); printf("Secret key: x = %u \n", *x); printf("h = g^x = %u\n", *h); printf("\n"); } void ElGamalEncrypt(unsigned int *m, unsigned int *a, unsigned int Nints, unsigned int p, unsigned int g, unsigned int h) { /* Q2.1 Parallelize this function with OpenMP */ #pragma omp parallel for for (unsigned int i=0; i<Nints;i++) { //pick y in Z_p randomly unsigned int y; do { y = randXbitInt(32)%p; } while (y==0); //dont allow y=0 //compute a = g^y a[i] = modExp(g,y,p); //compute s = h^y unsigned int s = modExp(h,y,p); //encrypt m by multiplying with s m[i] = modprod(m[i],s,p); } } void ElGamalDecrypt(unsigned int *m, unsigned int *a, unsigned int Nints, unsigned int p, unsigned int x) { /* Q2.1 Parallelize this function with OpenMP */ #pragma omp parallel for for (unsigned int i=0; i<Nints;i++) { //compute s = a^x unsigned int s = modExp(a[i],x,p); //compute s^{-1} = s^{p-2} unsigned int invS = modExp(s,p-2,p); //decrypt message by multplying by invS m[i] = modprod(m[i],invS,p); } } //Pad the end of string so its length is divisible by Nchars // Assume there is enough allocated storage for the padded string void padString(unsigned char* string, unsigned int charsPerInt) { /* Q1.2 Complete this function */ while((strlen(string)) % charsPerInt != 0){ //+1 since the strlen doesnt count the end null character string[strlen(string)] = ' '; //string = string + ' '; } } void convertStringToZ(unsigned char *string, unsigned int Nchars, unsigned int *Z, unsigned int Nints) { /* Q1.3 Complete this function */ #pragma omp parallel for for(unsigned int i = 0; i < Nints; i++){ for(unsigned int j = 0; j < (Nchars/Nints); j++){ Z[i] = (Z[i]*256)+ string[(i*(Nchars/Nints))+j]; } } /* Q2.2 Parallelize this function with OpenMP */ } void convertZToString(unsigned int *Z, unsigned int Nints, unsigned char *string, unsigned int Nchars) { /* Q1.4 Complete this function */ #pragma omp parallel for for(int i = 0; i<Nints; i++){ for (int j = (Nchars/Nints)-1; j >= 0; j--){ string[(i*(Nchars/Nints))+j] = Z[i]%256; Z[i] = Z[i]/256; //printf("String is %c \n", string[i*(Nchars/Nints)]); } } /* Q2.2 Parallelize this function with OpenMP */ }
apply_constant_scalarvalue_process.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // // #if !defined(KRATOS_APPLY_CONSTANT_VALUE_PROCESS_H_INCLUDED ) #define KRATOS_APPLY_CONSTANT_VALUE_PROCESS_H_INCLUDED // System includes #include <string> #include <iostream> // External includes // Project includes #include "includes/define.h" #include "includes/kratos_flags.h" #include "includes/kratos_parameters.h" #include "processes/process.h" namespace Kratos { ///@name Kratos Classes ///@{ /// The base class for all processes in Kratos. /** This function applies a constant value (and fixity) to all of the nodes in a given mesh */ class ApplyConstantScalarValueProcess : public Process { public: ///@name Type Definitions ///@{ KRATOS_DEFINE_LOCAL_FLAG(VARIABLE_IS_FIXED); /// Pointer definition of ApplyConstantScalarValueProcess KRATOS_CLASS_POINTER_DEFINITION(ApplyConstantScalarValueProcess); ///@} ///@name Life Cycle ///@{ ApplyConstantScalarValueProcess(ModelPart& model_part, Parameters rParameters ) : Process(Flags()) , mr_model_part(model_part) { KRATOS_TRY //only include validation with c++11 since raw_literals do not exist in c++03 // Some values need to be mandatorily prescribed since no meaningful default value exist. For this reason try accessing to them // So that an error is thrown if they don't exist rParameters["value"]; rParameters["variable_name"]; rParameters["model_part_name"]; // Now validate agains defaults -- this also ensures no type mismatch rParameters.ValidateAndAssignDefaults(GetDefaultParameters()); mmesh_id = rParameters["mesh_id"].GetInt(); mvariable_name = rParameters["variable_name"].GetString(); this->Set( VARIABLE_IS_FIXED, rParameters["is_fixed"].GetBool()); if( KratosComponents< Variable<double> >::Has( mvariable_name ) ) //case of double variable { mdouble_value = rParameters["value"].GetDouble(); if( model_part.GetNodalSolutionStepVariablesList().Has( KratosComponents< Variable<double> >::Get( mvariable_name ) ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",mvariable_name); } } else if( KratosComponents< VariableComponent< VectorComponentAdaptor<array_1d<double, 3> > > >::Has(mvariable_name) ) //case of component variable { typedef VariableComponent< VectorComponentAdaptor<array_1d<double, 3> > > component_type; component_type var_component = KratosComponents< component_type >::Get(mvariable_name); if( model_part.GetNodalSolutionStepVariablesList().Has( var_component.GetSourceVariable() ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",mvariable_name); } mdouble_value = rParameters["value"].GetDouble(); } else if( KratosComponents< Variable<int> >::Has( mvariable_name ) ) //case of int variable { mint_value = rParameters["value"].GetInt(); if( model_part.GetNodalSolutionStepVariablesList().Has( KratosComponents< Variable<int> >::Get( mvariable_name ) ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",mvariable_name); } if(this->Is(VARIABLE_IS_FIXED)) { KRATOS_THROW_ERROR(std::runtime_error,"sorry it is not possible to fix variables of type Variable<int>. Only double variables or vector components can be fixed",""); } } else if( KratosComponents< Variable<bool> >::Has( mvariable_name ) ) //case of bool variable { mbool_value = rParameters["value"].GetBool(); if( model_part.GetNodalSolutionStepVariablesList().Has( KratosComponents< Variable<bool> >::Get( mvariable_name ) ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",mvariable_name); } if(this->Is(VARIABLE_IS_FIXED)) { KRATOS_THROW_ERROR(std::runtime_error,"sorry it is not possible to fix variables of type Variable<bool>. Only double variables or vector components can be fixed",""); } } KRATOS_CATCH(""); } ApplyConstantScalarValueProcess(ModelPart& model_part, const Variable<double>& rVariable, const double double_value, std::size_t mesh_id, Flags options ) : Process(options) , mr_model_part(model_part),mdouble_value(double_value), mint_value(0), mbool_value(false),mmesh_id(mesh_id) { KRATOS_TRY; if(this->IsDefined(VARIABLE_IS_FIXED) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"please specify if the variable is to be fixed or not (flag VARIABLE_IS_FIXED)",""); } if( model_part.GetNodalSolutionStepVariablesList().Has( rVariable ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",rVariable); } mvariable_name = rVariable.Name(); KRATOS_CATCH(""); } ApplyConstantScalarValueProcess(ModelPart& model_part, const VariableComponent<VectorComponentAdaptor<array_1d<double, 3> > >& rVariable, const double double_value, std::size_t mesh_id, Flags options ) : Process(options) , mr_model_part(model_part),mdouble_value(double_value), mint_value(0), mbool_value(false),mmesh_id(mesh_id) { KRATOS_TRY; if(this->IsDefined(VARIABLE_IS_FIXED) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"please specify if the variable is to be fixed or not (flag VARIABLE_IS_FIXED)","") } mvariable_name = rVariable.Name(); if( model_part.GetNodalSolutionStepVariablesList().Has( rVariable.GetSourceVariable() ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"trying to fix a variable that is not in the model_part - variable name is ",rVariable); } KRATOS_CATCH(""); } ApplyConstantScalarValueProcess(ModelPart& model_part, const Variable< int >& rVariable, const int int_value, std::size_t mesh_id, Flags options ) : Process(options) , mr_model_part(model_part),mdouble_value(0.0), mint_value(int_value), mbool_value(false),mmesh_id(mesh_id) { KRATOS_TRY; if(this->IsDefined(VARIABLE_IS_FIXED) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"Please specify if the variable is to be fixed or not (flag VARIABLE_IS_FIXED)",""); } if(this->Is(VARIABLE_IS_FIXED)) { KRATOS_THROW_ERROR(std::runtime_error,"Sorry it is not possible to fix variables of type Variable<int>. Only double variables or vector components can be fixed",""); } if( model_part.GetNodalSolutionStepVariablesList().Has( rVariable ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"Trying to fix a variable that is not in the model_part - variable name is ",rVariable); } mvariable_name = rVariable.Name(); KRATOS_CATCH(""); } ApplyConstantScalarValueProcess(ModelPart& model_part, const Variable< bool >& rVariable, const bool bool_value, std::size_t mesh_id, Flags options ) : Process(options) , mr_model_part(model_part),mdouble_value(0.0), mint_value(0), mbool_value(bool_value),mmesh_id(mesh_id) { KRATOS_TRY; if(this->IsDefined(VARIABLE_IS_FIXED) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"Please specify if the variable is to be fixed or not (flag VARIABLE_IS_FIXED)",""); } if(this->Is(VARIABLE_IS_FIXED)) { KRATOS_THROW_ERROR(std::runtime_error,"Sorry it is not possible to fix variables of type Variable<int>. Only double variables or vector components can be fixed",""); } if( model_part.GetNodalSolutionStepVariablesList().Has( rVariable ) == false ) { KRATOS_THROW_ERROR(std::runtime_error,"Trying to fix a variable that is not in the model_part - variable name is ",rVariable); } mvariable_name = rVariable.Name(); KRATOS_CATCH(""); } /// Destructor. ~ApplyConstantScalarValueProcess() override {} ///@} ///@name Operators ///@{ /// This operator is provided to call the process as a function and simply calls the Execute method. void operator()() { Execute(); } const Parameters GetDefaultParameters() const override { const Parameters default_parameters( R"( { "model_part_name":"PLEASE_CHOOSE_MODEL_PART_NAME", "mesh_id": 0, "variable_name": "PLEASE_PRESCRIBE_VARIABLE_NAME", "is_fixed": false, "value" : 1.0 } )" ); return default_parameters; } ///@} ///@name Operations ///@{ /// Execute method is used to execute the ApplyConstantScalarValueProcess algorithms. void Execute() override {} /// this function is designed for being called at the beginning of the computations /// right after reading the model and the groups void ExecuteInitialize() override { KRATOS_TRY; const bool is_fixed = this->Is(VARIABLE_IS_FIXED); if( KratosComponents< Variable<double> >::Has( mvariable_name ) ) //case of double variable { InternalApplyValue<>(KratosComponents< Variable<double> >::Get(mvariable_name) , is_fixed, mdouble_value); } else if( KratosComponents< VariableComponent< VectorComponentAdaptor<array_1d<double, 3> > > >::Has(mvariable_name) ) //case of component variable { typedef VariableComponent< VectorComponentAdaptor<array_1d<double, 3> > > component_type; component_type var_component = KratosComponents< component_type >::Get(mvariable_name); InternalApplyValue< component_type, double>(var_component , is_fixed, mdouble_value); } else if( KratosComponents< Variable<int> >::Has( mvariable_name ) ) //case of int variable { InternalApplyValueWithoutFixing<>(KratosComponents< Variable<int> >::Get(mvariable_name) , mint_value); } else if( KratosComponents< Variable<bool> >::Has( mvariable_name ) ) //case of bool variable { InternalApplyValueWithoutFixing<>(KratosComponents< Variable<bool> >::Get(mvariable_name), mbool_value); } else { KRATOS_THROW_ERROR(std::logic_error, "Not able to fix the variable. Attempting to fix variable:",mvariable_name); } KRATOS_CATCH(""); } /// this function is designed for being execute once before the solution loop but after all of the /// solvers where built void ExecuteBeforeSolutionLoop() override { } /// this function will be executed at every time step BEFORE performing the solve phase void ExecuteInitializeSolutionStep() override { } /// this function will be executed at every time step AFTER performing the solve phase void ExecuteFinalizeSolutionStep() override { } /// this function will be executed at every time step BEFORE writing the output void ExecuteBeforeOutputStep() override { } /// this function will be executed at every time step AFTER writing the output void ExecuteAfterOutputStep() override { } /// this function is designed for being called at the end of the computations /// right after reading the model and the groups void ExecuteFinalize() override { } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ApplyConstantScalarValueProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "ApplyConstantScalarValueProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ModelPart& mr_model_part; std::string mvariable_name; double mdouble_value; int mint_value; bool mbool_value; std::size_t mmesh_id; private: ///@name Static Member Variables ///@{ template< class TVarType, class TDataType > void InternalApplyValue(TVarType& rVar, const bool to_be_fixed, const TDataType value) { const int nnodes = mr_model_part.GetMesh(mmesh_id).Nodes().size(); if(nnodes != 0) { ModelPart::NodesContainerType::iterator it_begin = mr_model_part.GetMesh(mmesh_id).NodesBegin(); // ModelPart::NodesContainerType::iterator it_end = mr_model_part.GetMesh(mmesh_id).NodesEnd(); #pragma omp parallel for for(int i = 0; i<nnodes; i++) { ModelPart::NodesContainerType::iterator it = it_begin + i; if(to_be_fixed) { it->Fix(rVar); } it->FastGetSolutionStepValue(rVar) = value; } } } template< class TVarType, class TDataType > void InternalApplyValueWithoutFixing(TVarType& rVar, const TDataType value) { const int nnodes = mr_model_part.GetMesh(mmesh_id).Nodes().size(); if(nnodes != 0) { ModelPart::NodesContainerType::iterator it_begin = mr_model_part.GetMesh(mmesh_id).NodesBegin(); // ModelPart::NodesContainerType::iterator it_end = mr_model_part.GetMesh(mmesh_id).NodesEnd(); #pragma omp parallel for for(int i = 0; i<nnodes; i++) { ModelPart::NodesContainerType::iterator it = it_begin + i; it->FastGetSolutionStepValue(rVar) = value; } } } ///@} ///@name Un accessible methods ///@{ /// Assignment operator. ApplyConstantScalarValueProcess& operator=(ApplyConstantScalarValueProcess const& rOther); /// Copy constructor. //ApplyConstantScalarValueProcess(ApplyConstantScalarValueProcess const& rOther); ///@} }; // Class ApplyConstantScalarValueProcess KRATOS_CREATE_LOCAL_FLAG(ApplyConstantScalarValueProcess,VARIABLE_IS_FIXED, 0); ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, ApplyConstantScalarValueProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const ApplyConstantScalarValueProcess& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_APPLY_CONSTANT_VALUE_PROCESS_H_INCLUDED defined
a.13.1.c
/* { dg-do compile } */ int dequeue (float *a); void work (int i, float *a); void a13 (float *x, float *y) { int ix_next, iy_next; #pragma omp parallel shared(x, y) private(ix_next, iy_next) { #pragma omp critical (xaxis) ix_next = dequeue (x); work (ix_next, x); #pragma omp critical (yaxis) iy_next = dequeue (y); work (iy_next, y); } }
partial.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) ******************************************************************************/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] -= hypre_MPI_Wtime(); #endif /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; /*HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL;*/ HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ /*HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter, coarse_counter_offd; */ HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; /*HYPRE_Int strong_f_marker = -2;*/ /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i; /*HYPRE_Int i, ii, i1, i2, j, jj, kk, k1, jj1;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Int max_num_threads; HYPRE_Int *P_diag_array = NULL; HYPRE_Int *P_offd_array = NULL; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); max_num_threads = hypre_NumThreads(); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = (HYPRE_Int)(num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]); /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); /*P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); */ } if (full_off_procNodes) { /*P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes);*/ fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } /*hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd);*/ for (i=0; i < full_off_procNodes; i++) { fine_to_coarse_offd[i] = -1; tmp_CF_marker_offd[i] = -1; } cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } P_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1, HYPRE_MEMORY_HOST); P_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i, diagonal, distribute, sgn, sum) #endif { HYPRE_Int ii, jj_counter, jj_counter_offd, jj, kk, i1, i2, k1, jj1; HYPRE_BigInt big_k1; HYPRE_Int loc_col, jj_begin_row, jj_begin_row_offd; HYPRE_Int jj_end_row, jj_end_row_offd, strong_f_marker; HYPRE_Int size, rest, ne, ns; HYPRE_Int num_threads, my_thread_num; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; strong_f_marker = -2; num_threads = hypre_NumActiveThreads(); my_thread_num = hypre_GetThreadNum(); size = n_coarse_old/num_threads; rest = n_coarse_old - size*num_threads; if (my_thread_num < rest) { ns = my_thread_num*(size+1); ne = (my_thread_num+1)*(size+1); } else { ns = my_thread_num*size+rest; ne = (my_thread_num+1)*size+rest; } if (n_fine) P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); for (ii=0; ii < n_fine; ii++) P_marker[ii] = -1; if (full_off_procNodes) P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); for (ii=0; ii < full_off_procNodes; ii++) P_marker_offd[ii] = -1; /*coarse_counter = 0; coarse_counter_offd = 0;*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; /*P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd;*/ i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; /*coarse_counter++;*/ } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; if(big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1-col_1); if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } P_diag_array[my_thread_num] = jj_counter; P_offd_array[my_thread_num] = jj_counter_offd; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); for (i=0; i < max_num_threads; i++) { P_diag_array[i+1] += P_diag_array[i]; P_offd_array[i+1] += P_offd_array[i]; } P_diag_size = P_diag_array[max_num_threads]; P_offd_size = P_offd_array[max_num_threads]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = P_diag_size; P_offd_i[n_coarse_old] = P_offd_size; /* Fine to coarse mapping */ if(num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif jj_counter = start_indexing; jj_counter_offd = start_indexing; if (my_thread_num) { jj_counter = P_diag_array[my_thread_num-1]; jj_counter_offd = P_offd_array[my_thread_num-1]; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; P_diag_i[ii] = jj_counter; P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; /* Find local col number */ if(big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1-col_1); if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; if(i2 == i && (sgn*A_diag_data[jj1]) < 0) diagonal += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { big_k1 = A_ext_j[jj1]; if(big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if(P_marker[loc_col] >= jj_begin_row || loc_col == i) sum += A_ext_data[jj1]; } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { big_k1 = A_ext_j[jj1]; if(big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; if(loc_col == i) diagonal += distribute*A_ext_data[jj1]; } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); } /* end parallel region */ if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(P_offd_array, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if(num_functions > 1) hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialStdInterp * Comment: The interpolatory weighting can be changed with the sep_weight * variable. This can enable not separating negative and positive * off diagonals in the weight formula. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialStdInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int sep_weight, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; HYPRE_Int *ihat = NULL; HYPRE_Int *ihat_offd = NULL; HYPRE_Int *ipnt = NULL; HYPRE_Int *ipnt_offd = NULL; HYPRE_Int strong_f_marker = -2; /* Interpolation weight variables */ HYPRE_Real *ahat = NULL; HYPRE_Real *ahat_offd = NULL; HYPRE_Real sum_pos, sum_pos_C, sum_neg, sum_neg_C, sum, sum_C; HYPRE_Real diagonal, distribute; HYPRE_Real alfa, beta; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, j1, jj, kk, k1; HYPRE_BigInt big_k1; HYPRE_Int cnt_c, cnt_f, cnt_c_offd, cnt_f_offd, indx; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Real wall_1 = 0; HYPRE_Real wall_2 = 0; HYPRE_Real wall_3 = 0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag== 4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = (HYPRE_Int)(num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]); /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 0)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; if(big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1-col_1); if(CF_marker[loc_col] >= 0) { if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(CF_marker_offd[loc_col] >= 0) { if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } /* Initialize ahat, which is a modification to a, used in the standard * interpolation routine. */ if (n_fine) { ahat = hypre_CTAlloc(HYPRE_Real, n_fine, HYPRE_MEMORY_HOST); ihat = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); ipnt = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { ahat_offd = hypre_CTAlloc(HYPRE_Real, full_off_procNodes, HYPRE_MEMORY_HOST); ihat_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); ipnt_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; ahat[i] = 0; ihat[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; ahat_offd[i] = 0; ihat_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { if (debug_flag==4) wall_time = time_getWallclockSeconds(); strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = i1; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = k1; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd]=i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; if(big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1-col_1); if(CF_marker[loc_col] > 0) { if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = loc_col; P_diag_data[jj_counter] = zero; jj_counter++; } } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(CF_marker_offd[loc_col] > 0) { if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_1 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); cnt_c = 0; cnt_f = jj_end_row-jj_begin_row; cnt_c_offd = 0; cnt_f_offd = jj_end_row_offd-jj_begin_row_offd; ihat[i] = cnt_f; ipnt[cnt_f] = i; ahat[cnt_f++] = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is direct neighbor */ i1 = A_diag_j[jj]; if (P_marker[i1] != strong_f_marker) { indx = ihat[i1]; if (indx > -1) ahat[indx] += A_diag_data[jj]; else if (P_marker[i1] >= jj_begin_row) { ihat[i1] = cnt_c; ipnt[cnt_c] = i1; ahat[cnt_c++] += A_diag_data[jj]; } else if (CF_marker[i1] != -3) { ihat[i1] = cnt_f; ipnt[cnt_f] = i1; ahat[cnt_f++] += A_diag_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func[i1]) { distribute = A_diag_data[jj]/A_diag_data[A_diag_i[i1]]; for (kk = A_diag_i[i1]+1; kk < A_diag_i[i1+1]; kk++) { k1 = A_diag_j[kk]; indx = ihat[k1]; if (indx > -1) ahat[indx] -= A_diag_data[kk]*distribute; else if (P_marker[k1] >= jj_begin_row) { ihat[k1] = cnt_c; ipnt[cnt_c] = k1; ahat[cnt_c++] -= A_diag_data[kk]*distribute; } else { ihat[k1] = cnt_f; ipnt[cnt_f] = k1; ahat[cnt_f++] -= A_diag_data[kk]*distribute; } } if(num_procs > 1) { for (kk = A_offd_i[i1]; kk < A_offd_i[i1+1]; kk++) { k1 = A_offd_j[kk]; indx = ihat_offd[k1]; if(num_functions == 1 || dof_func[i1] == dof_func_offd[k1]) { if (indx > -1) ahat_offd[indx] -= A_offd_data[kk]*distribute; else if (P_marker_offd[k1] >= jj_begin_row_offd) { ihat_offd[k1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = k1; ahat_offd[cnt_c_offd++] -= A_offd_data[kk]*distribute; } else { ihat_offd[k1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = k1; ahat_offd[cnt_f_offd++] -= A_offd_data[kk]*distribute; } } } } } } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] != strong_f_marker) { indx = ihat_offd[i1]; if (indx > -1) ahat_offd[indx] += A_offd_data[jj]; else if (P_marker_offd[i1] >= jj_begin_row_offd) { ihat_offd[i1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = i1; ahat_offd[cnt_c_offd++] += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { ihat_offd[i1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = i1; ahat_offd[cnt_f_offd++] += A_offd_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { distribute = A_offd_data[jj]/A_ext_data[A_ext_i[i1]]; for (kk = A_ext_i[i1]+1; kk < A_ext_i[i1+1]; kk++) { big_k1 = A_ext_j[kk]; if(big_k1 >= col_1 && big_k1 < col_n) { /*diag*/ loc_col = (HYPRE_Int)(big_k1 - col_1); indx = ihat[loc_col]; if (indx > -1) ahat[indx] -= A_ext_data[kk]*distribute; else if (P_marker[loc_col] >= jj_begin_row) { ihat[loc_col] = cnt_c; ipnt[cnt_c] = loc_col; ahat[cnt_c++] -= A_ext_data[kk]*distribute; } else { ihat[loc_col] = cnt_f; ipnt[cnt_f] = loc_col; ahat[cnt_f++] -= A_ext_data[kk]*distribute; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(num_functions == 1 || dof_func_offd[loc_col] == dof_func_offd[i1]) { indx = ihat_offd[loc_col]; if (indx > -1) ahat_offd[indx] -= A_ext_data[kk]*distribute; else if(P_marker_offd[loc_col] >= jj_begin_row_offd) { ihat_offd[loc_col] = cnt_c_offd; ipnt_offd[cnt_c_offd] = loc_col; ahat_offd[cnt_c_offd++] -= A_ext_data[kk]*distribute; } else { ihat_offd[loc_col] = cnt_f_offd; ipnt_offd[cnt_f_offd] = loc_col; ahat_offd[cnt_f_offd++] -= A_ext_data[kk]*distribute; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_2 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); diagonal = ahat[cnt_c]; ahat[cnt_c] = 0; sum_pos = 0; sum_pos_C = 0; sum_neg = 0; sum_neg_C = 0; sum = 0; sum_C = 0; if(sep_weight == 1) { for (jj=0; jj < cnt_c; jj++) { if (ahat[jj] > 0) { sum_pos_C += ahat[jj]; } else { sum_neg_C += ahat[jj]; } } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos_C += ahat_offd[jj]; } else { sum_neg_C += ahat_offd[jj]; } } } sum_pos = sum_pos_C; sum_neg = sum_neg_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { if (ahat[jj] > 0) { sum_pos += ahat[jj]; } else { sum_neg += ahat[jj]; } ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos += ahat_offd[jj]; } else { sum_neg += ahat_offd[jj]; } ahat_offd[jj] = 0; } } if (sum_neg_C*diagonal) alfa = sum_neg/sum_neg_C/diagonal; if (sum_pos_C*diagonal) beta = sum_pos/sum_pos_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; if (ahat[j1] > 0) P_diag_data[jj] = -beta*ahat[j1]; else P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; if (ahat_offd[j1] > 0) P_offd_data[jj] = -beta*ahat_offd[j1]; else P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } else { for (jj=0; jj < cnt_c; jj++) { sum_C += ahat[jj]; } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { sum_C += ahat_offd[jj]; } } sum = sum_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { sum += ahat[jj]; ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { sum += ahat_offd[jj]; ahat_offd[jj] = 0; } } if (sum_C*diagonal) alfa = sum/sum_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_3 += wall_time; fflush(NULL); } } } if (debug_flag==4) { hypre_printf("Proc = %d fill part 1 %f part 2 %f part 3 %f\n", my_id, wall_1, wall_2, wall_3); fflush(NULL); } P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); hypre_TFree(ahat, HYPRE_MEMORY_HOST); hypre_TFree(ihat, HYPRE_MEMORY_HOST); hypre_TFree(ipnt, HYPRE_MEMORY_HOST); if (full_off_procNodes) { hypre_TFree(ahat_offd, HYPRE_MEMORY_HOST); hypre_TFree(ihat_offd, HYPRE_MEMORY_HOST); hypre_TFree(ipnt_offd, HYPRE_MEMORY_HOST); } if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if(num_functions > 1) hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, i2, jj, kk, k1, jj1; HYPRE_BigInt big_k1; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = (HYPRE_Int)(num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]); /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; if(big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1-col_1); if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { big_k1 = Sop_j[kk]; /* Find local col number */ if(big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1-col_1); if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { big_k1 = A_ext_j[jj1]; if(big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if(P_marker[loc_col] >= jj_begin_row ) sum += A_ext_data[jj1]; } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd && (sgn*A_ext_data[jj1]) < 0) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { big_k1 = A_ext_j[jj1]; if(big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -(HYPRE_Int)big_k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if(num_functions > 1) hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; }
symv_x_csr_u_lo.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include<stdlib.h> static alphasparse_status_t symv_s_csr_u_lo_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mule(y[i], beta); alpha_madde(y[i], alpha, x[i]); } ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT); for(ALPHA_INT i = 0; i < num_threads; i++) { y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); memset(y_local[i], '\0', sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_Number tmp; for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col >= i) { continue; } else { alpha_setzero(tmp); alpha_mul(tmp, alpha, A->values[ai]); alpha_madde(y_local[tid][col], tmp, x[i]); alpha_madde(y_local[tid][i], tmp, x[col]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT row = 0; row < m; row++) for(ALPHA_INT i = 0; i < num_threads; i++) alpha_adde(y[row], y_local[i][row]); for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_free(y_local[i]); } alpha_free(y_local); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return symv_s_csr_u_lo_omp(alpha, A, x, beta, y); }
bert_layer_batch.h
#ifndef BERT_LAYER_BATCH_H_ #define BERT_LAYER_BATCH_H_ #include <new> #include <string> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <mkl.h> #include <omp.h> #include <iostream> #include <immintrin.h> #include "my_types.h" #include "timer.h" // int maxTokenSize = 128, int hiddenSize = 768, int intermediateSize = 3072, attentionHeadNum = 12 template<int maxTokenSize, int hiddenSize, int intermediateSize, int attentionHeadNum> class BatchBertLayer { public: BatchBertLayer(int layerIdx) { this->layerIdx = layerIdx; this->batchSize = 0; #pragma omp parallel { int tid = omp_get_thread_num(); if (tid == 0) { num_threads = omp_get_num_threads(); } } qk_result = NULL; magic_value = NULL; // Preoare buffer of exp_buffer exp_buffer = new FloatPointer[num_threads]; for (int i = 0; i < num_threads; ++i) { exp_buffer[i] = (float *)aligned_alloc(64, sizeof(float) * maxTokenSize); } // Preoare buffer of erf_buffer erf_buffer = new FloatPointer[num_threads]; for (int i = 0; i < num_threads; ++i) { erf_buffer[i] = (float *)aligned_alloc(64, sizeof(float) * intermediateSize); } } virtual ~BatchBertLayer() { // exp_buffer, erf_buffer for (int i = 0; i < num_threads; ++i) { free(exp_buffer[i]); free(erf_buffer[i]); } delete[] exp_buffer; delete[] erf_buffer; exp_buffer = NULL; erf_buffer = NULL; // qk_result if (qk_result) { for (int i = 0; i < attentionHeadNum * batchSize; ++i) { free(qk_result[i]); } delete[] qk_result; } // magic_value if (magic_value) { free(magic_value); } } // When set batch size, may need to prepare some buffers void setBatchSize(int batchSize) { int preBatch = this->batchSize; if (preBatch == batchSize) { return; } else { this->batchSize = batchSize; } qkvMatMul.Resize(batchSize * maxTokenSize, hiddenSize*3); resultBuffer1.Resize(batchSize * maxTokenSize, hiddenSize); resultBuffer2.Resize(batchSize * maxTokenSize, hiddenSize); intermediateBuffer.Resize(batchSize * maxTokenSize, intermediateSize); // Preoare buffer of qk_result if (qk_result) { for (int i = 0; i < attentionHeadNum * preBatch; ++i) { free(qk_result[i]); } delete[] qk_result; } qk_result = new FloatPointer[attentionHeadNum * batchSize]; for (int i = 0; i < attentionHeadNum * batchSize; ++i) { qk_result[i] = (float *)aligned_alloc(64, sizeof(float) * maxTokenSize * maxTokenSize); } // Preoare buffer of magic_value if (magic_value) { free(magic_value); } magic_value = (float *)aligned_alloc(64, sizeof(float) * batchSize * maxTokenSize); } void setWeights(const float *_queryWeight, const float *_queryBias, const float *_keyWeight, const float *_keyBias, const float *_valueWeight, const float *_valueBias, const float *_attentionOutputWeight, const float *_attentionOutputBias, const float *_gamma1, const float *_beta1, const float *_intermediateWeight, const float *_intermediateBias, const float *_outputWeight, const float *_outputBias, const float *_gamma2, const float *_beta2) { // Merged weights, dimension is like: 768*(768*3) hpj::Matrix<float> tmp; tmp.Resize(hiddenSize, hiddenSize * 3); copyWeights(tmp, 0, hiddenSize, _queryWeight); copyWeights(tmp, hiddenSize, hiddenSize*2, _keyWeight); copyWeights(tmp, hiddenSize*2, hiddenSize*3, _valueWeight); copyTransposed(qkvWeight, tmp); /* qkvWeight.Resize(hiddenSize, hiddenSize * 3); copyWeights(qkvWeight, 0, hiddenSize, _queryWeight); copyWeights(qkvWeight, hiddenSize, hiddenSize*2, _keyWeight); copyWeights(qkvWeight, hiddenSize*2, hiddenSize*3, _valueWeight); */ // Merged bias qkvBias.Resize(hiddenSize * 3); memcpy(qkvBias.Data(), _queryBias, sizeof(float) * hiddenSize); memcpy(qkvBias.Data() + hiddenSize, _keyBias, sizeof(float) * hiddenSize); memcpy(qkvBias.Data() + hiddenSize*2, _valueBias, sizeof(float) * hiddenSize); // Weights for attention output attentionOutputWeight.Resize(hiddenSize, hiddenSize); copyWeights(attentionOutputWeight, _attentionOutputWeight); attentionOutputBias.Resize(hiddenSize); memcpy(attentionOutputBias.Data(), _attentionOutputBias, sizeof(float) * hiddenSize); // gamma and beta for batchnorm after self attention gamma1.Resize(hiddenSize); beta1.Resize(hiddenSize); memcpy(gamma1.Data(), _gamma1, sizeof(float) * hiddenSize); memcpy(beta1.Data(), _beta1, sizeof(float) * hiddenSize); // intermediate weight and bias intermediateWeight.Resize(hiddenSize, intermediateSize); copyWeights(intermediateWeight, _intermediateWeight); intermediateBias.Resize(intermediateSize); memcpy(intermediateBias.Data(), _intermediateBias, sizeof(float) * intermediateSize); // output dense weight and bias outputWeight.Resize(intermediateSize, hiddenSize); copyWeights(outputWeight, _outputWeight); outputBias.Resize(hiddenSize); memcpy(outputBias.Data(), _outputBias, sizeof(float) * hiddenSize); // gamma and beta for the last batchnorm gamma2.Resize(hiddenSize); beta2.Resize(hiddenSize); memcpy(gamma2.Data(), _gamma2, sizeof(float) * hiddenSize); memcpy(beta2.Data(), _beta2, sizeof(float) * hiddenSize); } // Do the forward computing for the whole BERT layer // input: (batchSize * maxTokenSize) x hidden_size // actualTokens: #tokens = maxTokenSize - padded_tokens hpj::Matrix<float> &forward(hpj::Matrix<float> &inputBuffer, std::vector<int> &actualTokens) { setBatchSize(actualTokens.size()); // Query, Key, Value computed together sgemm(inputBuffer, qkvWeight, qkvMatMul); biasAdd(qkvMatMul, qkvBias); //dumpMatrix(qkvMatMul); // BatchMatMul hpj::Matrix<float> query(qkvMatMul, 0, qkvMatMul.Rows(), 0, hiddenSize); hpj::Matrix<float> key(qkvMatMul, 0, qkvMatMul.Rows(), hiddenSize, hiddenSize); hpj::Matrix<float> value(qkvMatMul, 0, qkvMatMul.Rows(), hiddenSize*2, hiddenSize); batchMatMul(query, key, qk_result); //printf("qk_result[0]=%f,%f\n", qk_result[0][0], qk_result[0][1]); //printf("qk_result[1]=%f,%f\n", qk_result[1][0], qk_result[1][1]); // Softmax computeSoftmax(actualTokens); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/self/Softmax:\n", layerIdx); printf("%f, %f, ...\n", qk_result[0][0], qk_result[0][1]); printf("%f, %f, ...\n", qk_result[1][0], qk_result[1][1]); #endif // BatchMatMul batchMatMul(qk_result, value, resultBuffer1); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/self/Reshape_3:\n", layerIdx); dumpMatrix(resultBuffer1); #endif // dense denseWithSum(resultBuffer1, attentionOutputWeight, attentionOutputBias, inputBuffer, resultBuffer2); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/output/add:\n", layerIdx); dumpMatrix(resultBuffer2); #endif // batchmorm batchnorm(resultBuffer2, gamma1, beta1); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/output/LayerNorm/batchnorm/add_1:\n", layerIdx); dumpMatrix(resultBuffer2); #endif // intermediate intermediate(resultBuffer2, intermediateBuffer); #ifdef DEBUG printf("intermediate(bert/encoder/layer_%d/intermediate/dense/mul_1):\n", layerIdx); dumpMatrix(intermediateBuffer); #endif // dense in output denseWithSum(intermediateBuffer, outputWeight, outputBias, resultBuffer2, resultBuffer1); #ifdef DEBUG printf("bert/encoder/layer_%d/output/add:\n", layerIdx); dumpMatrix(resultBuffer1); #endif // batchnorm batchnorm(resultBuffer1, gamma2, beta2); #ifdef DEBUG printf("bert/encoder/layer_%d/output/LayerNorm/batchnorm/add_1:\n", layerIdx); dumpMatrix(resultBuffer1); #endif return resultBuffer1; } private: void copyWeights(hpj::Matrix<float> &w, int start_col, int end_col, const float *data) { hpj::Matrix<float> subW(w, 0, w.Rows(), start_col, end_col - start_col); copyWeights(subW, data); } void copyWeights(hpj::Matrix<float> &w, const float *data) { for (int i = 0; i < w.Rows(); ++i) { for (int j = 0; j < w.Cols(); ++j) { w(i, j) = *data++; } } } void copyTransposed(hpj::Matrix<float> &dst, hpj::Matrix<float> &src) { dst.Resize(src.Cols(), src.Rows()); for (int i = 0; i < dst.Rows(); ++i) { for (int j = 0; j < dst.Cols(); ++j) { dst(i, j) = src(j, i); } } } void dumpMatrix(hpj::Matrix<float> &m) { int cols = m.Cols(); for (int i = 0; i < m.Rows(); ++i) { if (m.Cols() < 10) { for (int j = 0; j < m.Cols(); ++j) { std::cout << m(i, j) << " "; } } else { std::cout << m(i, 0) << " " << m(i, 1) << " " << m(i, 2) << " ... " << m(i, cols-3) << " " << m(i, cols-2) << " " << m(i, cols-1); } std::cout << std::endl; } } // C = A * B // bTranspose: B need to be transposed or not void sgemm(hpj::Matrix<float> &A, hpj::Matrix<float> &B, hpj::Matrix<float> &C) { bool bTranspose = (A.Cols() != B.Rows()); int m = A.Rows(); int k = A.Cols(); int n = (bTranspose ? B.Rows() : B.Cols()); float alpha = 1; float beta = 0; cblas_sgemm(CblasRowMajor, CblasNoTrans, (bTranspose ? CblasTrans : CblasNoTrans), m, n, k, alpha, A.Data(), A.Stride(), B.Data(), B.Stride(), beta, C.Data(), C.Stride()); } // result = x * weight + bias + input void denseWithSum(hpj::Matrix<float> &x, hpj::Matrix<float> &weight, hpj::Vector<float> &bias, hpj::Matrix<float> &input, hpj::Matrix<float> &result) { assert(input.Rows() == result.Rows()); assert(input.Cols() == result.Cols()); sgemm(x, weight, result); float *pbias = bias.Data(); #pragma omp parallel for for (int i = 0; i < result.Rows(); ++i) { float *presult = result.Row(i); float *pinput = input.Row(i); #pragma omp simd for (int j = 0; j < result.Cols(); ++j) { presult[j] += pinput[j] + pbias[j]; } } } void batchnorm(hpj::Matrix<float> &x, hpj::Vector<float> &gamma, hpj::Vector<float> &beta) { assert(x.Rows() == batchSize * maxTokenSize); assert(x.Cols() == hiddenSize); float *pgamma = gamma.Data(); float *pbeta = beta.Data(); #pragma omp parallel for for (int i = 0; i < x.Rows(); ++i) { float sum = 0; float *px = x.Row(i); #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { sum += px[j]; } float mean = sum / hiddenSize; sum = 0; #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { float delta = (px[j] - mean); sum += delta * delta; } float tmp = sum / hiddenSize + 9.999999960041972e-13; float rvariance = 1.0f / sqrt(tmp); #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { px[j] = (px[j] - mean) * rvariance * pgamma[j] + pbeta[j]; } } } /*void intermediate(hpj::Matrix<float> &input, hpj::Matrix<float> &output) { sgemm(input, intermediateWeight, output); float *pbias = intermediateBias.Data(); float factor = 0.7978845608; // np.sqrt(2 / np.pi) #pragma omp parallel for for (int i = 0; i < output.Rows(); ++i) { int tid = omp_get_thread_num(); float *pout = output.Row(i); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { float x = pout[j] + pbias[j]; erf_buffer[tid][j] = x; pout[j] = factor * (x + 0.044715f * x * x * x); } vsTanh(output.Cols(), pout, pout); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { pout[j] = erf_buffer[tid][j] * 0.5f * (1 + pout[j]); } } }*/ void intermediate(hpj::Matrix<float> &input, hpj::Matrix<float> &output) { sgemm(input, intermediateWeight, output); float *pbias = intermediateBias.Data(); const float factor = sqrt(0.5f); const float scale = 0.5f / factor; #ifdef __INTEL_COMPILER #pragma omp parallel for for (int i = 0; i < output.Rows(); ++i) { float *pout = output.Row(i); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { float with_bias = pout[j] + pbias[j]; pout[j] = with_bias * 0.5f * (erf(with_bias * factor) + 1); } } #else #pragma omp parallel for for (int i = 0; i < output.Rows(); ++i) { int tid = omp_get_thread_num(); float *pout = output.Row(i); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { pout[j] = (pout[j] + pbias[j]) * factor; } vsErf(output.Cols(), pout, erf_buffer[tid]); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { pout[j] = pout[j] * scale * (erf_buffer[tid][j] + 1); } } #endif } // ONLY for dimension 768 // The first BatchMatMul inside self attention void batchMatMul(hpj::Matrix<float> &A, hpj::Matrix<float> &B, float **c_array){ #define GRP_COUNT 1 MKL_INT m[GRP_COUNT] = {maxTokenSize}; MKL_INT k[GRP_COUNT] = {64}; MKL_INT n[GRP_COUNT] = {maxTokenSize}; MKL_INT lda[GRP_COUNT] = {A.Stride()}; MKL_INT ldb[GRP_COUNT] = {B.Stride()}; MKL_INT ldc[GRP_COUNT] = {maxTokenSize}; CBLAS_TRANSPOSE transA[GRP_COUNT] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[GRP_COUNT] = { CblasTrans }; float alpha[GRP_COUNT] = {1.0}; float beta[GRP_COUNT] = {0.0}; const MKL_INT size_per_grp[GRP_COUNT] = {attentionHeadNum * batchSize}; // Total number of multiplications: attentionHeadNum * batchSize const float **a_array = new ConstFloatPointer[attentionHeadNum * batchSize]; const float **b_array = new ConstFloatPointer[attentionHeadNum * batchSize]; for (int b = 0; b < batchSize; ++b) { for (int i = 0; i < attentionHeadNum; ++i) { a_array[b*attentionHeadNum + i] = A.Row(b*maxTokenSize) + i * 64; b_array[b*attentionHeadNum + i] = B.Row(b*maxTokenSize) + i * 64; } } // Call cblas_sgemm_batch cblas_sgemm_batch ( CblasRowMajor, transA, transB, m, n, k, alpha, a_array, lda, b_array, ldb, beta, c_array, ldc, GRP_COUNT, size_per_grp); delete[] a_array; delete[] b_array; } // ONLY for dimension 768 // The second BatchMatMul inside self attention void batchMatMul(float *a_array[], hpj::Matrix<float> &B, hpj::Matrix<float> &C) { #define GRP_COUNT 1 MKL_INT m[GRP_COUNT] = {maxTokenSize}; MKL_INT k[GRP_COUNT] = {maxTokenSize}; MKL_INT n[GRP_COUNT] = {64}; MKL_INT lda[GRP_COUNT] = {maxTokenSize}; MKL_INT ldb[GRP_COUNT] = {B.Stride()}; MKL_INT ldc[GRP_COUNT] = {C.Stride()}; CBLAS_TRANSPOSE transA[GRP_COUNT] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[GRP_COUNT] = { CblasNoTrans }; float alpha[GRP_COUNT] = {1.0}; float beta[GRP_COUNT] = {0.0}; const MKL_INT size_per_grp[GRP_COUNT] = {attentionHeadNum * batchSize}; // Total number of multiplications: attentionHeadNum * batchSize const float **b_array = new ConstFloatPointer[attentionHeadNum * batchSize]; float **c_array = new FloatPointer[attentionHeadNum * batchSize]; for (int b = 0; b < batchSize; ++b) { for (int i = 0; i < attentionHeadNum; ++i) { b_array[b*attentionHeadNum + i] = B.Row(b*maxTokenSize) + i * 64; c_array[b*attentionHeadNum + i] = C.Row(b*maxTokenSize) + i * 64; } } // Call cblas_sgemm_batch cblas_sgemm_batch ( CblasRowMajor, transA, transB, m, n, k, alpha, (const float **)a_array, lda, (const float **)b_array, ldb, beta, c_array, ldc, GRP_COUNT, size_per_grp); delete[] b_array; delete[] c_array; } // Add bias to matrix void biasAdd(hpj::Matrix<float> &m, hpj::Vector<float> &bias) { float *pbias = bias.Data(); #pragma omp parallel for for (int i = 0; i < m.Rows(); ++i) { float *p = m.Row(i); #pragma omp simd for (int j = 0; j < m.Cols(); ++j) { p[j] += pbias[j]; } } } // input and output are both in qk_result void computeSoftmax(std::vector<int> &actualTokens) { #pragma omp parallel for for (int b = 0; b < batchSize; ++b) { memset(&magic_value[b * maxTokenSize], 0, sizeof(float) * actualTokens[b]); #pragma omp simd for (int i = actualTokens[b]; i < maxTokenSize; ++i) { magic_value[b * maxTokenSize + i] = -10000; } } #pragma omp parallel for collapse(2) for (int b = 0; b < batchSize; ++b) { for (int i = 0; i < attentionHeadNum; ++i) { int tid = omp_get_thread_num(); float *pbuffer = exp_buffer[tid]; float *result = qk_result[b*attentionHeadNum+i]; for (int row = 0; row < maxTokenSize; ++row) { float sum = 0; // max_val is used to avoid exp(x) = inf float max_val = std::numeric_limits<float>::min(); #pragma omp simd for (int j = 0; j < actualTokens[b]; ++j) { if (result[j] > max_val) { max_val = result[j]; } } max_val *= 0.125f; #ifdef __INTEL_COMPILER #pragma omp simd for (int j = 0; j < maxTokenSize; ++j) { pbuffer[j] = exp(result[j] * 0.125f + magic_value[b * maxTokenSize + j] - max_val); sum += pbuffer[j]; } #else #pragma omp simd for (int j = 0; j < maxTokenSize; ++j) { pbuffer[j] = result[j] * 0.125f + magic_value[b * maxTokenSize + j] - max_val; } vsExp(maxTokenSize, pbuffer, pbuffer); #pragma omp simd for (int j = 0; j < maxTokenSize; ++j) { sum += pbuffer[j]; } #endif float r_sum = 1.0f / sum; #pragma omp simd for (int j = 0; j < maxTokenSize; ++j) { result[j] = pbuffer[j] * r_sum; } result += maxTokenSize; } } } } private: // For debug usage int layerIdx; typedef float * FloatPointer; typedef const float * ConstFloatPointer; int batchSize; // Store the result of input*qkvWeight hpj::Matrix<float> qkvMatMul; // Buffer like the dimesion of 128x768 hpj::Matrix<float> resultBuffer1, resultBuffer2; // Buffer to store the result of intermediate hpj::Matrix<float> intermediateBuffer; // Store the BatchMatMul result of query and key float **qk_result; // Store the result of exp for each line float **exp_buffer; // Temp buffer in intermediate float **erf_buffer; // Magic value: 0 or -10000 float *magic_value; int num_threads; // Merged query, key, value weighs hpj::Matrix<float> qkvWeight; // Merged query, key, value bias hpj::Vector<float> qkvBias; hpj::Matrix<float> attentionOutputWeight; hpj::Vector<float> attentionOutputBias; // batchnorm param hpj::Vector<float> gamma1, beta1; hpj::Vector<float> gamma2, beta2; hpj::Matrix<float> intermediateWeight; hpj::Vector<float> intermediateBias; hpj::Matrix<float> outputWeight; hpj::Vector<float> outputBias; }; #endif
DRB073-doall2-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. */ #include <stdio.h> /* Two-dimensional array computation using loops: missing private(j). References to j in the loop cause data races. Data race pairs (we allow multiple ones to preserve the pattern): Write_set = {j@61:10, j@61:20} Read_set = {j@62:20, j@62:12, j61@:14, j61@:20} Any pair from Write_set vs. Write_set and Write_set vs. Read_set is a data race pair. */ int a[100][100]; int main() { int i,j; #pragma omp parallel for private(i, j) for (i=0;i<100;i++) #pragma omp parallel for private(j) for (j=0;j<100;j++) a[i][j]=i; #pragma omp parallel for private(i, j) for (i=0;i<100;i++) #pragma omp parallel for private(j) for (j=0;j<100;j++) a[i][j]=a[i][j]+1; for (i=0;i<100;i++) for (j=0;j<100;j++) printf("%d\n", a[i][j]); return 0; }
mongodb_fmt_plug.c
/* Cracker for both MongoDB system and sniffed network hashes. Hacked together * during November of 2012 by Dhiru Kholia <dhiru at openwall.com>. * * Based on https://github.com/cyberpunkych/attacking_mongodb * * Hash format for MongoDB system hashes: user:$mongodb$0$user$hash * Hash format for MongoDB network hashes: user:$mongodb$1$user$salt$hash * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, * are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_mongodb; #elif FMT_REGISTERS_H john_register_one(&fmt_mongodb); #else #include "md5.h" #include <string.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #ifdef __MIC__ #define OMP_SCALE 512 #else #define OMP_SCALE 16384 // Tuned on K8-dual HT #endif // __MIC__ #endif // OMP_SCALE #endif // _OPENMP #include "memdbg.h" #define FORMAT_LABEL "MongoDB" #define FORMAT_NAME "system / network" #define FORMAT_TAG "$mongodb$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 16 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN sizeof(uint32_t) #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests mongodb_tests[] = { {"$mongodb$0$sa$75692b1d11c072c6c79332e248c4f699", "sa"}, {"$mongodb$1$sa$58d3229c83e3f87e$0c85e3f74adce5d037426791940c820a", "sa"}, /* Ettercap generated test vectors */ {"$mongodb$1$sa$10441db416a99ffc$797d7e18879446845f10ae9d519960b2", "longpassword"}, {"$mongodb$1$longusername$86336266301fb552$1abe48bac6ad0bf567ab51b094f026a9", "longpassword"}, /* Ettercap fixed salt MiTM attack generated test vectors */ {"$mongodb$1$longusername$0000000000000000$53257e018399a241849cb04c70ba8daa", "longpassword"}, {"$mongodb$1$longusername$0000000000000000$10290925d16d81e50db242c9f3572d91", "longpassword@12345678"}, {"$mongodb$1$eight18_characters$8c82aec197929775$5c414259f7f7a42f8c4d1b6ffb37913a", "123"}, {"$mongodb$1$Herman$9b90cf265f3194d7$a5ca2c517c06fdfb773144d53fb26f56", "123456789"}, {"$mongodb$1$sz110$be8fa52f0e64c250$441d6ece7356c67dcc69dd26e7e0501f", "passWOrd"}, {"$mongodb$1$jack$304b81adddfb4d6f$c95e106f1d9952c88044a0b21a6bd3fd", ""}, // https://jira.mongodb.org/browse/SERVER-9476 {"$mongodb$1$z$ce88504553b16752$6deb79af26ebcdd2b2c40438008cb7b0", "g"}, // https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst {"$mongodb$1$user$2375531c32080ae8$21742f26431831d5cfca035a08c5bdf6", "pencil"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static struct custom_salt { int type; unsigned char salt[17]; unsigned char username[128]; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ptr, *ctcopy, *keeptr; int type, extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; if (!(ctcopy = strdup(ciphertext))) return 0; keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; if (!(ptr = strtokm(ctcopy, "$"))) /* type */ goto error; if (!isdec(ptr)) goto error; type = atoi(ptr); if (type != 0 && type != 1) goto error; if (!(ptr = strtokm(NULL, "$"))) /* username */ goto error; if (strlen(ptr) > 127) goto error; if (type == 0) { if (!(ptr = strtokm(NULL, "$"))) /* hash */ goto error; if (hexlenl(ptr, &extra) != 32 || extra) goto error; } else { if (!(ptr = strtokm(NULL, "$"))) /* salt */ goto error; if (hexlenl(ptr, &extra) != 16 || extra) goto error; if (!(ptr = strtokm(NULL, "$"))) /* hash */ goto error; if (hexlenl(ptr, &extra) != 32 || extra) goto error; } MEM_FREE(keeptr); return 1; error: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += FORMAT_TAG_LEN; /* skip over "$mongodb$" */ p = strtokm(ctcopy, "$"); cs.type = atoi(p); p = strtokm(NULL, "$"); strcpy((char*)cs.username, p); if (cs.type == 1) { p = strtokm(NULL, "$"); strcpy((char*)cs.salt, p); } MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } inline static void hex_encode(unsigned char *str, int len, unsigned char *out) { int i; for (i = 0; i < len; ++i) { out[0] = itoa16[str[i]>>4]; out[1] = itoa16[str[i]&0xF]; out += 2; } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { if (cur_salt->type == 0) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, cur_salt->username, strlen((char*)cur_salt->username)); MD5_Update(&ctx, ":mongo:", 7); MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Final((unsigned char*)crypt_out[index], &ctx); } else { unsigned char hexout[32]; unsigned char out[32]; MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, cur_salt->username, strlen((char*)cur_salt->username)); MD5_Update(&ctx, ":mongo:", 7); MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Final(out, &ctx); hex_encode(out, 16, hexout); MD5_Init(&ctx); MD5_Update(&ctx, cur_salt->salt, 16); MD5_Update(&ctx, cur_salt->username, strlen((char*)cur_salt->username)); MD5_Update(&ctx, hexout, 32); MD5_Final((unsigned char*)crypt_out[index], &ctx); } } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void mongodb_set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } /* * report salt type as first "tunable cost" */ static unsigned int mongodb_salt_type(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->type; } struct fmt_main fmt_mongodb = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD, { "salt type", /* FIXME: report user name length as 2nd cost? */ }, { FORMAT_TAG }, mongodb_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { mongodb_salt_type, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, mongodb_set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
xgboost_reg_eval.h
#ifndef XGBOOST_REG_EVAL_H #define XGBOOST_REG_EVAL_H /*! * \file xgboost_reg_eval.h * \brief evaluation metrics for regression and classification * \author Kailong Chen: chenkl198812@gmail.com, Tianqi Chen: tianqi.tchen@gmail.com */ #include <cmath> #include <vector> #include <algorithm> #include "../utils/xgboost_utils.h" #include "../utils/xgboost_omp.h" namespace xgboost{ namespace regression{ /*! \brief evaluator that evaluates the loss metrics */ struct IEvaluator{ /*! * \brief evaluate a specific metric * \param preds prediction * \param labels label */ virtual float Eval( const std::vector<float> &preds, const std::vector<float> &labels ) const= 0; /*! \return name of metric */ virtual const char *Name( void ) const= 0; }; /*! \brief RMSE */ struct EvalRMSE : public IEvaluator{ virtual float Eval( const std::vector<float> &preds, const std::vector<float> &labels ) const{ const unsigned ndata = static_cast<unsigned>( preds.size() ); float sum = 0.0; #pragma omp parallel for reduction(+:sum) schedule( static ) for( unsigned i = 0; i < ndata; ++ i ){ float diff = preds[i] - labels[i]; sum += diff * diff; } return sqrtf( sum / ndata ); } virtual const char *Name( void ) const{ return "rmse"; } }; /*! \brief Error */ struct EvalError : public IEvaluator{ virtual float Eval( const std::vector<float> &preds, const std::vector<float> &labels ) const{ const unsigned ndata = static_cast<unsigned>( preds.size() ); unsigned nerr = 0; #pragma omp parallel for reduction(+:nerr) schedule( static ) for( unsigned i = 0; i < ndata; ++ i ){ if( preds[i] > 0.5f ){ if( labels[i] < 0.5f ) nerr += 1; }else{ if( labels[i] > 0.5f ) nerr += 1; } } return static_cast<float>(nerr) / ndata; } virtual const char *Name( void ) const{ return "error"; } }; /*! \brief Error */ struct EvalLogLoss : public IEvaluator{ virtual float Eval( const std::vector<float> &preds, const std::vector<float> &labels ) const{ const unsigned ndata = static_cast<unsigned>( preds.size() ); unsigned nerr = 0; #pragma omp parallel for reduction(+:nerr) schedule( static ) for( unsigned i = 0; i < ndata; ++ i ){ const float y = labels[i]; const float py = preds[i]; nerr -= y * std::log(py) + (1.0f-y)*std::log(1-py); } return static_cast<float>(nerr) / ndata; } virtual const char *Name( void ) const{ return "negllik"; } }; }; namespace regression{ /*! \brief a set of evaluators */ struct EvalSet{ public: inline void AddEval( const char *name ){ if( !strcmp( name, "rmse") ) evals_.push_back( &rmse_ ); if( !strcmp( name, "error") ) evals_.push_back( &error_ ); if( !strcmp( name, "logloss") ) evals_.push_back( &logloss_ ); } inline void Init( void ){ std::sort( evals_.begin(), evals_.end() ); evals_.resize( std::unique( evals_.begin(), evals_.end() ) - evals_.begin() ); } inline void Eval( FILE *fo, const char *evname, const std::vector<float> &preds, const std::vector<float> &labels ) const{ for( size_t i = 0; i < evals_.size(); ++ i ){ float res = evals_[i]->Eval( preds, labels ); fprintf( fo, "\t%s-%s:%f", evname, evals_[i]->Name(), res ); } } private: EvalRMSE rmse_; EvalError error_; EvalLogLoss logloss_; std::vector<const IEvaluator*> evals_; }; }; }; #endif
validator.c
// // Created by chaos on 2/23/2021. // #include "validator.h" #ifdef USE_MPI #include <mpi.h> #endif #include <string.h> #include "crypto/cipher.h" #include "crypto/ec.h" #include "crypto/hash.h" #include "seed_iter.h" int CryptoFunc_aes256(const unsigned char* curr_seed, void* args) { CipherValidator* v = (CipherValidator*)args; if (v == NULL) { return -1; } return aes256EcbEncrypt(v->curr_cipher, curr_seed, v->msg, v->msg_size); } int CryptoCmp_aes256(void* args) { CipherValidator* v = (CipherValidator*)args; if (v == NULL || v->curr_cipher == NULL || v->client_cipher == NULL) { return -1; } return memcmp(v->curr_cipher, v->client_cipher, v->msg_size) != 0; } int CryptoFunc_cipher(const unsigned char* curr_seed, void* args) { CipherValidator* v = (CipherValidator*)args; if (v == NULL || v->ctx == NULL) { return 1; } if (evpEncrypt(v->curr_cipher, v->ctx, v->evp_cipher, curr_seed, v->msg, v->msg_size, v->iv)) { return 1; } // By setting the EVP structure to NULL, we avoid reallocation later if (v->evp_cipher != NULL) { v->evp_cipher = NULL; v->iv = NULL; } return 0; } int CryptoCmp_cipher(void* args) { CipherValidator* v = (CipherValidator*)args; if (v == NULL || v->curr_cipher == NULL || v->client_cipher == NULL) { return -1; } return memcmp(v->curr_cipher, v->client_cipher, v->msg_size) != 0; } int CryptoFunc_ec(const unsigned char* curr_seed, void* args) { EcValidator* v = (EcValidator*)args; if (v == NULL) { return -1; } return getEcPublicKey(v->curr_point, v->ctx, v->group, curr_seed, SEED_SIZE); } int CryptoCmp_ec(void* args) { EcValidator* v = (EcValidator*)args; if (v == NULL) { return -1; } return EC_POINT_cmp(v->group, v->curr_point, v->client_point, v->ctx); } int CryptoFunc_hash(const unsigned char* curr_seed, void* args) { HashValidator* v = (HashValidator*)args; if (v == NULL) { return -1; } switch (v->nid) { #ifndef ALWAYS_EVP_HASH case NID_md5: return md5Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha1: return sha1Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha224: return sha224Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha256: return sha256Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha384: return sha384Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha512: return sha512Hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); #endif #ifndef ALWAYS_EVP_SHA3 case NID_sha3_224: return sha3_224_hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha3_256: return sha3_256_hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha3_384: return sha3_384_hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_sha3_512: return sha3_512_hash(v->curr_digest, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_shake128: return shake128_hash(v->curr_digest, v->digest_size, curr_seed, SEED_SIZE, v->salt, v->salt_size); case NID_shake256: return shake256_hash(v->curr_digest, v->digest_size, curr_seed, SEED_SIZE, v->salt, v->salt_size); #endif case NID_kang12: return kang12Hash(v->curr_digest, v->digest_size, curr_seed, SEED_SIZE, v->salt, v->salt_size); default: return evpHash(v->curr_digest, v->is_xof ? &(v->digest_size) : NULL, v->ctx, v->md, curr_seed, SEED_SIZE, v->salt, v->salt_size); } } int CryptoCmp_hash(void* args) { HashValidator* v = (HashValidator*)args; if (v == NULL) { return -1; } return memcmp(v->curr_digest, v->client_digest, v->digest_size) != 0; } int CryptoFunc_kang12(const unsigned char* curr_seed, void* args) { Kang12Validator* v = (Kang12Validator*)args; if (v == NULL) { return 1; } return kang12Hash(v->curr_digest, v->digest_size, curr_seed, SEED_SIZE, v->salt, v->salt_size); } int CryptoCmp_kang12(void* args) { Kang12Validator* v = (Kang12Validator*)args; if (v == NULL) { return -1; } return memcmp(v->curr_digest, v->client_digest, v->digest_size) != 0; } CipherValidator* CipherValidator_create(const EVP_CIPHER* evp_cipher, const unsigned char* client_cipher, const unsigned char* msg, size_t msg_size, const unsigned char* iv) { CipherValidator* v = malloc(sizeof(*v)); if (v == NULL) { return NULL; } v->evp_cipher = evp_cipher; v->msg_size = msg_size; v->msg = msg; v->client_cipher = client_cipher; // IV is optional as NULL depending on the cipher chosen v->iv = iv; v->curr_cipher = malloc(msg_size * sizeof(*(v->curr_cipher))); v->ctx = EVP_CIPHER_CTX_new(); if (v->evp_cipher == NULL || v->msg == NULL || v->client_cipher == NULL || v->curr_cipher == NULL || v->ctx == NULL) { CipherValidator_destroy(v); return NULL; } if (v->msg_size % EVP_CIPHER_block_size(v->evp_cipher) != 0) { CipherValidator_destroy(v); return NULL; } if ((v->iv == NULL && EVP_CIPHER_iv_length(v->evp_cipher) != 0) || (v->iv != NULL && EVP_CIPHER_iv_length(v->evp_cipher) == 0)) { CipherValidator_destroy(v); return NULL; } return v; } void CipherValidator_destroy(CipherValidator* v) { if (v == NULL) { return; } if (v->ctx != NULL) { EVP_CIPHER_CTX_free(v->ctx); } if (v->curr_cipher != NULL) { free(v->curr_cipher); } free(v); } EcValidator* EcValidator_create(const EC_GROUP* group, const EC_POINT* client_point) { EcValidator* v = malloc(sizeof(*v)); if (v == NULL || group == NULL || client_point == NULL) { EcValidator_destroy(v); return NULL; } v->group = group; v->client_point = client_point; v->curr_point = EC_POINT_new(v->group); v->ctx = BN_CTX_secure_new(); if (v->curr_point == NULL || v->ctx == NULL) { EcValidator_destroy(v); return NULL; } return v; } void EcValidator_destroy(EcValidator* v) { if (v == NULL) { return; } if (v->ctx != NULL) { BN_CTX_free(v->ctx); } if (v->curr_point != NULL) { EC_POINT_free(v->curr_point); } free(v); } HashValidator* HashValidator_create(const EVP_MD* md, const unsigned char* client_digest, size_t digest_size, const unsigned char* salt, size_t salt_size) { HashValidator* v = malloc(sizeof(*v)); if (v == NULL || md == NULL || client_digest == NULL || (salt == NULL && salt_size != 0) || (salt != NULL && salt_size == 0)) { HashValidator_destroy(v); return NULL; } v->md = md; v->nid = EVP_MD_nid(md); v->is_xof = md == EVP_shake128() || md == EVP_shake256(); v->digest_size = v->is_xof ? EVP_MD_size(md) : digest_size; v->client_digest = client_digest; v->salt = salt; v->salt_size = salt_size; v->curr_digest = malloc(v->digest_size * sizeof(*(v->curr_digest))); v->ctx = EVP_MD_CTX_new(); if (v->curr_digest == NULL || v->ctx == NULL) { HashValidator_destroy(v); return NULL; } if (salt_size == 0) { EVP_MD_CTX_set_flags(v->ctx, EVP_MD_CTX_FLAG_ONESHOT); } return v; } void HashValidator_destroy(HashValidator* v) { if (v == NULL) { return; } if (v->ctx != NULL) { EVP_MD_CTX_free(v->ctx); } if (v->curr_digest != NULL) { free(v->curr_digest); } free(v); } Kang12Validator* Kang12Validator_create(const unsigned char* client_digest, size_t digest_size, const unsigned char* salt, size_t salt_size) { Kang12Validator* v = malloc(sizeof(*v)); if (v == NULL || client_digest == NULL || digest_size == 0 || (salt == NULL && salt_size != 0) || (salt != NULL && salt_size == 0)) { Kang12Validator_destroy(v); return NULL; } v->digest_size = digest_size; v->client_digest = client_digest; v->salt = salt; v->salt_size = salt_size; v->curr_digest = malloc(v->digest_size * sizeof(*(v->curr_digest))); return v; } void Kang12Validator_destroy(Kang12Validator* v) { if (v == NULL) { return; } if (v->curr_digest != NULL) { free(v->curr_digest); } free(v); } int findMatchingSeed(unsigned char* client_seed, const unsigned char* host_seed, const mpz_t first_perm, const mpz_t last_perm, int all, long long int* validated_keys, #ifdef USE_MPI int* signal, int verbose, int my_rank, int nprocs, #else const int* signal, #endif int (*crypto_func)(const unsigned char*, void*), int (*crypto_cmp)(void*), void* crypto_args) { // Declaration int status = 0, cmp_status = 1; SeedIter iter; const unsigned char* curr_seed; #ifdef USE_MPI int probe_flag = 0; long long int iter_count = 0; MPI_Request* requests; MPI_Status* statuses; if ((requests = malloc(nprocs * sizeof(*(requests)))) == NULL) { return -1; } if ((statuses = malloc(nprocs * sizeof(*(statuses)))) == NULL) { free(requests); return -1; } #endif SeedIter_init(&iter, host_seed, SEED_SIZE, first_perm, last_perm); while (!SeedIter_end(&iter) && (all || !(*signal))) { if (validated_keys != NULL) { ++(*validated_keys); } curr_seed = SeedIter_get(&iter); // If crypto_func fails for some reason, break prematurely. if (crypto_func != NULL && crypto_func(curr_seed, crypto_args)) { status = -1; break; } // If crypto_cmp fails for some reason, break prematurely. if (crypto_cmp != NULL && (cmp_status = crypto_cmp(crypto_args)) < 0) { status = -1; break; } // If the new crypto output is the same as the passed in client crypto output, set status to // true and break if (cmp_status == 0) { status = 1; #ifdef USE_MPI *signal = 1; if (verbose) { fprintf(stderr, "INFO: Found by rank: %d, alerting ranks ...\n", my_rank); } memcpy(client_seed, curr_seed, SEED_SIZE); if (!all) { // alert all ranks that the key was found, including yourself for (int i = 0; i < nprocs; i++) { if (i != my_rank) { MPI_Isend(signal, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &(requests[i])); } } for (int i = 0; i < nprocs; i++) { if (i != my_rank) { MPI_Wait(&(requests[i]), MPI_STATUS_IGNORE); } } } #else // Only have one thread copy the host_seed at a time // This might happen more than once if the # of threads exceeds the number of possible // keys #pragma omp critical memcpy(client_seed, curr_seed, SEED_SIZE); if (!all) { break; } #endif } #ifdef USE_MPI if (!all && !(*signal) && iter_count % 128 == 0) { MPI_Iprobe(MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &probe_flag, MPI_STATUS_IGNORE); if (probe_flag) { MPI_Recv(signal, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } #endif SeedIter_next(&iter); } #ifdef USE_MPI free(requests); free(statuses); #endif return status; }
math_libmextras.c
#include <stdio.h> #include <math.h> #include <omp_libmextras.h> #define FUNC(x) sinpi(x) #define TYPE double #define EPS 1e-5 void vmul(TYPE*a, TYPE*b, TYPE*c, int N){ #pragma omp target map(to: a[0:N],b[0:N]) map(from:c[0:N]) #pragma omp teams distribute parallel for for(int i=0; i<N; i++) { c[i]=FUNC(a[i])*FUNC(b[i]); } } int main(){ const int N = 100; TYPE a[N], b[N], c[N], validate[N]; TYPE delta, delta_max=0; int flag=-1, flag_max=-1; // Mark Success for(int i=0; i<N; i++) { a[i]=i+1; b[i]=i+2; validate[i]=FUNC(a[i])*FUNC(b[i]); } vmul(a,b,c,N); for(int i=0; i<N; i++) { delta=fabs(c[i]-validate[i]); if(delta > EPS) { // print 1st bad index if(flag == -1) printf("First fail: c[%d](%g) != validate[%d](%g) <%g>\n", i,c[i],i,validate[i],c[i]-validate[i]); if(delta > delta_max) { delta_max=delta; flag_max=flag; } flag = i; } } if(flag == -1){ printf("Success\n"); return 0; } else { printf("Last fail: c[%d](%g) != validate[%d](%g) <%g>\n", flag,c[flag],flag,validate[flag],c[flag]-validate[flag]); printf("Max fail: c[%d](%g) != validate[%d](%g) <%g>\n", flag_max, c[flag_max],flag_max,validate[flag_max],c[flag_max]-validate[flag_max]); printf("Fail\n"); return 1; } }
problem.c
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @file src/control/problem.c * @version 0.3.0 * @author Aleksandr Mikhalev * @date 2017-11-07 * */ #include "common.h" #include "starsh.h" int starsh_problem_new(STARSH_problem **problem, int ndim, STARSH_int *shape, char symm, char dtype, void *row_data, void *col_data, STARSH_kernel *kernel, const char *name) //! Init @ref STARSH_problem object. /*! Unlike all other *_new() functions, this function creates copy of `shape` * to store internally. This is done to avoid clearing memory of static * objects, defined like `STARSH_int shape[2] = {10, 20}`. Number of dimensions * must be 2 or greater. If `ndim = 2`, then corresponding kernel is scalar. If * `ndim > 2`, then corresponding kernel returns `(ndim-2)`-dimensional tensor. * * @param[out] problem: Address of pointer to @ref STARSH_problem object. * @param[in] ndim: Dimensionality of corresponding array. Equal to `2` plus * dimensionality of kernel. * @param[in] shape: Shape of corresponding array. Subarray `shape[1:ndim-2]` * is equal to shape of kernel. * @param[in] symm: 'S' for summetric problem, 'N' for nonsymmetric. Symmetric * problem requires symmetric kernel and equality of `row_data` and * `col_data`. * @param[in] dtype: Data type of the problem. Equal to 's', 'd', 'c' or 'z' * as in LAPACK routines. * @param[in] row_data: Pointer to some structure of physical data for rows. * @param[in] col_data: Pointer to some structure of physical data for columns. * @param[in] kernel: Pointer to a function of interaction. * @param[in] name: String, containing name of the problem. * @return Error code @ref STARSH_ERRNO. * @ingroup problem * */ { if(problem == NULL) { STARSH_ERROR("Invalid value of `problem`"); return STARSH_WRONG_PARAMETER; } if(ndim < 2) { STARSH_ERROR("Invalid value of `ndim`"); return STARSH_WRONG_PARAMETER; } if(shape == NULL) { STARSH_ERROR("Invalid value of `shape`"); return STARSH_WRONG_PARAMETER; } if(kernel == NULL) { STARSH_ERROR("Invalid value of `kernel`"); return STARSH_WRONG_PARAMETER; } int i; size_t dtype_size = 0; if(dtype == 's') dtype_size = sizeof(float); else if(dtype == 'd') dtype_size = sizeof(double); else if(dtype == 'c') dtype_size = sizeof(float complex); else if(dtype == 'z') dtype_size = sizeof(double complex); else { STARSH_ERROR("Invalid value of `dtype`"); return STARSH_WRONG_PARAMETER; } size_t entry_size = dtype_size; for(i = 1; i < ndim-1; i++) entry_size *= shape[i]; STARSH_problem *P; STARSH_MALLOC(P, 1); *problem = P; P->ndim = ndim; STARSH_MALLOC(P->shape, ndim); memcpy(P->shape, shape, ndim*sizeof(*P->shape)); P->symm = symm; P->dtype = dtype; P->dtype_size = dtype_size; P->entry_size = entry_size; P->row_data = row_data; P->col_data = col_data; P->kernel = kernel; P->name = NULL; if(name != NULL) { STARSH_MALLOC(P->name, strlen(name)+1); strcpy(P->name, name); } return STARSH_SUCCESS; } void starsh_problem_free(STARSH_problem *problem) //! Free @ref STARSH_problem object. //! @ingroup problem { if(problem == NULL) return; free(problem->shape); if(problem->name != NULL) free(problem->name); free(problem); } void starsh_problem_info(STARSH_problem *problem) //! Print short info about @ref STARSH_problem object. //! @ingroup problem { if(problem == NULL) return; STARSH_problem *P = problem; printf("<STARS_Problem at %p, name \"%s\", shape (%zd", P, P->name, P->shape[0]); for(int i = 1; i < P->ndim; i++) printf(",%zd", P->shape[i]); printf("), '%c' dtype, '%c' symmetric>\n", P->dtype, P->symm); } int starsh_problem_get_block(STARSH_problem *problem, int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, Array **A) //! Get submatrix on given rows and columns. /*! Rows correspond to the first dimension and columns correspond to the * last dimension. * * @param[in] problem: Pointer to @ref STARSH_problem object. * @param[in] nrows: Number of rows. * @param[in] ncols: Number of columns. * @param[in] irow: Indexes of rows. * @param[in] icol: Indexes of columns. * @param[out] A: Address of pointer to @ref array object. * @return Error code @ref STARSH_ERRNO. * @ingroup problem * */ { STARSH_problem *P = problem; if(problem == NULL) { STARSH_ERROR("Invalid value of `parameter`"); return STARSH_WRONG_PARAMETER; } if(irow == NULL) { STARSH_ERROR("Invalid value of `irow`"); return STARSH_WRONG_PARAMETER; } if(icol == NULL) { STARSH_ERROR("Invalid value of `icol`"); return STARSH_WRONG_PARAMETER; } int ndim = P->ndim, info; if(nrows < 0) { STARSH_ERROR("Invalid value of `nrows`"); return STARSH_WRONG_PARAMETER; } if(ncols < 0) { STARSH_ERROR("Invalid value of `ncols`"); return STARSH_WRONG_PARAMETER; } int *shape; STARSH_MALLOC(shape, ndim); shape[0] = nrows; shape[ndim-1] = ncols; for(int i = 1; i < ndim-1; i++) { shape[i] = problem->shape[i]; } info = array_new(A, ndim, shape, problem->dtype, 'F'); if(info != 0) return info; problem->kernel(nrows, ncols, irow, icol, problem->row_data, problem->col_data, (*A)->data, nrows); return STARSH_SUCCESS; } static void _matrix_kernel(int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, void *row_data, void *col_data, void *result, int ld) //! Kernel for problems, defined by dense matrices. //! @ingroup problem { Array *A = row_data; size_t esize = A->dtype_size; STARSH_int i, j; size_t dest, src, lda; for(int i = 1; i < A->ndim-1; i++) esize *= A->shape[i]; if(A->order == 'C') { lda = A->shape[A->ndim-1]; //#pragma omp parallel for private(dest, src, i, j) for(i = 0; i < nrows; i++) for(j = 0; j < ncols; j++) { dest = j*(size_t)ld+i; src = irow[i]*lda+icol[j]; memcpy(result+dest*esize, A->data+src*esize, esize); } } else { lda = A->shape[0]; //#pragma omp parallel for private(dest, src, i, j) for(i = 0; i < nrows; i++) for(j = 0; j < ncols; j++) { dest = j*(size_t)ld+i; src = icol[j]*lda+irow[i]; memcpy(result+dest*esize, A->data+src*esize, esize); } } } int starsh_problem_from_array(STARSH_problem **problem, Array *A, char symm) //! Create STARSH_problem instance, based on dense array. /*! If @ref array `A` is sorted in C order, then temporary @ref array object * will be created as a copy of input `A`, but in Fortran order. There will be * no way to free that temporary @ref array object. * * @param[out] problem: Address of pointer to @ref STARSH_problem object. * @param[in] A: Array. * @param[in] symm: 'S' if @ref array `A` is symmetric or 'N' otherwise. * @return Error code @ref STARSH_ERRNO. * @ingroup problem * */ { if(problem == NULL) { STARSH_ERROR("Invalid value of `problem`"); return STARSH_WRONG_PARAMETER; } if(A == NULL) { STARSH_ERROR("Invalid value of `A`"); return STARSH_WRONG_PARAMETER; } if(A->ndim < 2) { STARSH_ERROR("`A` should be at least two-dimensional"); return STARSH_WRONG_PARAMETER; } if(symm != 'S' && symm != 'N') { STARSH_ERROR("Invalid value of `symm`"); return STARSH_WRONG_PARAMETER; } Array *A2 = A; int info; if(A->order == 'C') { STARSH_WARNING("A->order is 'C', creating " "copy of array with layout in Fortran style ('F'-order). It " "makes corresponding matrix non-freeable"); info = array_new_copy(&A2, A, 'F'); if(info != 0) return info; } STARSH_int shape[A->ndim]; for(int i = 0; i < A->ndim; i++) shape[i] = A->shape[i]; info = starsh_problem_new(problem, A->ndim, shape, symm, A->dtype, A2, A2, _matrix_kernel, "Problem from matrix"); return info; } int starsh_problem_to_array(STARSH_problem *problem, Array **A) //! Generate dense array by a given problem. /*! Dense matrix will be created. This function makes it easier to check * kernel. * * @param[in] problem: Pointer to @ref STARSH_problem object. * @param[out] A: Address of pointer to @ref array object. * @return Error code @ref STARSH_ERRNO. * @ingroup problem * */ { if(problem == NULL) { STARSH_ERROR("Invalid value of `problem`"); return STARSH_WRONG_PARAMETER; } if(A == NULL) { STARSH_ERROR("Invalid value of `A`"); return STARSH_WRONG_PARAMETER; } STARSH_int i; int info; int ndim = problem->ndim; STARSH_int nrows = problem->shape[0]; STARSH_int ncols = problem->shape[ndim-1]; STARSH_int *irow, *icol; STARSH_MALLOC(irow, nrows); STARSH_MALLOC(icol, ncols); for(i = 0; i < nrows; i++) irow[i] = i; for(i = 0; i < ncols; i++) icol[i] = i; info = starsh_problem_get_block(problem, nrows, ncols, irow, icol, A); free(irow); free(icol); return info; }
grid.c
/* Copyright 2014-2015 The Regents of the University of California. * Copyright 2015-2019 Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * 2011-2019 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2014 Frank Ong <frankong@berkeley.edu> */ #include <math.h> #include <complex.h> #include <assert.h> #include <string.h> #include "num/multind.h" #include "num/flpmath.h" #include "num/specfun.h" #include "misc/nested.h" #include "misc/misc.h" #include "grid.h" static double kb(double beta, double x) { if (fabs(x) >= 0.5) return 0.; return bessel_i0(beta * sqrt(1. - pow(2. * x, 2.))) / bessel_i0(beta); } static void kb_precompute(double beta, int n, float table[n + 1]) { for (int i = 0; i < n + 1; i++) table[i] = kb(beta, (double)(i) / (double)(n - 1) / 2.); } static double ftkb(double beta, double x) { double a = sqrt(pow(beta, 2.) - pow(M_PI * x, 2.)); return ((0. == a) ? 1. : (a / sinh(a))); // * bessel_i0(beta); } static double rolloff(double x, double beta, double width) { return ftkb(beta, x * width) / ftkb(beta, 0.); } // Linear interpolation static float lerp(float a, float b, float c) { return (1. - c) * a + c * b; } // Linear interpolation look up static float intlookup(int n, const float table[n + 1], float x) { float fpart; // fpart = modff(x * n, &ipart); // int index = ipart; int index = (int)(x * (n - 1)); fpart = x * (n - 1) - (float)index; #if 1 assert(index >= 0); assert(index <= n); assert(fpart >= 0.); assert(fpart <= 1.); #endif float l = lerp(table[index], table[index + 1], fpart); #if 1 assert(l <= 1.); assert(0 >= 0.); #endif return l; } enum { kb_size = 100 }; static float kb_table[kb_size + 1]; static float kb_beta = -1.; void gridH(const struct grid_conf_s* conf, const complex float* traj, const long ksp_dims[4], complex float* dst, const long grid_dims[4], const complex float* grid) { long C = ksp_dims[3]; // precompute kaiser bessel table #pragma omp critical if (-1 == kb_beta) { kb_precompute(conf->beta, kb_size, kb_table); kb_beta = conf->beta; } assert(fabs(kb_beta - conf->beta) < 1.E-6); assert(1 == ksp_dims[0]); long samples = ksp_dims[1] * ksp_dims[2]; #pragma omp parallel for for(int i = 0; i < samples; i++) { float pos[3]; pos[0] = conf->os * (creal(traj[i * 3 + 0])); pos[1] = conf->os * (creal(traj[i * 3 + 1])); pos[2] = conf->os * (creal(traj[i * 3 + 2])); pos[0] += (grid_dims[0] > 1) ? ((float)grid_dims[0] / 2.) : 0.; pos[1] += (grid_dims[1] > 1) ? ((float)grid_dims[1] / 2.) : 0.; pos[2] += (grid_dims[2] > 1) ? ((float)grid_dims[2] / 2.) : 0.; complex float val[C]; for (int j = 0; j < C; j++) val[j] = 0.0; grid_pointH(C, 3, grid_dims, pos, val, grid, conf->periodic, conf->width, kb_size, kb_table); for (int j = 0; j < C; j++) dst[j * samples + i] += val[j]; } } void grid(const struct grid_conf_s* conf, const complex float* traj, const long grid_dims[4], complex float* grid, const long ksp_dims[4], const complex float* src) { long C = ksp_dims[3]; // precompute kaiser bessel table #pragma omp critical if (-1 == kb_beta) { kb_precompute(conf->beta, kb_size, kb_table); kb_beta = conf->beta; } assert(fabs(kb_beta - conf->beta) < 1.E-6); assert(1 == ksp_dims[0]); long samples = ksp_dims[1] * ksp_dims[2]; // grid #pragma omp parallel for for(int i = 0; i < samples; i++) { float pos[3]; pos[0] = conf->os * (creal(traj[i * 3 + 0])); pos[1] = conf->os * (creal(traj[i * 3 + 1])); pos[2] = conf->os * (creal(traj[i * 3 + 2])); pos[0] += (grid_dims[0] > 1) ? ((float) grid_dims[0] / 2.) : 0.; pos[1] += (grid_dims[1] > 1) ? ((float) grid_dims[1] / 2.) : 0.; pos[2] += (grid_dims[2] > 1) ? ((float) grid_dims[2] / 2.) : 0.; complex float val[C]; for (int j = 0; j < C; j++) val[j] = src[j * samples + i]; grid_point(C, 3, grid_dims, pos, grid, val, conf->periodic, conf->width, kb_size, kb_table); } } static void grid2_dims(unsigned int D, const long trj_dims[D], const long ksp_dims[D], const long grid_dims[D]) { assert(D >= 4); assert(md_check_compat(D - 3, ~0, grid_dims + 3, ksp_dims + 3)); // assert(md_check_compat(D - 3, ~(MD_BIT(0) | MD_BIT(1)), trj_dims + 3, ksp_dims + 3)); assert(md_check_bounds(D - 3, ~0, trj_dims + 3, ksp_dims + 3)); assert(3 == trj_dims[0]); assert(1 == trj_dims[3]); assert(1 == ksp_dims[0]); } void grid2(const struct grid_conf_s* conf, unsigned int D, const long trj_dims[D], const complex float* traj, const long grid_dims[D], complex float* dst, const long ksp_dims[D], const complex float* src) { grid2_dims(D, trj_dims, ksp_dims, grid_dims); long ksp_strs[D]; md_calc_strides(D, ksp_strs, ksp_dims, CFL_SIZE); long trj_strs[D]; md_calc_strides(D, trj_strs, trj_dims, CFL_SIZE); long grid_strs[D]; md_calc_strides(D, grid_strs, grid_dims, CFL_SIZE); long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = 0; do { grid(conf, &MD_ACCESS(D, trj_strs, pos, traj), grid_dims, &MD_ACCESS(D, grid_strs, pos, dst), ksp_dims, &MD_ACCESS(D, ksp_strs, pos, src)); } while(md_next(D, ksp_dims, (~0 ^ 15), pos)); } void grid2H(const struct grid_conf_s* conf, unsigned int D, const long trj_dims[D], const complex float* traj, const long ksp_dims[D], complex float* dst, const long grid_dims[D], const complex float* src) { grid2_dims(D, trj_dims, ksp_dims, grid_dims); long ksp_strs[D]; md_calc_strides(D, ksp_strs, ksp_dims, CFL_SIZE); long trj_strs[D]; md_calc_strides(D, trj_strs, trj_dims, CFL_SIZE); long grid_strs[D]; md_calc_strides(D, grid_strs, grid_dims, CFL_SIZE); long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = 0; do { gridH(conf, &MD_ACCESS(D, trj_strs, pos, traj), ksp_dims, &MD_ACCESS(D, ksp_strs, pos, dst), grid_dims, &MD_ACCESS(D, grid_strs, pos, src)); } while(md_next(D, ksp_dims, (~0 ^ 15), pos)); } typedef void CLOSURE_TYPE(grid_update_t)(long ind, float d); #ifndef __clang__ #define VLA(x) x #else // blocks extension does not play well even with arguments which // just look like variably-modified types #define VLA(x) #endif static void grid_point_gen(int N, const long dims[VLA(N)], const float pos[VLA(N)], bool periodic, float width, int kb_size, const float kb_table[VLA(kb_size + 1)], grid_update_t update) { #ifndef __clang__ int sti[N]; int eni[N]; int off[N]; #else // blocks extension does not play well with variably-modified types int* sti = alloca(sizeof(int[N])); int* eni = alloca(sizeof(int[N])); int* off = alloca(sizeof(int[N])); #endif for (int j = 0; j < N; j++) { sti[j] = (int)ceil(pos[j] - width); eni[j] = (int)floor(pos[j] + width); off[j] = 0; if (sti[j] > eni[j]) return; if (!periodic) { sti[j] = MAX(sti[j], 0); eni[j] = MIN(eni[j], dims[j] - 1); } else { while (sti[j] + off[j] < 0) off[j] += dims[j]; } if (1 == dims[j]) { assert(0. == pos[j]); // ==0. fails nondeterministically for test_nufft_forward bbdec08cb sti[j] = 0; eni[j] = 0; } } __block NESTED(void, grid_point_r, (int N, long ind, float d)) // __block for recursion { if (0 == N) { NESTED_CALL(update, (ind, d)); } else { N--; for (int w = sti[N]; w <= eni[N]; w++) { float frac = fabs(((float)w - pos[N])); float d2 = d * intlookup(kb_size, kb_table, frac / width); long ind2 = (ind * dims[N] + ((w + off[N]) % dims[N])); grid_point_r(N, ind2, d2); } } }; grid_point_r(N, 0, 1.); } void grid_point(unsigned int ch, int N, const long dims[VLA(N)], const float pos[VLA(N)], complex float* dst, const complex float val[VLA(ch)], bool periodic, float width, int kb_size, const float kb_table[kb_size + 1]) { NESTED(void, update, (long ind, float d)) { for (unsigned int c = 0; c < ch; c++) { // we are allowed to update real and imaginary part independently which works atomically #pragma omp atomic __real(dst[ind + c * dims[0] * dims[1] * dims[2]]) += __real(val[c]) * d; #pragma omp atomic __imag(dst[ind + c * dims[0] * dims[1] * dims[2]]) += __imag(val[c]) * d; } }; grid_point_gen(N, dims, pos, periodic, width, kb_size, kb_table, update); } void grid_pointH(unsigned int ch, int N, const long dims[VLA(N)], const float pos[VLA(N)], complex float val[VLA(ch)], const complex float* src, bool periodic, float width, int kb_size, const float kb_table[kb_size + 1]) { NESTED(void, update, (long ind, float d)) { for (unsigned int c = 0; c < ch; c++) { __real(val[c]) += __real(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; __imag(val[c]) += __imag(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; } }; grid_point_gen(N, dims, pos, periodic, width, kb_size, kb_table, update); } double calc_beta(float os, float width) { return M_PI * sqrt(pow((width * 2. / os) * (os - 0.5), 2.) - 0.8); } static float pos(int d, int i) { return (1 == d) ? 0. : (((float)i - (float)d / 2.) / (float)d); } void rolloff_correction(float os, float width, float beta, const long dimensions[3], complex float* dst) { #pragma omp parallel for collapse(3) for (int z = 0; z < dimensions[2]; z++) for (int y = 0; y < dimensions[1]; y++) for (int x = 0; x < dimensions[0]; x++) dst[x + dimensions[0] * (y + z * dimensions[1])] = rolloff(os * pos(dimensions[0], x), beta, width) * rolloff(os * pos(dimensions[1], y), beta, width) * rolloff(os * pos(dimensions[2], z), beta, width); }
GB_bitmap_masker_template.c
//------------------------------------------------------------------------------ // GB_bitmap_masker_template: phase2 for R = masker (C, M, Z), R is bitmap //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Computes C<M>=Z or C<!M>=Z, returning the result in R, which is bitmap. // The input matrix C is not modified. Effectively, this computes R=C and then // R<M>=Z or R<!M>=Z. If the C_replace descriptor is enabled, then C has // already been cleared, and is an empty (but non-NULL) matrix. // phase2: computes R in a single pass // C is sparse or hypersparse. Z is bitmap or full. R is bitmap. // M has any sparsity structure. // ------------------------------------------ // C <!M> = Z R // ------------------------------------------ // sparse sparse bitmap bitmap // sparse sparse full bitmap // sparse bitmap bitmap bitmap // sparse bitmap full bitmap // sparse full bitmap bitmap // sparse full full bitmap // ------------------------------------------ // C <M> = Z R // ------------------------------------------ // sparse bitmap bitmap bitmap // sparse bitmap full bitmap // sparse full bitmap bitmap // sparse full full bitmap // FUTURE:: add special cases for C==Z, C==M, and Z==M aliases { int64_t p, rnvals = 0 ; ASSERT (R_sparsity == GxB_BITMAP) ; ASSERT (C_is_sparse || C_is_hyper) ; ASSERT (Z_is_bitmap || Z_is_full) ; //-------------------------------------------------------------------------- // scatter C into the R bitmap //-------------------------------------------------------------------------- ASSERT_MATRIX_OK (C, "C input to R_bitmap_masker", GB0) ; GB_SLICE_MATRIX (C, 8) ; #pragma omp parallel for num_threads(C_nthreads) schedule(dynamic,1) \ reduction(+:rnvals) for (taskid = 0 ; taskid < C_ntasks ; taskid++) { int64_t kfirst = kfirst_Cslice [taskid] ; int64_t klast = klast_Cslice [taskid] ; for (int64_t k = kfirst ; k <= klast ; k++) { // find the part of C(:,k) for this task int64_t j = GBH (Ch, k) ; int64_t pC_start, pC_end ; GB_get_pA (&pC_start, &pC_end, taskid, k, kfirst, klast, pstart_Cslice, Cp, vlen) ; int64_t pR_start = j * vlen ; // traverse over C(:,j), the kth vector of C for (int64_t pC = pC_start ; pC < pC_end ; pC++) { // R(i,j) = C(i,j) int64_t i = Ci [pC] ; int64_t pR = pR_start + i ; Rb [pR] = 1 ; rnvals++ ; memcpy (Rx + (pR)*rsize, Cx +(pC)*rsize, rsize) ; } } } R->nvals = rnvals ; ASSERT_MATRIX_OK (R, "R with C scattered", GB0) ; //-------------------------------------------------------------------------- // R<M>=Z or R<!M>=Z //-------------------------------------------------------------------------- if (M_is_sparse || M_is_hyper) { //---------------------------------------------------------------------- // Method05: M is sparse or hypersparse, Z bitmap/full, R bitmap //---------------------------------------------------------------------- // ------------------------------------------ // C <!M> = Z R // ------------------------------------------ // sparse sparse bitmap bitmap // sparse sparse full bitmap ASSERT (Mask_comp) ; //---------------------------------------------------------------------- // scatter M into the R bitmap //---------------------------------------------------------------------- GB_SLICE_MATRIX (M, 8) ; #pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < M_ntasks ; taskid++) { int64_t kfirst = kfirst_Mslice [taskid] ; int64_t klast = klast_Mslice [taskid] ; for (int64_t k = kfirst ; k <= klast ; k++) { // find the part of M(:,k) for this task int64_t j = GBH (Mh, k) ; int64_t pM_start, pM_end ; GB_get_pA (&pM_start, &pM_end, taskid, k, kfirst, klast, pstart_Mslice, Mp, vlen) ; int64_t pR_start = j * vlen ; // traverse over M(:,j), the kth vector of M for (int64_t pM = pM_start ; pM < pM_end ; pM++) { // mark R(i,j) if M(i,j) is true bool mij = GB_mcast (Mx, pM, msize) ; if (mij) { int64_t i = Mi [pM] ; int64_t p = pR_start + i ; Rb [p] += 2 ; } } } } //---------------------------------------------------------------------- // R<!M>=Z, using M scattered into R //---------------------------------------------------------------------- // Rb is marked as follows: // 0: R(i,j) is not present, and M(i,j) is false // 1: R(i,j) is present, and M(i,j) is false // 2: R(i,j) is not present, and M(i,j) is true // 3: R(i,j) is present, and M(i,j) is true // M is complemented, but shown uncomplemented in the table below since // that is how it is scattered into R. // Rb R(i,j) M(i,j) Z(i,j) modification to R(i,j) // 0 - 0 zij R(i,j) = Z(i,j), new value, rnvals++ // 0 - 0 - do nothing // 1 rij 0 zij R(i,j) = Z(i,j), overwrite // 1 rij 0 - delete R(i,j), rnvals-- // 2 - 1 zij do nothing, set Rb to 0 // 2 - 1 - do nothing, set Rb to 0 // 3 rij 1 zij keep R(i,j), set Rb to 1 // 3 rij 1 - keep R(i,j), set Rb to 1 #pragma omp parallel for num_threads(R_nthreads) schedule(static) \ reduction(+:rnvals) for (p = 0 ; p < rnz ; p++) { int8_t r = Rb [p] ; int8_t z = GBB (Zb, p) ; switch (r) { case 0 : // R(i,j) not present, M(i,j) false if (z) { // R(i,j) = Z(i,j), insert new value memcpy (Rx +(p)*rsize, Zx +(p)*rsize, rsize) ; Rb [p] = 1 ; rnvals++ ; } break ; case 1 : // R(i,j) present, M(i,j) false if (z) { // R(i,j) = Z(i,j), update prior value memcpy (Rx +(p)*rsize, Zx +(p)*rsize, rsize) ; } else { // delete R(i,j) Rb [p] = 0 ; rnvals-- ; } break ; case 2 : // R(i,j) not present, M(i,j) true Rb [p] = 0 ; break ; case 3 : // R(i,j) present, M(i,j) true Rb [p] = 1 ; break ; default: ; } } } else { //---------------------------------------------------------------------- // Method06: M and Z are bitmap or full, R is bitmap //---------------------------------------------------------------------- // ------------------------------------------ // C <!M> = Z R // ------------------------------------------ // sparse bitmap bitmap bitmap // sparse bitmap full bitmap // sparse full bitmap bitmap // sparse full full bitmap // ------------------------------------------ // C <M> = Z R // ------------------------------------------ // sparse bitmap bitmap bitmap // sparse bitmap full bitmap // sparse full bitmap bitmap // sparse full full bitmap // Rb R(i,j) M(i,j) Z(i,j) modification to R(i,j) // 0 - 0 zij do nothing // 0 - 0 - do nothing // 1 rij 0 zij do nothing // 1 rij 0 - do nothing // 0 - 1 zij R(i,j) = Z(i,j), rnvals++ // 0 - 1 - do nothing // 1 rij 1 zij R(i,j) = Z(i,j), no change to rnvals // 1 rij 1 - delete, rnvals-- #pragma omp parallel for num_threads(R_nthreads) schedule(static) \ reduction(+:rnvals) for (p = 0 ; p < rnz ; p++) { bool mij = GBB (Mb, p) && GB_mcast (Mx, p, msize) ; if (Mask_comp) mij = !mij ; if (mij) { int8_t z = GBB (Zb, p) ; int8_t r = Rb [p] ; if (r) { if (z) { // R(i,j) = Z(i,j), update, no change to rnvals memcpy (Rx +(p)*rsize, Zx +(p)*rsize, rsize) ; } else { // delete R(i,j) Rb [p] = 0 ; rnvals-- ; } } else if (z) { // R(i,j) = Z(i,j), new entry memcpy (Rx +(p)*rsize, Zx +(p)*rsize, rsize) ; Rb [p] = 1 ; rnvals++ ; } } } } R->nvals = rnvals ; }
cancel-1.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void f1 (void) { #pragma omp cancel parallel /* { dg-error "orphaned" } */ #pragma omp cancel for /* { dg-error "orphaned" } */ #pragma omp cancel sections /* { dg-error "orphaned" } */ #pragma omp cancel taskgroup /* { dg-error "orphaned" } */ #pragma omp cancellation point parallel /* { dg-error "orphaned" } */ #pragma omp cancellation point for /* { dg-error "orphaned" } */ #pragma omp cancellation point sections /* { dg-error "orphaned" } */ #pragma omp cancellation point taskgroup /* { dg-error "orphaned" } */ } void f2 (void) { int i, j = 0; #pragma omp parallel { #pragma omp cancel parallel #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp master { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp single { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp critical { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp taskgroup { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp task { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } #pragma omp taskgroup #pragma omp task { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup } #pragma omp taskloop for (i = 0; i < 10; i++) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup #pragma omp task { #pragma omp cancellation point taskgroup #pragma omp cancel taskgroup } } #pragma omp taskloop nogroup for (i = 0; i < 10; i++) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup/* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp task { #pragma omp cancellation point taskgroup/* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp taskgroup { #pragma omp task { #pragma omp task { #pragma omp cancellation point taskgroup #pragma omp cancel taskgroup } } #pragma omp taskloop nogroup for (i = 0; i < 10; i++) { #pragma omp task { #pragma omp cancellation point taskgroup #pragma omp cancel taskgroup } #pragma omp cancellation point taskgroup #pragma omp cancel taskgroup } } #pragma omp taskgroup { #pragma omp parallel { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } #pragma omp taskloop for (i = 0; i < 10; i++) { #pragma omp cancel taskgroup #pragma omp cancellation point taskgroup } #pragma omp taskloop nogroup for (i = 0; i < 10; i++) { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target #pragma omp teams #pragma omp distribute for (i = 0; i < 10; i++) { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target data map(i) { #pragma omp task { #pragma omp cancel taskgroup #pragma omp cancellation point taskgroup } } } #pragma omp taskloop for (i = 0; i < 10; i++) { #pragma omp parallel { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target #pragma omp teams #pragma omp distribute for (j = 0; j < 10; j++) { #pragma omp task { #pragma omp cancel taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ #pragma omp cancellation point taskgroup /* { dg-error "construct not closely nested inside of .taskgroup. region" } */ } } #pragma omp target data map(i) { #pragma omp task { #pragma omp cancel taskgroup #pragma omp cancellation point taskgroup } } } #pragma omp for for (i = 0; i < 10; i++) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } #pragma omp for ordered for (i = 0; i < 10; i++) #pragma omp ordered { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } #pragma omp sections { { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } #pragma omp section { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } } #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } } #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp target teams { #pragma omp cancel parallel /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancel for /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancel sections /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancel taskgroup /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancellation point parallel /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancellation point for /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancellation point sections /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ #pragma omp cancellation point taskgroup /* { dg-error "only .distribute., .parallel. or .loop. regions are allowed to be strictly nested" } */ } #pragma omp target teams distribute for (i = 0; i < 10; i++) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp for for (i = 0; i < 10; i++) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp for for (i = 0; i < 10; i++) #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp for for (i = 0; i < 10; i++) #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp for ordered for (i = 0; i < 10; i++) #pragma omp ordered #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } #pragma omp for ordered for (i = 0; i < 10; i++) #pragma omp ordered #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup/* { dg-error "not closely nested inside" } */ } #pragma omp sections { { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp section { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } } #pragma omp sections { #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp section #pragma omp target data map(j) { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } } #pragma omp sections { #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } #pragma omp section #pragma omp target { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } } #pragma omp task { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup #pragma omp taskgroup { #pragma omp cancel parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancel for /* { dg-error "not closely nested inside" } */ #pragma omp cancel sections /* { dg-error "not closely nested inside" } */ #pragma omp cancel taskgroup /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point parallel /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point for /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point sections /* { dg-error "not closely nested inside" } */ #pragma omp cancellation point taskgroup /* { dg-error "not closely nested inside" } */ } } } void f3 (void) { int i; #pragma omp for nowait for (i = 0; i < 10; i++) { #pragma omp cancel for /* { dg-warning "nowait" } */ } #pragma omp sections nowait { { #pragma omp cancel sections /* { dg-warning "nowait" } */ } #pragma omp section { #pragma omp cancel sections /* { dg-warning "nowait" } */ } } #pragma omp for ordered for (i = 0; i < 10; i++) { #pragma omp cancel for /* { dg-warning "ordered" } */ #pragma omp ordered { } } } #pragma omp cancellation point /* { dg-error "expected declaration specifiers before end of line" } */ void f4 (void) { if (0) #pragma omp cancellation EKAHI /* { dg-error "expected .point. before .EKAHI." } */ ; #pragma omp cancellation HO OKAHI /* { dg-error "expected .point. before .HO." } */ if (0) #pragma omp cancellation point /* { dg-error ".pragma omp cancellation point. may only be used in compound statements" } */ ; #pragma omp cancellation point /* { dg-error ".pragma omp cancellation point. must specify one of" } */ }
pentagon.h
// This code is modified from AutoMine and GraphZero // Daniel Mawhirter and Bo Wu. SOSP 2019. // AutoMine: Harmonizing High-Level Abstraction and High Performance for Graph Mining #pragma omp parallel for schedule(dynamic,1) reduction(+:counter) for(vidType v0 = 0; v0 < g.V(); v0++) { for (auto v1 : g.N(v0)) { if (v1 >= v0) break; auto y1 = g.N(v1); for (auto v2 : g.N(v0)) { if (v2 >= v1) break; for (auto v3 : g.N(v2)) { if (v3 >= v0) break; if (v3 == v1) continue; auto y3 = g.N(v3); counter += intersection_num_bound_except(y1, y3, v0, v2); } } } }