source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_binop__ge_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__ge_int8) // A.*B function (eWiseMult): GB (_AemultB_01__ge_int8) // A.*B function (eWiseMult): GB (_AemultB_02__ge_int8) // A.*B function (eWiseMult): GB (_AemultB_03__ge_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_int8) // A*D function (colscale): GB (_AxD__ge_int8) // D*A function (rowscale): GB (_DxB__ge_int8) // C+=B function (dense accum): GB (_Cdense_accumB__ge_int8) // C+=b function (dense accum): GB (_Cdense_accumb__ge_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_int8) // C=scalar+B GB (_bind1st__ge_int8) // C=scalar+B' GB (_bind1st_tran__ge_int8) // C=A+scalar GB (_bind2nd__ge_int8) // C=A'+scalar GB (_bind2nd_tran__ge_int8) // C type: bool // 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 \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ 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) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GE || GxB_NO_INT8 || GxB_NO_GE_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__ge_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__ge_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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ge_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__ge_int8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ge_int8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ge_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__ge_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__ge_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__ge_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__ge_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__ge_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 bool *Cx = (bool *) 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__ge_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 ; bool *Cx = (bool *) 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__ge_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__ge_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
dbscan_vp.h
#ifndef DBSCAN_VP_H #define DBSCAN_VP_H #include "vptree.h" #include <Eigen/Dense> namespace clustering { class DBSCAN_VP : private boost::noncopyable { private: static inline double dist( const Eigen::VectorXf& p1, const Eigen::VectorXf& p2 ) { return ( p1 - p2 ).norm(); } const Dataset::Ptr m_dset; public: typedef VPTREE< Eigen::VectorXf, dist > TVpTree; typedef std::vector< int32_t > Labels; typedef boost::shared_ptr< DBSCAN_VP > Ptr; DBSCAN_VP( const Dataset::Ptr dset ) : m_dset( dset ) , m_fit_time( .0 ) , m_predict_time( .0 ) { } ~DBSCAN_VP() { } TVpTree::Ptr get_vp() const { return m_vp_tree; } void fit() { const Dataset::DataContainer& d = m_dset->data(); const double start = omp_get_wtime(); m_vp_tree = boost::make_shared< TVpTree >(); m_vp_tree->create( m_dset ); const size_t dlen = d.size(); prepare_labels( dlen ); m_fit_time = omp_get_wtime() - start; } const std::vector< double > predict_eps( size_t k ) { const Dataset::DataContainer& d = m_dset->data(); std::vector< double > r( d.size(), 0.0 ); omp_set_dynamic( 1 ); #pragma omp parallel for for ( size_t i = 0; i < d.size(); ++i ) { TVpTree::TNeighborsList nlist; m_vp_tree->search_by_k( d[i], k, nlist, true ); if ( nlist.size() >= k ) { r[i] = nlist[0].second; } } std::sort( r.begin(), r.end() ); return std::move( r ); } uint32_t predict( double eps, size_t min_elems ) { std::unique_ptr< std::vector< uint32_t > > candidates( new std::vector< uint32_t >() ); std::unique_ptr< std::vector< uint32_t > > new_candidates( new std::vector< uint32_t >() ); int32_t cluster_id = 0; TVpTree::TNeighborsList index_neigh; TVpTree::TNeighborsList n_neigh; const double start = omp_get_wtime(); const Dataset::DataContainer& d = m_dset->data(); const size_t dlen = d.size(); for ( uint32_t pid = 0; pid < dlen; ++pid ) { if ( pid % 10000 == 0 ) VLOG( 1 ) << "progress: pid = " << pid << " " << ( float( pid ) / float( dlen ) ) * 100 << "%"; if ( m_labels[pid] >= 0 ) continue; find_neighbors( d, eps, pid, index_neigh ); // VLOG( 1 ) << "Analyzing pid " << pid << " Neigh size " << index_neigh.size(); if ( index_neigh.size() < min_elems ) continue; m_labels[pid] = cluster_id; //VLOG( 1 ) << "pid = " << pid << " neig = " << index_neigh.size(); candidates->clear(); for ( const auto& nn : index_neigh ) { if ( m_labels[nn.first] >= 0 ) continue; m_labels[nn.first] = cluster_id; // find_neighbors( d, eps, nn.first, n_neigh ); // VLOG( 1 ) << "nn.first = " << nn.first << " neig = " << n_neigh.size(); // if ( n_neigh.size() >= min_elems ) { candidates->push_back( nn.first ); // } } while ( candidates->size() > 0 ) { // std::cout << "\tcandidates = " << candidates.size() << std::endl; VLOG( 1 ) << "candidates size " << candidates->size(); new_candidates->clear(); const float csize = float( candidates->size() ); #pragma omp parallel for ordered schedule( dynamic ) for ( size_t j = 0; j < candidates->size(); ++j ) { // for ( const auto& c_pid : *candidates ) { TVpTree::TNeighborsList c_neigh; const uint32_t c_pid = candidates->at( j ); // VLOG( 1 ) << "c_pid = " << c_pid << " " << m_labels[c_pid]; // if ( m_labels[c_pid] >= 0 && m_labels[c_pid] != cluster_id ) // continue; find_neighbors( d, eps, c_pid, c_neigh ); if ( c_neigh.size() < min_elems ) continue; // VLOG( 1 ) << "c_pid = " << c_pid << " neig = " << c_neigh.size(); #pragma omp ordered { for ( const auto& nn : c_neigh ) { if ( m_labels[nn.first] >= 0 ) continue; m_labels[nn.first] = cluster_id; // find_neighbors( d, eps, nn.first, n_neigh ); // VLOG( 1 ) << "nn.first = " << nn.first << " neig = " << n_neigh.size(); // if ( n_neigh.size() >= min_elems ) { new_candidates->push_back( nn.first ); } if ( j % 1000 == 0 ) VLOG( 1 ) << "sub progress: j = " << j << " " << ( float( j ) / csize ) * 100 << "% " << new_candidates->size(); } // } } VLOG( 1 ) << "new candidates = " << new_candidates->size(); std::swap( candidates, new_candidates ); } ++cluster_id; } m_predict_time = omp_get_wtime() - start; return cluster_id; } void reset() { m_vp_tree.reset(); m_labels.clear(); } const Labels& get_labels() const { return m_labels; } const double get_fit_time() const { return m_fit_time; } const double get_predict_time() const { return m_predict_time; } private: void find_neighbors( const Dataset::DataContainer& d, double eps, uint32_t pid, TVpTree::TNeighborsList& neighbors ) { neighbors.clear(); m_vp_tree->search_by_dist( d[pid], eps, neighbors ); } Labels m_labels; void prepare_labels( size_t s ) { m_labels.resize( s ); for ( auto& l : m_labels ) { l = -1; } } TVpTree::Ptr m_vp_tree; double m_fit_time; double m_predict_time; }; // std::ostream& operator<<( std::ostream& o, DBSCAN& d ); } #endif // DBSCAN_VP_H
strtri.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/compute/ztrtri.c, normal z -> s, Fri Sep 28 17:38:03 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_trtri * * Computes the inverse of an upper or lower triangular matrix A. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] diag * - PlasmaNonUnit: A is non-unit triangular; * - PlasmaUnit: A is unit triangular. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] pA * On entry, the triangular matrix A. If uplo = 'U', the * leading n-by-n 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 = * 'L', the leading n-by-n 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 = * 'U', the diagonal elements of A are also not referenced and * are assumed to be 1. On exit, the (triangular) inverse of * the original matrix, in the same storage format. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * ******************************************************************************* * * @retval PlasmaSuccess successful exit. * @retval < 0 if -i, the i-th argument had an illegal value. * @retval > 0 if i, A(i,i) is exactly zero. The triangular * matrix is singular and its inverse can not be computed. * ******************************************************************************* * * @sa plasma_ctrtri * @sa plasma_dtrtri * @sa plasma_strtri * ******************************************************************************/ int plasma_strtri(plasma_enum_t uplo, plasma_enum_t diag, int n, float *pA, int lda) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (uplo != PlasmaUpper && uplo != PlasmaLower) { plasma_error("illegal value of uplo"); return -1; } if (diag != PlasmaUnit && diag != PlasmaNonUnit) { plasma_error("illegal value of diag"); return -2; } if (n < 0) { plasma_error("illegal value of n"); return -3; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -5; } // quick return if (imax(n, 0) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_trtri(plasma, PlasmaRealFloat, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrix. plasma_desc_t A; int retval; retval = plasma_desc_general_create(PlasmaRealFloat, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_sge2desc(pA, lda, A, &sequence, &request); // Call the tile async function. plasma_omp_strtri(uplo, diag, A, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_sdesc2ge(A, pA, lda, &sequence, &request); } // implicit synchronization // Free matrix A in tile layout. plasma_desc_destroy(&A); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_trtri * * Computes the inverse of a complex upper or lower triangular matrix A. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] diag * - PlasmaNonUnit: A is non-unit triangular; * - PlasmaUnit: A is unit triangular. * * @param[in] A * On entry, the triangular matrix A. If uplo = 'U', the * leading n-by-n 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 = * 'L', the leading n-by-n 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 = * 'U', the diagonal elements of A are also not referenced and * are assumed to be 1. On exit, the (triangular) inverse of * the original matrix, in the same storage format. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_strtri * @sa plasma_omp_strtri * @sa plasma_omp_ctrtri * @sa plasma_omp_dtrtri * @sa plasma_omp_strtri * ******************************************************************************/ void plasma_omp_strtri(plasma_enum_t uplo, plasma_enum_t diag, plasma_desc_t A, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((diag != PlasmaUnit) && (diag != PlasmaNonUnit)) { plasma_error("illegal value of diag"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (A.n == 0) return; // Call the parallel function. plasma_pstrtri(uplo, diag, A, sequence, request); }
gauss_seidel_omp.c
#include<stdio.h> #include<math.h> #include<omp.h> //added this # include <time.h> #include <sys/types.h> #include <sys/time.h> #define ESP 0.0001 double gettime(void) { struct timeval tval; gettimeofday(&tval, NULL); return( (double)tval.tv_sec + (double)tval.tv_usec/1000000.0 ); } int main(int argc, char **argv){ double a[3][3]; double x[3], x_old[3]; double c[] = {1, 28, 76}; int i, j, k, iter, N, M; double sum[3]; int maxiter = 6; double Ea[3], EaMax; double wtime1, wtime2; int flag =0; N=3; M=3; //initial guess for x[] x[0] = 1.00; x[1] = 0.00; x[2] = 1.00; x_old[0] = 1.00; x_old[1] = 0.00; x_old[2] = 1.00; a[0][0] = 12.00; a[0][1] = 3.00; a[0][2] = -5.00; a[1][0] = 1.00; a[1][1] = 5.00; a[1][2] = 3.00; a[2][0] = 3.00; a[2][1] = 7.00; a[2][2] = 13.00; for(i=0; i<M;i++){ for(j=0; j<N;j++){ printf(" %lf ", a[i][j]); } printf("\n"); } wtime1 = gettime(); omp_set_num_threads(N); for(iter = 1; iter <= maxiter; iter++){ EaMax =0.0; flag = 0; #pragma omp parallel for shared (a, x_old, N, M, sum, Ea ) private ( i, j ) for(i=0; i<N; i++){ sum[i] = 0.0; for(j=(i+1); j<M; j++){ sum[i] = a[i][j] * x[j] + sum[i]; } if (i == 0){ x[i] = (c[i] - sum[i])/a[i][i]; #pragma omp atomic update flag++; Ea[i] = fabs((x[i] - x_old [i])/x[i]) * 100; x_old[i] = x[i]; }else if (i > 0){ #pragma omp flush(flag) while(flag < i) { #pragma omp flush(flag) } for(j=0; j<i; j++){ sum[i] = sum[i] + a[i][j]*x[j]; } x[i] = (c[i] - sum[i])/a[i][i]; #pragma omp atomic update flag++; Ea[i] = fabs((x[i] - x_old [i])/x[i]) * 100; x_old[i] = x[i]; } } for(i = 0; i < N; i++){ if(Ea[i] > EaMax){ EaMax = Ea[i]; } printf("\nIn iteration number: %d, thread_is: %d, X[%d]: %lf, X_old[%d]: %lf, Error: %lf, EaMax: %lf, Sum: %lf\n", iter, omp_get_thread_num(), i,x[i], i, x_old[i], Ea[i],EaMax, sum[i] ); } printf("\nEaMax: %lf\n", EaMax); if(EaMax < ESP){ break; } } wtime2 = gettime(); printf ( "Elapsed wall clock time (seconds) %f\n", (wtime2 - wtime1) ); return 0; }
test-float-libmvec-sincosf-main.c
/* Test for vector sincosf ABI. Copyright (C) 2016-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <math.h> #define N 1000 float x[N], s[N], c[N]; float *s_ptrs[N]; float *c_ptrs[N]; int test_sincosf_abi (void) { int i; for(i = 0; i < N; i++) { x[i] = i / 3; s_ptrs[i] = &s[i]; c_ptrs[i] = &c[i]; } #pragma omp simd for(i = 0; i < N; i++) sincosf (x[i], s_ptrs[i], c_ptrs[i]); return 0; }
nvector_openmp.c
/* ----------------------------------------------------------------- * Programmer(s): David J. Gardner and Carol S. Woodward @ LLNL * ----------------------------------------------------------------- * Acknowledgements: This NVECTOR module is based on the NVECTOR * Serial module by Scott D. Cohen, Alan C. * Hindmarsh, Radu Serban, and Aaron Collier * @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2022, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * This is the implementation file for an OpenMP implementation * of the NVECTOR module. * -----------------------------------------------------------------*/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_math.h> #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define ONEPT5 RCONST(1.5) /* Private functions for special cases of vector operations */ static void VCopy_OpenMP(N_Vector x, N_Vector z); /* z=x */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x+y */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */ static void VNeg_OpenMP(N_Vector x, N_Vector z); /* z=-x */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x+y) */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y); /* y <- ax+y */ static void VScaleBy_OpenMP(realtype a, N_Vector x); /* x <- ax */ /* Private functions for special cases of vector array operations */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X+Y */ static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X-Y */ static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X+Y) */ static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X-Y) */ static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX+Y */ static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX-Y */ static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y); /* Y <- aX+Y */ /* * ----------------------------------------------------------------- * exported functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------- * Returns vector type ID. Used to identify vector implementation * from abstract N_Vector interface. */ N_Vector_ID N_VGetVectorID_OpenMP(N_Vector v) { return SUNDIALS_NVEC_OPENMP; } /* ---------------------------------------------------------------------------- * Function to create a new empty vector */ N_Vector N_VNewEmpty_OpenMP(sunindextype length, int num_threads, SUNContext sunctx) { N_Vector v; N_VectorContent_OpenMP content; /* Create vector */ v = NULL; v = N_VNewEmpty(sunctx); if (v == NULL) return(NULL); /* Attach operations */ /* constructors, destructors, and utility operations */ v->ops->nvgetvectorid = N_VGetVectorID_OpenMP; v->ops->nvclone = N_VClone_OpenMP; v->ops->nvcloneempty = N_VCloneEmpty_OpenMP; v->ops->nvdestroy = N_VDestroy_OpenMP; v->ops->nvspace = N_VSpace_OpenMP; v->ops->nvgetarraypointer = N_VGetArrayPointer_OpenMP; v->ops->nvsetarraypointer = N_VSetArrayPointer_OpenMP; v->ops->nvgetlength = N_VGetLength_OpenMP; /* standard vector operations */ v->ops->nvlinearsum = N_VLinearSum_OpenMP; v->ops->nvconst = N_VConst_OpenMP; v->ops->nvprod = N_VProd_OpenMP; v->ops->nvdiv = N_VDiv_OpenMP; v->ops->nvscale = N_VScale_OpenMP; v->ops->nvabs = N_VAbs_OpenMP; v->ops->nvinv = N_VInv_OpenMP; v->ops->nvaddconst = N_VAddConst_OpenMP; v->ops->nvdotprod = N_VDotProd_OpenMP; v->ops->nvmaxnorm = N_VMaxNorm_OpenMP; v->ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMP; v->ops->nvwrmsnorm = N_VWrmsNorm_OpenMP; v->ops->nvmin = N_VMin_OpenMP; v->ops->nvwl2norm = N_VWL2Norm_OpenMP; v->ops->nvl1norm = N_VL1Norm_OpenMP; v->ops->nvcompare = N_VCompare_OpenMP; v->ops->nvinvtest = N_VInvTest_OpenMP; v->ops->nvconstrmask = N_VConstrMask_OpenMP; v->ops->nvminquotient = N_VMinQuotient_OpenMP; /* fused and vector array operations are disabled (NULL) by default */ /* local reduction kernels */ v->ops->nvdotprodlocal = N_VDotProd_OpenMP; v->ops->nvmaxnormlocal = N_VMaxNorm_OpenMP; v->ops->nvminlocal = N_VMin_OpenMP; v->ops->nvl1normlocal = N_VL1Norm_OpenMP; v->ops->nvinvtestlocal = N_VInvTest_OpenMP; v->ops->nvconstrmasklocal = N_VConstrMask_OpenMP; v->ops->nvminquotientlocal = N_VMinQuotient_OpenMP; v->ops->nvwsqrsumlocal = N_VWSqrSumLocal_OpenMP; v->ops->nvwsqrsummasklocal = N_VWSqrSumMaskLocal_OpenMP; /* single buffer reduction operations */ v->ops->nvdotprodmultilocal = N_VDotProdMulti_OpenMP; /* XBraid interface operations */ v->ops->nvbufsize = N_VBufSize_OpenMP; v->ops->nvbufpack = N_VBufPack_OpenMP; v->ops->nvbufunpack = N_VBufUnpack_OpenMP; /* debugging functions */ v->ops->nvprint = N_VPrint_OpenMP; v->ops->nvprintfile = N_VPrintFile_OpenMP; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof *content); if (content == NULL) { N_VDestroy(v); return(NULL); } /* Attach content */ v->content = content; /* Initialize content */ content->length = length; content->num_threads = num_threads; content->own_data = SUNFALSE; content->data = NULL; return(v); } /* ---------------------------------------------------------------------------- * Function to create a new vector */ N_Vector N_VNew_OpenMP(sunindextype length, int num_threads, SUNContext sunctx) { N_Vector v; realtype *data; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads, sunctx); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create a vector with user data component */ N_Vector N_VMake_OpenMP(sunindextype length, realtype *v_data, int num_threads, SUNContext sunctx) { N_Vector v; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads, sunctx); if (v == NULL) return(NULL); if (length > 0) { /* Attach data */ NV_OWN_DATA_OMP(v) = SUNFALSE; NV_DATA_OMP(v) = v_data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors. */ N_Vector* N_VCloneVectorArray_OpenMP(int count, N_Vector w) { return(N_VCloneVectorArray(count, w)); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors with NULL data array. */ N_Vector* N_VCloneVectorArrayEmpty_OpenMP(int count, N_Vector w) { return(N_VCloneEmptyVectorArray(count, w)); } /* ---------------------------------------------------------------------------- * Function to free an array created with N_VCloneVectorArray_OpenMP */ void N_VDestroyVectorArray_OpenMP(N_Vector* vs, int count) { N_VDestroyVectorArray(vs, count); return; } /* ---------------------------------------------------------------------------- * Function to return number of vector elements */ sunindextype N_VGetLength_OpenMP(N_Vector v) { return NV_LENGTH_OMP(v); } /* ---------------------------------------------------------------------------- * Function to print a vector to stdout */ void N_VPrint_OpenMP(N_Vector x) { N_VPrintFile_OpenMP(x, stdout); } /* ---------------------------------------------------------------------------- * Function to print a vector to outfile */ void N_VPrintFile_OpenMP(N_Vector x, FILE *outfile) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); for (i = 0; i < N; i++) { #if defined(SUNDIALS_EXTENDED_PRECISION) STAN_SUNDIALS_FPRINTF(outfile, "%11.8Lg\n", xd[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) STAN_SUNDIALS_FPRINTF(outfile, "%11.8g\n", xd[i]); #else STAN_SUNDIALS_FPRINTF(outfile, "%11.8g\n", xd[i]); #endif } STAN_SUNDIALS_FPRINTF(outfile, "\n"); return; } /* * ----------------------------------------------------------------- * implementation of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Create new vector from existing vector without attaching data */ N_Vector N_VCloneEmpty_OpenMP(N_Vector w) { N_Vector v; N_VectorContent_OpenMP content; if (w == NULL) return(NULL); /* Create vector */ v = NULL; v = N_VNewEmpty(w->sunctx); if (v == NULL) return(NULL); /* Attach operations */ if (N_VCopyOps(w, v)) { N_VDestroy(v); return(NULL); } /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof *content); if (content == NULL) { N_VDestroy(v); return(NULL); } /* Attach content */ v->content = content; /* Initialize content */ content->length = NV_LENGTH_OMP(w); content->num_threads = NV_NUM_THREADS_OMP(w); content->own_data = SUNFALSE; content->data = NULL; return(v); } /* ---------------------------------------------------------------------------- * Create new vector from existing vector and attach data */ N_Vector N_VClone_OpenMP(N_Vector w) { N_Vector v; realtype *data; sunindextype length; v = NULL; v = N_VCloneEmpty_OpenMP(w); if (v == NULL) return(NULL); length = NV_LENGTH_OMP(w); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Destroy vector and free vector memory */ void N_VDestroy_OpenMP(N_Vector v) { if (v == NULL) return; /* free content */ if (v->content != NULL) { /* free data array if it's owned by the vector */ if (NV_OWN_DATA_OMP(v) && NV_DATA_OMP(v) != NULL) { free(NV_DATA_OMP(v)); NV_DATA_OMP(v) = NULL; } free(v->content); v->content = NULL; } /* free ops and vector */ if (v->ops != NULL) { free(v->ops); v->ops = NULL; } free(v); v = NULL; return; } /* ---------------------------------------------------------------------------- * Get storage requirement for N_Vector */ void N_VSpace_OpenMP(N_Vector v, sunindextype *lrw, sunindextype *liw) { *lrw = NV_LENGTH_OMP(v); *liw = 1; return; } /* ---------------------------------------------------------------------------- * Get vector data pointer */ realtype *N_VGetArrayPointer_OpenMP(N_Vector v) { return((realtype *) NV_DATA_OMP(v)); } /* ---------------------------------------------------------------------------- * Set vector data pointer */ void N_VSetArrayPointer_OpenMP(realtype *v_data, N_Vector v) { if (NV_LENGTH_OMP(v) > 0) NV_DATA_OMP(v) = v_data; return; } /* ---------------------------------------------------------------------------- * Compute linear combination z[i] = a*x[i]+b*y[i] */ void N_VLinearSum_OpenMP(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { sunindextype i, N; realtype c, *xd, *yd, *zd; N_Vector v1, v2; booleantype test; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */ Vaxpy_OpenMP(a,x,y); return; } if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */ Vaxpy_OpenMP(b,y,x); return; } /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) { VSum_OpenMP(x, y, z); return; } /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { v1 = test ? y : x; v2 = test ? x : y; VDiff_OpenMP(v2, v1, z); return; } /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin1_OpenMP(c, v1, v2, z); return; } /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin2_OpenMP(c, v1, v2, z); return; } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) { VScaleSum_OpenMP(a, x, y, z); return; } /* Case: a == -b */ if (a == -b) { VScaleDiff_OpenMP(a, x, y, z); return; } /* Do all cases not handled above: (1) a == other, b == 0.0 - user should have called N_VScale (2) a == 0.0, b == other - user should have called N_VScale (3) a,b == other, a !=b, a != -b */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,b,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+(b*yd[i]); return; } /* ---------------------------------------------------------------------------- * Assigns constant value to all vector elements, z[i] = c */ void N_VConst_OpenMP(realtype c, N_Vector z) { sunindextype i, N; realtype *zd; i = 0; /* initialize to suppress clang warning */ zd = NULL; N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(z)) for (i = 0; i < N; i++) zd[i] = c; return; } /* ---------------------------------------------------------------------------- * Compute componentwise product z[i] = x[i]*y[i] */ void N_VProd_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]*yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise division z[i] = x[i]/y[i] */ void N_VDiv_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]/yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaler multiplication z[i] = c*x[i] */ void N_VScale_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; if (z == x) { /* BLAS usage: scale x <- cx */ VScaleBy_OpenMP(c, x); return; } if (c == ONE) { VCopy_OpenMP(x, z); } else if (c == -ONE) { VNeg_OpenMP(x, z); } else { N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*xd[i]; } return; } /* ---------------------------------------------------------------------------- * Compute absolute value of vector components z[i] = SUNRabs(x[i]) */ void N_VAbs_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = SUNRabs(xd[i]); return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = 1 / x[i] */ void N_VInv_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = ONE/xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise addition of a scaler to a vector z[i] = x[i] + b */ void N_VAddConst_OpenMP(N_Vector x, realtype b, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,b,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+b; return; } /* ---------------------------------------------------------------------------- * Computes the dot product of two vectors, a = sum(x[i]*y[i]) */ realtype N_VDotProd_OpenMP(N_Vector x, N_Vector y) { sunindextype i, N; realtype sum, *xd, *yd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); #pragma omp parallel for default(none) private(i) shared(N,xd,yd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += xd[i]*yd[i]; } return(sum); } /* ---------------------------------------------------------------------------- * Computes max norm of a vector */ realtype N_VMaxNorm_OpenMP(N_Vector x) { sunindextype i, N; realtype tmax, max, *xd; i = 0; /* initialize to suppress clang warning */ max = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel default(none) private(i,tmax) shared(N,max,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmax = ZERO; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (SUNRabs(xd[i]) > tmax) tmax = SUNRabs(xd[i]); } #pragma omp critical { if (tmax > max) max = tmax; } } return(max); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a vector */ realtype N_VWrmsNorm_OpenMP(N_Vector x, N_Vector w) { return(SUNRsqrt(N_VWSqrSumLocal_OpenMP(x, w)/(NV_LENGTH_OMP(x)))); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a masked vector */ realtype N_VWrmsNormMask_OpenMP(N_Vector x, N_Vector w, N_Vector id) { return(SUNRsqrt(N_VWSqrSumMaskLocal_OpenMP(x, w, id)/(NV_LENGTH_OMP(x)))); } /* ---------------------------------------------------------------------------- * Finds the minimun component of a vector */ realtype N_VMin_OpenMP(N_Vector x) { sunindextype i, N; realtype min, *xd; realtype tmin; i = 0; /* initialize to suppress clang warning */ xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); min = xd[0]; #pragma omp parallel default(none) private(i,tmin) shared(N,min,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmin = xd[0]; #pragma omp for schedule(static) for (i = 1; i < N; i++) { if (xd[i] < tmin) tmin = xd[i]; } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted L2 norm of a vector */ realtype N_VWL2Norm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum)); } /* ---------------------------------------------------------------------------- * Computes L1 norm of a vector */ realtype N_VL1Norm_OpenMP(N_Vector x) { sunindextype i, N; realtype sum, *xd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,xd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i<N; i++) sum += SUNRabs(xd[i]); return(sum); } /* ---------------------------------------------------------------------------- * Compare vector component values to a scaler */ void N_VCompare_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { zd[i] = (SUNRabs(xd[i]) >= c) ? ONE : ZERO; } return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO */ booleantype N_VInvTest_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd, val; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); val = ZERO; #pragma omp parallel for default(none) private(i) shared(N,val,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (xd[i] == ZERO) val = ONE; else zd[i] = ONE/xd[i]; } if (val > ZERO) return (SUNFALSE); else return (SUNTRUE); } /* ---------------------------------------------------------------------------- * Compute constraint mask of a vector */ booleantype N_VConstrMask_OpenMP(N_Vector c, N_Vector x, N_Vector m) { sunindextype i, N; realtype temp; realtype *cd, *xd, *md; booleantype test; i = 0; /* initialize to suppress clang warning */ cd = xd = md = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); cd = NV_DATA_OMP(c); md = NV_DATA_OMP(m); temp = ZERO; #pragma omp parallel for default(none) private(i,test) shared(N,xd,cd,md,temp) \ schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { md[i] = ZERO; /* Continue if no constraints were set for the variable */ if (cd[i] == ZERO) continue; /* Check if a set constraint has been violated */ test = (SUNRabs(cd[i]) > ONEPT5 && xd[i]*cd[i] <= ZERO) || (SUNRabs(cd[i]) > HALF && xd[i]*cd[i] < ZERO); if (test) { temp = md[i] = ONE; /* Here is a race to write to temp */ } } /* Return false if any constraint was violated */ return (temp == ONE) ? SUNFALSE : SUNTRUE; } /* ---------------------------------------------------------------------------- * Compute minimum componentwise quotient */ realtype N_VMinQuotient_OpenMP(N_Vector num, N_Vector denom) { sunindextype i, N; realtype *nd, *dd, min, tmin, val; i = 0; /* initialize to suppress clang warning */ nd = dd = NULL; N = NV_LENGTH_OMP(num); nd = NV_DATA_OMP(num); dd = NV_DATA_OMP(denom); min = BIG_REAL; #pragma omp parallel default(none) private(i,tmin,val) shared(N,min,nd,dd) \ num_threads(NV_NUM_THREADS_OMP(num)) { tmin = BIG_REAL; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (dd[i] != ZERO) { val = nd[i]/dd[i]; if (val < tmin) tmin = val; } } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted square sum of a vector */ realtype N_VWSqrSumLocal_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(sum); } /* ---------------------------------------------------------------------------- * Computes weighted square sum of a masked vector */ realtype N_VWSqrSumMaskLocal_OpenMP(N_Vector x, N_Vector w, N_Vector id) { sunindextype i, N; realtype sum, *xd, *wd, *idd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = idd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); idd = NV_DATA_OMP(id); #pragma omp parallel for default(none) private(i) shared(N,xd,wd,idd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (idd[i] > ZERO) { sum += SUNSQR(xd[i]*wd[i]); } } return(sum); } /* * ----------------------------------------------------------------- * fused vector operations * ----------------------------------------------------------------- */ int N_VLinearCombination_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector z) { int i; sunindextype j, N; realtype* zd=NULL; realtype* xd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], z); return(0); } /* should have called N_VLinearSum */ if (nvec == 2) { N_VLinearSum_OpenMP(c[0], X[0], c[1], X[1], z); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); /* * X[0] += c[i]*X[i], i = 1,...,nvec-1 */ if ((X[0] == z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * X[0] = c[0] * X[0] + sum{ c[i] * X[i] }, i = 1,...,nvec-1 */ if (X[0] == z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] *= c[0]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * z = sum{ c[i] * X[i] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { xd = NV_DATA_OMP(X[0]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[0] * xd[j]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } int N_VScaleAddMulti_OpenMP(int nvec, realtype* a, N_Vector x, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a[0], x, ONE, Y[0], Z[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,yd) shared(nvec,Y,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { yd[j] += a[i] * xd[j]; } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,yd,zd) shared(nvec,Y,Z,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a[i] * xd[j] + yd[j]; } } } return(0); } int N_VDotProdMulti_OpenMP(int nvec, N_Vector x, N_Vector* Y, realtype* dotprods) { int i; sunindextype j, N; realtype sum; realtype* xd=NULL; realtype* yd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VDotProd */ if (nvec == 1) { dotprods[0] = N_VDotProd_OpenMP(x, Y[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* initialize dot products */ for (i=0; i<nvec; i++) { dotprods[i] = ZERO; } /* compute multiple dot products */ #pragma omp parallel default(none) private(i,j,yd,sum) shared(nvec,Y,N,xd,dotprods) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += xd[j] * yd[j]; } #pragma omp critical { dotprods[i] += sum; } } } return(0); } /* * ----------------------------------------------------------------- * vector array operations * ----------------------------------------------------------------- */ int N_VLinearSumVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, realtype b, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; realtype c; N_Vector* V1; N_Vector* V2; booleantype test; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a, X[0], b, Y[0], Z[0]); return(0); } /* BLAS usage: axpy y <- ax+y */ if ((b == ONE) && (Z == Y)) return(VaxpyVectorArray_OpenMP(nvec, a, X, Y)); /* BLAS usage: axpy x <- by+x */ if ((a == ONE) && (Z == X)) return(VaxpyVectorArray_OpenMP(nvec, b, Y, X)); /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) return(VSumVectorArray_OpenMP(nvec, X, Y, Z)); /* Cases: */ /* (1) a == 1.0, b = -1.0, */ /* (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { V1 = test ? Y : X; V2 = test ? X : Y; return(VDiffVectorArray_OpenMP(nvec, V2, V1, Z)); } /* Cases: */ /* (1) a == 1.0, b == other or 0.0, */ /* (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin1VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Cases: */ /* (1) a == -1.0, b != 1.0, */ /* (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin2VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) return(VScaleSumVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Case: a == -b */ if (a == -b) return(VScaleDiffVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Do all cases not handled above: */ /* (1) a == other, b == 0.0 - user should have called N_VScale */ /* (2) a == 0.0, b == other - user should have called N_VScale */ /* (3) a,b == other, a !=b, a != -b */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* compute linear sum for each vector pair in vector arrays */ #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a,b) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a * xd[j] + b * yd[j]; } } } return(0); } int N_VScaleVectorArray_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[i] *= c[i] */ if (X == Z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { xd[j] *= c[i]; } } } return(0); } /* * Z[i] = c[i] * X[i] */ #pragma omp parallel default(none) private(i,j,xd,zd) shared(nvec,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[i] * xd[j]; } } } return(0); } int N_VConstVectorArray_OpenMP(int nvec, realtype c, N_Vector* Z) { int i; sunindextype j, N; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VConst */ if (nvec == 1) { N_VConst_OpenMP(c, Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* set each vector in the vector array to a constant */ #pragma omp parallel default(none) private(i,j,zd) shared(nvec,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c; } } } return(0); } int N_VWrmsNormVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNorm_OpenMP(X[0], W[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VWrmsNormMaskVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, N_Vector id, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; realtype* idd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNormMask_OpenMP(X[0], W[0], id); return(0); } /* get vector length and mask data array */ N = NV_LENGTH_OMP(X[0]); idd = NV_DATA_OMP(id); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,idd,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { if (idd[j] > ZERO) sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VScaleAddMultiVectorArray_OpenMP(int nvec, int nsum, realtype* a, N_Vector* X, N_Vector** Y, N_Vector** Z) { int i, j; sunindextype k, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; int retval; N_Vector* YY; N_Vector* ZZ; i = 0; /* initialize to suppress clang warning */ k = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VLinearSum */ if (nsum == 1) { N_VLinearSum_OpenMP(a[0], X[0], ONE, Y[0][0], Z[0][0]); return(0); } /* should have called N_VScaleAddMulti */ YY = (N_Vector*) malloc(nsum * sizeof(N_Vector)); ZZ = (N_Vector*) malloc(nsum * sizeof(N_Vector)); for (j=0; j<nsum; j++) { YY[j] = Y[j][0]; ZZ[j] = Z[j][0]; } retval = N_VScaleAddMulti_OpenMP(nsum, a, X[0], YY, ZZ); free(YY); free(ZZ); return(retval); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VLinearSumVectorArray */ if (nsum == 1) { retval = N_VLinearSumVectorArray_OpenMP(nvec, a[0], X, ONE, Y[0], Z[0]); return(retval); } /* ---------------------------- * Compute multiple linear sums * ---------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,k,xd,yd) shared(nvec,nsum,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { yd[k] += a[j] * xd[k]; } } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,k,xd,yd,zd) shared(nvec,nsum,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); zd = NV_DATA_OMP(Z[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = a[j] * xd[k] + yd[k]; } } } } return(0); } int N_VLinearCombinationVectorArray_OpenMP(int nvec, int nsum, realtype* c, N_Vector** X, N_Vector* Z) { int i; /* vector arrays index in summation [0,nsum) */ int j; /* vector index in vector array [0,nvec) */ sunindextype k; /* element index in vector [0,N) */ sunindextype N; realtype* zd=NULL; realtype* xd=NULL; realtype* ctmp; N_Vector* Y; i = 0; /* initialize to suppress clang warning */ k = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VScale */ if (nsum == 1) { N_VScale_OpenMP(c[0], X[0][0], Z[0]); return(0); } /* should have called N_VLinearSum */ if (nsum == 2) { N_VLinearSum_OpenMP(c[0], X[0][0], c[1], X[1][0], Z[0]); return(0); } /* should have called N_VLinearCombination */ Y = (N_Vector*) malloc(nsum * sizeof(N_Vector)); for (i=0; i<nsum; i++) { Y[i] = X[i][0]; } N_VLinearCombination_OpenMP(nsum, c, Y, Z[0]); free(Y); return(0); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VScaleVectorArray */ if (nsum == 1) { ctmp = (realtype*) malloc(nvec * sizeof(realtype)); for (j=0; j<nvec; j++) { ctmp[j] = c[0]; } N_VScaleVectorArray_OpenMP(nvec, ctmp, X[0], Z); free(ctmp); return(0); } /* should have called N_VLinearSumVectorArray */ if (nsum == 2) { N_VLinearSumVectorArray_OpenMP(nvec, c[0], X[0], c[1], X[1], Z); return(0); } /* -------------------------- * Compute linear combination * -------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[0][j] += c[i]*X[i][j], i = 1,...,nvec-1 */ if ((X[0] == Z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * X[0][j] = c[0] * X[0][j] + sum{ c[i] * X[i][j] }, i = 1,...,nvec-1 */ if (X[0] == Z) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] *= c[0]; } for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * Z[j] = sum{ c[i] * X[i][j] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { /* scale first vector in the sum into the output vector */ xd = NV_DATA_OMP(X[0][j]); zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = c[0] * xd[k]; } /* scale and sum remaining vectors into the output vector */ for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * ----------------------------------------------------------------- * OPTIONAL XBraid interface operations * ----------------------------------------------------------------- */ int N_VBufSize_OpenMP(N_Vector x, sunindextype *size) { if (x == NULL) return(-1); *size = NV_LENGTH_OMP(x) * ((sunindextype)sizeof(realtype)); return(0); } int N_VBufPack_OpenMP(N_Vector x, void *buf) { sunindextype i, N; realtype *xd = NULL; realtype *bd = NULL; if (x == NULL || buf == NULL) return(-1); N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); bd = (realtype*) buf; #pragma omp for schedule(static) for (i = 0; i < N; i++) bd[i] = xd[i]; return(0); } int N_VBufUnpack_OpenMP(N_Vector x, void *buf) { sunindextype i, N; realtype *xd = NULL; realtype *bd = NULL; if (x == NULL || buf == NULL) return(-1); N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); bd = (realtype*) buf; #pragma omp for schedule(static) for (i = 0; i < N; i++) xd[i] = bd[i]; return(0); } /* * ----------------------------------------------------------------- * private functions for special cases of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Copy vector components into a second vector */ static void VCopy_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector sum */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute the negative of a vector */ static void VNeg_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = -xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector sum */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]+yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute scaled vector difference */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]-yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute vector sum z[i] = a*x[i]+y[i] */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference z[i] = a*x[i]-y[i] */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute special cases of linear sum */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y) { sunindextype i, N; realtype *xd, *yd; i = 0; /* initialize to suppress clang warning */ xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); if (a == ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += xd[i]; return; } if (a == -ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] -= xd[i]; return; } #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += a*xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector x[i] = a*x[i] */ static void VScaleBy_OpenMP(realtype a, N_Vector x) { sunindextype i, N; realtype *xd; i = 0; /* initialize to suppress clang warning */ xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,a,xd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) xd[i] *= a; return; } /* * ----------------------------------------------------------------- * private functions for special cases of vector array operations * ----------------------------------------------------------------- */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] + yd[j]; } } return(0); } static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] - yd[j]; } } return(0); } static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] + yd[j]); } } return(0); } static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] - yd[j]); } } return(0); } static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) + yd[j]; } } return(0); } static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) - yd[j]; } } return(0); } static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); if (a == ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += xd[j]; } } return(0); } if (a == -ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] -= xd[j]; } } return(0); } #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += a * xd[j]; } } return(0); } /* * ----------------------------------------------------------------- * Enable / Disable fused and vector array operations * ----------------------------------------------------------------- */ int N_VEnableFusedOps_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); if (tf) { /* enable all fused vector operations */ v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; /* enable all vector array operations */ v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; /* enable single buffer reduction operations */ v->ops->nvdotprodmultilocal = N_VDotProdMulti_OpenMP; } else { /* disable all fused vector operations */ v->ops->nvlinearcombination = NULL; v->ops->nvscaleaddmulti = NULL; v->ops->nvdotprodmulti = NULL; /* disable all vector array operations */ v->ops->nvlinearsumvectorarray = NULL; v->ops->nvscalevectorarray = NULL; v->ops->nvconstvectorarray = NULL; v->ops->nvwrmsnormvectorarray = NULL; v->ops->nvwrmsnormmaskvectorarray = NULL; v->ops->nvscaleaddmultivectorarray = NULL; v->ops->nvlinearcombinationvectorarray = NULL; /* disable single buffer reduction operations */ v->ops->nvdotprodmultilocal = NULL; } /* return success */ return(0); } int N_VEnableLinearCombination_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; else v->ops->nvlinearcombination = NULL; /* return success */ return(0); } int N_VEnableScaleAddMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; else v->ops->nvscaleaddmulti = NULL; /* return success */ return(0); } int N_VEnableDotProdMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) { v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; v->ops->nvdotprodmultilocal = N_VDotProdMulti_OpenMP; } else { v->ops->nvdotprodmulti = NULL; v->ops->nvdotprodmultilocal = NULL; } /* return success */ return(0); } int N_VEnableLinearSumVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; else v->ops->nvlinearsumvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; else v->ops->nvscalevectorarray = NULL; /* return success */ return(0); } int N_VEnableConstVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; else v->ops->nvconstvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; else v->ops->nvwrmsnormvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormMaskVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; else v->ops->nvwrmsnormmaskvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleAddMultiVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; else v->ops->nvscaleaddmultivectorarray = NULL; /* return success */ return(0); } int N_VEnableLinearCombinationVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; else v->ops->nvlinearcombinationvectorarray = NULL; /* return success */ return(0); }
CacheEfficientHogwildTrainer.h
/* * Copyright 2016 [See AUTHORS file for list of authors] * * 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 _CACHE_EFFICIENT_HOGWILD_TRAINER_ #define _CACHE_EFFICIENT_HOGWILD_TRAINER_ #include <map> #include "Partitioner/DFSCachePartitioner.h" #include "Partitioner/GreedyCachePartitioner.h" #include "Trainer/Trainer.h" DEFINE_bool(dfs_cache_partitioner, false, "For cache efficient hogwild trainer, use the DFS method to cache partition data points."); DEFINE_bool( greedy_cache_partitioner, false, "For cache efficient hogwild trainer, use an n^2 greedy algorithm to generate cache friendyl data point ordering."); class CacheEfficientHogwildTrainer : public Trainer { protected: void PrintStatsAboutProblem(const std::vector<Datapoint *> &datapoints) { int n_total_coordinate_accesses = 0; int n_distinct_model_accesses = 0; double avg_num_coordinates_accessed_per_datapoint = 0; int max_coordinates_accessed_per_datapoint = 0; int min_coordinates_accessed_per_datapoint = INT_MAX; std::map<int, bool> coordinates_set; for (int i = 0; i < datapoints.size(); i++) { n_total_coordinate_accesses += datapoints[i]->GetCoordinates().size(); for (const auto &coordinate : datapoints[i]->GetCoordinates()) { coordinates_set[coordinate] = 1; } max_coordinates_accessed_per_datapoint = fmax(max_coordinates_accessed_per_datapoint, datapoints[i]->GetCoordinates().size()); min_coordinates_accessed_per_datapoint = fmin(max_coordinates_accessed_per_datapoint, datapoints[i]->GetCoordinates().size()); } n_distinct_model_accesses = coordinates_set.size(); avg_num_coordinates_accessed_per_datapoint = n_total_coordinate_accesses / (double)datapoints.size(); printf( "n_datapoints=%d\n" "n_total_coordinate_accesses=%d\n" "n_distinct_model_acceses=%d\n" "avg_num_coordinates_accessed_per_datapoint=%lf\n" "max_coordinates_accessed=%d\n" "min_coordinates_accessed=%d\n", (int)datapoints.size(), n_total_coordinate_accesses, n_distinct_model_accesses, avg_num_coordinates_accessed_per_datapoint, max_coordinates_accessed_per_datapoint, min_coordinates_accessed_per_datapoint); } public: CacheEfficientHogwildTrainer() {} ~CacheEfficientHogwildTrainer() {} TrainStatistics Train(Model *model, const std::vector<Datapoint *> &datapoints, Updater *updater) override { // Print some stats. PrintStatsAboutProblem(datapoints); // Partition. Timer partition_timer; DatapointPartitions partitions(FLAGS_n_threads); if (FLAGS_dfs_cache_partitioner) { DFSCachePartitioner partitioner; partitions = partitioner.Partition(datapoints, FLAGS_n_threads); } else if (FLAGS_greedy_cache_partitioner) { GreedyCachePartitioner partitioner; partitions = partitioner.Partition(datapoints, FLAGS_n_threads); } else { std::cout << "CacheEfficientHogwildTrainer.h: No partitioning method selected" << std::endl; exit(0); } if (FLAGS_print_partition_time) { this->PrintPartitionTime(partition_timer); } model->SetUpWithPartitions(partitions); updater->SetUpWithPartitions(partitions); TrainStatistics stats; // Train. Timer gradient_timer; for (int epoch = 0; epoch < FLAGS_n_epochs; epoch++) { this->EpochBegin(epoch, gradient_timer, model, datapoints, &stats); updater->EpochBegin(); #pragma omp parallel for schedule(static, 1) for (int thread = 0; thread < FLAGS_n_threads; thread++) { for (int batch = 0; batch < partitions.NumBatches(); batch++) { for (int index = 0; index < partitions.NumDatapointsInBatch(thread, batch); index++) { updater->Update(partitions.GetDatapoint(thread, batch, index)); } } } updater->EpochFinish(); } return stats; } }; #endif
kinFoodWeb_kry_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Ting Yan @ SMU * Based on kinFoodWeb_kry.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example (serial): * * This example solves a nonlinear system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion * on the unit square in two dimensions. The dependent variable * vector is the following: * * 1 2 ns * c = (c , c , ..., c ) (denoted by the variable cc) * * and the PDE's are as follows: * * i i * 0 = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The number np is both the * number of prey and predator species. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * b(i) = BB * (1 + alpha * x * y) (i <= np) * b(i) =-BB * (1 + alpha * x * y) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED ( i > np) * * The various scalar parameters are set using define's or in * routine InitUserData. * * The boundary conditions are: normal derivative = 0, and the * initial guess is constant in x and y, but the final solution * is not. * * The PDEs are discretized by central differencing on an MX by * MY mesh. * * The nonlinear system is solved by KINSOL using the method * specified in the local variable globalstrat. * * The preconditioner matrix is a block-diagonal matrix based on * the partial derivatives of the interaction terms f only. * * Constraints are imposed to make all components of the solution * positive. * * Optionally, we can set the number of threads with an environment * variable or from the command line. To check the current value * for number of threads set by the environment variable: * % echo $OMP_NUM_THREADS * * Execution: * * If the user wants to use the default value or the number of * threads set by the environment variable use * % ./kinFoodWeb_kry_omp * If the user wants to specify the number of threads to use * % ./kinFoodWeb_kry_omp num_threads * where num_threads is the number of threads the user wants to use * * ----------------------------------------------------------------- * References: * * 1. Peter N. Brown and Youcef Saad, * Hybrid Krylov Methods for Nonlinear Systems of Equations * LLNL report UCRL-97645, November 1987. * * 2. Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, * Lawrence Livermore National Laboratory Report UCRL-95088, * Rev. 1, June 1987, and Journal of Applied Mathematics and * Computation, Vol. 31 (May 1989), pp. 40-91. (Presents a * description of the time-dependent version of this test * problem.) * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <kinsol/kinsol.h> /* access to KINSOL func., consts. */ #include <nvector/nvector_openmp.h> /* access to OpenMP N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #include <sundials/sundials_math.h> /* access to SUNMAX, SUNRabs, SUNRsqrt */ #ifdef _OPENMP #include <omp.h> #endif /* Problem Constants */ #define NUM_SPECIES 6 /* must equal 2*(number of prey or predators) number of prey = number of predators */ #define PI RCONST(3.1415926535898) /* pi */ #define MX 8 /* MX = number of x mesh points */ #define MY 8 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NSMX * MY) /* number of equations in the system */ #define AA RCONST(1.0) /* value of coefficient AA in above eqns */ #define EE RCONST(10000.) /* value of coefficient EE in above eqns */ #define GG RCONST(0.5e-6) /* value of coefficient GG in above eqns */ #define BB RCONST(1.0) /* value of coefficient BB in above eqns */ #define DPREY RCONST(1.0) /* value of coefficient dprey above */ #define DPRED RCONST(0.5) /* value of coefficient dpred above */ #define ALPHA RCONST(1.0) /* value of coefficient alpha above */ #define AX RCONST(1.0) /* total range of x variable */ #define AY RCONST(1.0) /* total range of y variable */ #define FTOL RCONST(1.e-7) /* ftol tolerance */ #define STOL RCONST(1.e-13) /* stol tolerance */ #define THOUSAND RCONST(1000.0) /* one thousand */ #define ZERO RCONST(0.0) /* 0. */ #define ONE RCONST(1.0) /* 1. */ #define TWO RCONST(2.0) /* 2. */ #define PREYIN RCONST(1.0) /* initial guess for prey concentrations. */ #define PREDIN RCONST(30000.0)/* initial guess for predator concs. */ /* User-defined vector access macro: IJ_Vptr */ /* IJ_Vptr is defined in order to translate from the underlying 3D structure of the dependent variable vector to the 1D storage scheme for an N-vector. IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to indices is = 0, jx = i, jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, i*NUM_SPECIES + j*NSMX)) /* Type : UserData contains preconditioner blocks, pivot arrays, and problem constants */ typedef struct { realtype **P[MX][MY]; sunindextype *pivot[MX][MY]; realtype **acoef, *bcoef; N_Vector rates; realtype *cox, *coy; realtype ax, ay, dx, dy; realtype uround, sqruround; sunindextype mx, my, ns, np; int nthreads; } *UserData; /* Functions Called by the KINSOL Solver */ static int func(N_Vector cc, N_Vector fval, void *user_data); static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data); static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data); /* Private Helper Functions */ static UserData AllocUserData(void); static void InitUserData(UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector cc, N_Vector sc); static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol); static void PrintOutput(N_Vector cc); static void PrintFinalStats(void *kmem); static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data); static realtype DotProd(sunindextype size, realtype *x1, realtype *x2); static int check_flag(void *flagvalue, const char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int globalstrategy; realtype fnormtol, scsteptol; N_Vector cc, sc, constraints; UserData data; int flag, maxl, maxlrst; void *kmem; SUNLinearSolver LS; int num_threads; cc = sc = constraints = NULL; kmem = NULL; LS = NULL; data = NULL; /* Allocate memory, and set problem data, initial values, tolerances */ globalstrategy = KIN_NONE; /* Set the number of threads to use */ num_threads = 1; /* default value*/ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrithe with command line value, if supplied */ num_threads = strtol(argv[1], NULL, 0); data = AllocUserData(); if (check_flag((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); data->nthreads = num_threads; /* Create serial vectors of length NEQ */ cc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)cc, "N_VNew_OpenMP", 0)) return(1); sc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)sc, "N_VNew_OpenMP", 0)) return(1); data->rates = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)data->rates, "N_VNew_OpenMP", 0)) return(1); constraints = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)constraints, "N_VNew_OpenMP", 0)) return(1); N_VConst(TWO, constraints); SetInitialProfiles(cc, sc); fnormtol=FTOL; scsteptol=STOL; /* Call KINCreate/KINInit to initialize KINSOL. A pointer to KINSOL problem memory is returned and stored in kmem. */ kmem = KINCreate(); if (check_flag((void *)kmem, "KINCreate", 0)) return(1); /* Vector cc passed as template vector. */ flag = KINInit(kmem, func, cc); if (check_flag(&flag, "KINInit", 1)) return(1); flag = KINSetUserData(kmem, data); if (check_flag(&flag, "KINSetUserData", 1)) return(1); flag = KINSetConstraints(kmem, constraints); if (check_flag(&flag, "KINSetConstraints", 1)) return(1); flag = KINSetFuncNormTol(kmem, fnormtol); if (check_flag(&flag, "KINSetFuncNormTol", 1)) return(1); flag = KINSetScaledStepTol(kmem, scsteptol); if (check_flag(&flag, "KINSetScaledStepTol", 1)) return(1); /* We no longer need the constraints vector since KINSetConstraints creates a private copy for KINSOL to use. */ N_VDestroy_OpenMP(constraints); /* Create SUNLinSol_SPGMR object with right preconditioning and the maximum Krylov dimension maxl */ maxl = 15; LS = SUNLinSol_SPGMR(cc, PREC_RIGHT, maxl); if(check_flag((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); /* Attach the linear solver to KINSOL */ flag = KINSetLinearSolver(kmem, LS, NULL); if (check_flag(&flag, "KINSetLinearSolver", 1)) return 1; /* Set the maximum number of restarts */ maxlrst = 2; flag = SUNLinSol_SPGMRSetMaxRestarts(LS, maxlrst); if (check_flag(&flag, "SUNLinSol_SPGMRSetMaxRestarts", 1)) return(1); /* Specify the preconditioner setup and solve routines */ flag = KINSetPreconditioner(kmem, PrecSetupBD, PrecSolveBD); if (check_flag(&flag, "KINSetPreconditioner", 1)) return(1); /* Print out the problem size, solution parameters, initial guess. */ PrintHeader(globalstrategy, maxl, maxlrst, fnormtol, scsteptol); /* Call KINSol and print output concentration profile */ flag = KINSol(kmem, /* KINSol memory block */ cc, /* initial guess on input; solution vector */ globalstrategy, /* global strategy choice */ sc, /* scaling vector for the variable cc */ sc); /* scaling vector for function values fval */ if (check_flag(&flag, "KINSol", 1)) return(1); printf("\n\nComputed equilibrium species concentrations:\n"); PrintOutput(cc); /* Print final statistics and free memory */ PrintFinalStats(kmem); printf("num_threads = %i\n", num_threads); N_VDestroy_OpenMP(cc); N_VDestroy_OpenMP(sc); KINFree(&kmem); SUNLinSolFree(LS); FreeUserData(data); return(0); } /* Readability definitions used in other routines below */ #define acoef (data->acoef) #define bcoef (data->bcoef) #define cox (data->cox) #define coy (data->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY KINSOL *-------------------------------------------------------------------- */ /* * System function for predator-prey system */ static int func(N_Vector cc, N_Vector fval, void *user_data) { realtype xx, yy, delx, dely, *cxy, *rxy, *fxy, dcyli, dcyui, dcxli, dcxri; sunindextype jx, jy, is, idyu, idyl, idxr, idxl; UserData data; data = (UserData)user_data; delx = data->dx; dely = data->dy; /* Loop over all mesh points, evaluating rate array at each point*/ for (jy = 0; jy < MY; jy++) { yy = dely*jy; /* Set lower/upper index shifts, special at boundaries. */ idyl = (jy != 0 ) ? NSMX : -NSMX; idyu = (jy != MY-1) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = delx*jx; /* Set left/right index shifts, special at boundaries. */ idxl = (jx != 0 ) ? NUM_SPECIES : -NUM_SPECIES; idxr = (jx != MX-1) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); rxy = IJ_Vptr(data->rates,jx,jy); fxy = IJ_Vptr(fval,jx,jy); /* Get species interaction rate array at (xx,yy) */ WebRate(xx, yy, cxy, rxy, user_data); for(is = 0; is < NUM_SPECIES; is++) { /* Differencing in x direction */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in y direction */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxri = *(cxy + idxr +is) - *(cxy+is); /* Compute the total rate value at (xx,yy) */ fxy[is] = (coy)[is] * (dcyui - dcyli) + (cox)[is] * (dcxri - dcxli) + rxy[is]; } /* end of is loop */ } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner setup routine. Generate and preprocess P. */ static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data) { realtype r, r0, uround, sqruround, xx, yy, delx, dely, csave, fac; realtype *cxy, *scxy, **Pxy, *ratesxy, *Pxycol, perturb_rates[NUM_SPECIES]; sunindextype i, j, jx, jy, ret; UserData data; data = (UserData) user_data; delx = data->dx; dely = data->dy; uround = data->uround; sqruround = data->sqruround; fac = N_VWL2Norm(fval, fscale); r0 = THOUSAND * uround * fac * NEQ; if(r0 == ZERO) r0 = ONE; /* Loop over spatial points; get size NUM_SPECIES Jacobian block at each */ for (jy = 0; jy < MY; jy++) { yy = jy*dely; for (jx = 0; jx < MX; jx++) { xx = jx*delx; Pxy = (data->P)[jx][jy]; cxy = IJ_Vptr(cc,jx,jy); scxy= IJ_Vptr(cscale,jx,jy); ratesxy = IJ_Vptr((data->rates),jx,jy); /* Compute difference quotients of interaction rate fn. */ for (j = 0; j < NUM_SPECIES; j++) { csave = cxy[j]; /* Save the j,jx,jy element of cc */ r = SUNMAX(sqruround*SUNRabs(csave), r0/scxy[j]); cxy[j] += r; /* Perturb the j,jx,jy element of cc */ fac = ONE/r; WebRate(xx, yy, cxy, perturb_rates, data); /* Restore j,jx,jy element of cc */ cxy[j] = csave; /* Load the j-th column of difference quotients */ Pxycol = Pxy[j]; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) Pxycol[i] = (perturb_rates[i] - ratesxy[i]) * fac; } /* end of j loop */ /* Do LU decomposition of size NUM_SPECIES preconditioner block */ ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (data->pivot)[jx][jy]); if (ret != 0) return(1); } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner solve routine */ static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data) { realtype **Pxy, *vxy; sunindextype *piv, jx, jy; UserData data; data = (UserData)user_data; #pragma omp parallel for collapse(2) default(shared) private(jx, jy, Pxy, piv, vxy) schedule(static) for (jx=0; jx<MX; jx++) { for (jy=0; jy<MY; jy++) { /* For each (jx,jy), solve a linear system of size NUM_SPECIES. vxy is the address of the corresponding portion of the vector vv; Pxy is the address of the corresponding block of the matrix P; piv is the address of the corresponding block of the array pivot. */ vxy = IJ_Vptr(vv,jx,jy); Pxy = (data->P)[jx][jy]; piv = (data->pivot)[jx][jy]; denseGETRS(Pxy, NUM_SPECIES, piv, vxy); } /* end of jy loop */ } /* end of jx loop */ return(0); } /* * Interaction rate function routine */ static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data) { sunindextype i; realtype fac; UserData data; data = (UserData)user_data; for (i = 0; i<NUM_SPECIES; i++) ratesxy[i] = DotProd(NUM_SPECIES, cxy, acoef[i]); fac = ONE + ALPHA * xx * yy; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) ratesxy[i] = cxy[i] * ( bcoef[i] * fac + ratesxy[i] ); } /* * Dot product routine for realtype arrays */ static realtype DotProd(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { int jx, jy; UserData data; data = (UserData) malloc(sizeof *data); for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { (data->P)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->pivot)[jx][jy] = newIndexArray(NUM_SPECIES); } } acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); bcoef = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); cox = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); coy = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(UserData data) { sunindextype i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; data->mx = MX; data->my = MY; data->ns = NUM_SPECIES; data->np = NUM_SPECIES/2; data->ax = AX; data->ay = AY; data->dx = (data->ax)/(MX-1); data->dy = (data->ay)/(MY-1); data->uround = UNIT_ROUNDOFF; data->sqruround = SUNRsqrt(data->uround); /* Set up the coefficients a and b plus others found in the equations */ np = data->np; dx2=(data->dx)*(data->dx); dy2=(data->dy)*(data->dy); for (i = 0; i < np; i++) { a1= &(acoef[i][np]); a2= &(acoef[i+np][0]); a3= &(acoef[i][0]); a4= &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* and then change the diagonal elements of acoef to -AA */ acoef[i][i]=-AA; acoef[i+np][i+np] = -AA; bcoef[i] = BB; bcoef[i+np] = -BB; cox[i]=DPREY/dx2; cox[i+np]=DPRED/dx2; coy[i]=DPREY/dy2; coy[i+np]=DPRED/dy2; } } /* * Free data memory */ static void FreeUserData(UserData data) { int jx, jy; for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { destroyMat((data->P)[jx][jy]); destroyArray((data->pivot)[jx][jy]); } } destroyMat(acoef); free(bcoef); free(cox); free(coy); N_VDestroy_OpenMP(data->rates); free(data); } /* * Set initial conditions in cc */ static void SetInitialProfiles(N_Vector cc, N_Vector sc) { int i, jx, jy; realtype *cloc, *sloc; realtype ctemp[NUM_SPECIES], stemp[NUM_SPECIES]; /* Initialize arrays ctemp and stemp used in the loading process */ for (i = 0; i < NUM_SPECIES/2; i++) { ctemp[i] = PREYIN; stemp[i] = ONE; } for (i = NUM_SPECIES/2; i < NUM_SPECIES; i++) { ctemp[i] = PREDIN; stemp[i] = RCONST(0.00001); } /* Load initial profiles into cc and sc vector from ctemp and stemp. */ for (jy = 0; jy < MY; jy++) { for (jx = 0; jx < MX; jx++) { cloc = IJ_Vptr(cc,jx,jy); sloc = IJ_Vptr(sc,jx,jy); for (i = 0; i < NUM_SPECIES; i++) { cloc[i] = ctemp[i]; sloc[i] = stemp[i]; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol) { printf("\nPredator-prey test problem -- KINSol (OpenMP version)\n\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Number of species = %d\n", NUM_SPECIES); printf("Total system size = %d\n\n", NEQ); printf("Flag globalstrategy = %d (0 = None, 1 = Linesearch)\n", globalstrategy); printf("Linear solver is SPGMR with maxl = %d, maxlrst = %d\n", maxl, maxlrst); printf("Preconditioning uses interaction-only block-diagonal matrix\n"); printf("Positivity constraints imposed on all components \n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: fnormtol = %Lg scsteptol = %Lg\n", fnormtol, scsteptol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #else printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #endif printf("\nInitial profile of concentration\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At all mesh points: %Lg %Lg %Lg %Lg %Lg %Lg\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #else printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #endif } /* * Print sampled values of current cc */ static void PrintOutput(N_Vector cc) { int is, jx, jy; realtype *ct; jy = 0; jx = 0; ct = IJ_Vptr(cc,jx,jy); printf("\nAt bottom left:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++){ if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } jy = MY-1; jx = MX-1; ct = IJ_Vptr(cc,jx,jy); printf("\n\nAt top right:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++) { if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } printf("\n\n"); } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *kmem) { long int nni, nfe, nli, npe, nps, ncfl, nfeSG; int flag; flag = KINGetNumNonlinSolvIters(kmem, &nni); check_flag(&flag, "KINGetNumNonlinSolvIters", 1); flag = KINGetNumFuncEvals(kmem, &nfe); check_flag(&flag, "KINGetNumFuncEvals", 1); flag = KINGetNumLinIters(kmem, &nli); check_flag(&flag, "KINGetNumLinIters", 1); flag = KINGetNumPrecEvals(kmem, &npe); check_flag(&flag, "KINGetNumPrecEvals", 1); flag = KINGetNumPrecSolves(kmem, &nps); check_flag(&flag, "KINGetNumPrecSolves", 1); flag = KINGetNumLinConvFails(kmem, &ncfl); check_flag(&flag, "KINGetNumLinConvFails", 1); flag = KINGetNumLinFuncEvals(kmem, &nfeSG); check_flag(&flag, "KINGetNumLinFuncEvals", 1); printf("Final Statistics.. \n"); printf("nni = %5ld nli = %5ld\n", nni, nli); printf("nfe = %5ld nfeSG = %5ld\n", nfe, nfeSG); printf("nps = %5ld npe = %5ld ncfl = %5ld\n", nps, npe, ncfl); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns a flag so check if * flag >= 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return(1); } } /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
GB_unaryop__identity_fp64_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_fp64_int16 // op(A') function: GB_tran__identity_fp64_int16 // C type: double // A type: int16_t // cast: double cij = (double) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, 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_IDENTITY || GxB_NO_FP64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_fp64_int16 ( double *Cx, // Cx and Ax may be aliased int16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_fp64_int16 ( 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
ex07.c
#include <stdio.h> #include <omp.h> static long num_steps = 1000000; double step; int main(int argv, char* argc) { int i; double x, pi, sum = 0.0; step = 1.0 / (double) num_steps; double startTime = omp_get_wtime(); #pragma omp parallel { double x; #pragma omp for reduction (+:sum) for (i = 0; i < num_steps; i++) { x = (i + 0.5) * step; sum += 4.0 / (1.0 + x * x); } } pi = step * sum; double endTime = omp_get_wtime(); printf ("Computed integral: %f\n", pi); printf ("Time elapsed: %f secs\n", (endTime - startTime)); return 0; }
GB_binop__isne_fc64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__isne_fc64 // A.*B function (eWiseMult): GB_AemultB__isne_fc64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__isne_fc64 // C+=b function (dense accum): GB_Cdense_accumb__isne_fc64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isne_fc64 // C=scalar+B GB_bind1st__isne_fc64 // C=scalar+B' GB_bind1st_tran__isne_fc64 // C=A+scalar GB_bind2nd__isne_fc64 // C=A'+scalar GB_bind2nd_tran__isne_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // B,b type: GxB_FC64_t // BinaryOp: cij = GB_FC64_isne (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_FC64_isne (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_FC64 || GxB_NO_ISNE_FC64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__isne_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__isne_fc64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__isne_fc64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__isne_fc64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__isne_fc64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__isne_fc64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t bij = Bx [p] ; Cx [p] = GB_FC64_isne (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_fc64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; Cx [p] = GB_FC64_isne (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_isne (x, aij) ; \ } GrB_Info GB_bind1st_tran__isne_fc64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_isne (aij, y) ; \ } GrB_Info GB_bind2nd_tran__isne_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
grid_basis.c
/* * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <math.h> #include "cint.h" #include "config.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #define MAX_THREADS 256 void VXCnr_ao_screen(unsigned char *non0table, double *coords, int ngrids, int *atm, int natm, int *bas, int nbas, double *env) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; int ib, i, j; int np, nc, atm_id, bas_id; double rr, arr, maxc; double logcoeff[NPRIMAX]; double dr[3]; double *p_exp, *pcoeff, *ratm; for (bas_id = 0; bas_id < nbas; bas_id++) { np = bas[NPRIM_OF]; nc = bas[NCTR_OF ]; p_exp = env + bas[PTR_EXP]; pcoeff = env + bas[PTR_COEFF]; atm_id = bas[ATOM_OF]; ratm = env + atm[atm_id*ATM_SLOTS+PTR_COORD]; for (j = 0; j < np; j++) { maxc = 0; for (i = 0; i < nc; i++) { maxc = MAX(maxc, fabs(pcoeff[i*np+j])); } logcoeff[j] = log(maxc); } for (ib = 0; ib < nblk; ib++) { for (i = ib*BLKSIZE; i < MIN(ngrids, (ib+1)*BLKSIZE); i++) { dr[0] = coords[0*ngrids+i] - ratm[0]; dr[1] = coords[1*ngrids+i] - ratm[1]; dr[2] = coords[2*ngrids+i] - ratm[2]; rr = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2]; for (j = 0; j < np; j++) { arr = p_exp[j] * rr; if (arr-logcoeff[j] < EXPCUTOFF) { non0table[ib*nbas+bas_id] = 1; goto next_blk; } } } non0table[ib*nbas+bas_id] = 0; next_blk:; } bas += BAS_SLOTS; } } void VXCgen_grid(double *out, double *coords, double *atm_coords, double *radii_table, int natm, int ngrids) { const size_t Ngrids = ngrids; int i, j, n; double dx, dy, dz, dist; double *grid_dist = malloc(sizeof(double) * natm*Ngrids); for (i = 0; i < natm; i++) { for (n = 0; n < Ngrids; n++) { dx = coords[0*Ngrids+n] - atm_coords[i*3+0]; dy = coords[1*Ngrids+n] - atm_coords[i*3+1]; dz = coords[2*Ngrids+n] - atm_coords[i*3+2]; grid_dist[i*Ngrids+n] = sqrt(dx*dx + dy*dy + dz*dz); } } double *bufs[MAX_THREADS]; #pragma omp parallel default(none) \ shared(out, grid_dist, atm_coords, radii_table, natm, bufs) \ private(i, j, n, dx, dy, dz) { int thread_id = omp_get_thread_num(); double *buf = out; if (thread_id != 0) { buf = malloc(sizeof(double) * natm*Ngrids); } bufs[thread_id] = buf; for (i = 0; i < natm*Ngrids; i++) { buf[i] = 1; } int ij; double fac; double *g = malloc(sizeof(double)*Ngrids); #pragma omp for nowait schedule(static) for (ij = 0; ij < natm*natm; ij++) { i = ij / natm; j = ij % natm; if (i <= j) { continue; } dx = atm_coords[i*3+0] - atm_coords[j*3+0]; dy = atm_coords[i*3+1] - atm_coords[j*3+1]; dz = atm_coords[i*3+2] - atm_coords[j*3+2]; fac = 1 / sqrt(dx*dx + dy*dy + dz*dz); for (n = 0; n < Ngrids; n++) { g[n] = grid_dist[i*Ngrids+n] - grid_dist[j*Ngrids+n]; g[n] *= fac; } if (radii_table != NULL) { fac = radii_table[i*natm+j]; for (n = 0; n < Ngrids; n++) { g[n] += fac * (1 - g[n]*g[n]); } } for (n = 0; n < Ngrids; n++) { g[n] = (3 - g[n]*g[n]) * g[n] * .5; } for (n = 0; n < Ngrids; n++) { g[n] = (3 - g[n]*g[n]) * g[n] * .5; } for (n = 0; n < Ngrids; n++) { g[n] = (3 - g[n]*g[n]) * g[n] * .5; g[n] *= .5; } for (n = 0; n < Ngrids; n++) { buf[i*Ngrids+n] *= .5 - g[n]; buf[j*Ngrids+n] *= .5 + g[n]; } } NPomp_dprod_reduce_inplace(bufs, natm*Ngrids); if (thread_id != 0) { free(buf); } free(g); } free(grid_dist); }
critical_orphaned.c
int counter = 0; int foo() { #pragma omp critical { counter++; } return 0; } int main() { foo(); return 0; }
GB_binop__bshift_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__bshift_uint32 // A.*B function (eWiseMult): GB_AemultB__bshift_uint32 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__bshift_uint32 // C+=b function (dense accum): GB_Cdense_accumb__bshift_uint32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bshift_uint32 // C=scalar+B GB_bind1st__bshift_uint32 // C=scalar+B' GB_bind1st_tran__bshift_uint32 // C=A+scalar GB_bind2nd__bshift_uint32 // C=A'+scalar GB_bind2nd_tran__bshift_uint32 // C type: uint32_t // A type: uint32_t // B,b type: int8_t // BinaryOp: cij = GB_bitshift_uint32 (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 0 // 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 \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_bitshift_uint32 (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BSHIFT || GxB_NO_UINT32 || GxB_NO_BSHIFT_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__bshift_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__bshift_uint32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__bshift_uint32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type 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 (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__bshift_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__bshift_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__bshift_uint32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t bij = Bx [p] ; Cx [p] = GB_bitshift_uint32 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__bshift_uint32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_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++) { uint32_t aij = Ax [p] ; Cx [p] = GB_bitshift_uint32 (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = GB_bitshift_uint32 (x, aij) ; \ } GrB_Info GB_bind1st_tran__bshift_uint32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = GB_bitshift_uint32 (aij, y) ; \ } GrB_Info GB_bind2nd_tran__bshift_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
attention.c
#include "darknet.h" #include <sys/time.h> #include <assert.h> void extend_data_truth(data *d, int n, real_t val) { int i, j; for (i = 0; i < d->y.rows; ++i) { d->y.vals[i] = realloc(d->y.vals[i], (d->y.cols + n) * sizeof(real_t)); for (j = 0; j < n; ++j) { d->y.vals[i][d->y.cols + j] = val; } } d->y.cols += n; } matrix network_loss_data(network *net, data test) { int i, b; int k = 1; matrix pred = make_matrix(test.X.rows, k); real_t *X = calloc(net->batch * test.X.cols, sizeof(real_t)); real_t *y = calloc(net->batch * test.y.cols, sizeof(real_t)); for (i = 0; i < test.X.rows; i += net->batch) { for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; memcpy(X + b * test.X.cols, test.X.vals[i + b], test.X.cols * sizeof(real_t)); memcpy(y + b * test.y.cols, test.y.vals[i + b], test.y.cols * sizeof(real_t)); } network orig = *net; net->input = X; net->truth = y; net->train = 0; net->delta = 0; forward_network(net); *net = orig; real_t *delta = net->layers[net->n - 1].output; for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; int t = max_index(y + b * test.y.cols, 1000); real_t err = sum_array(delta + b * net->outputs, net->outputs); pred.vals[i + b][0] = -err; //pred.vals[i+b][0] = 1-delta[b*net->outputs + t]; } } free(X); free(y); return pred; } void train_attention(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear) { int i, j; real_t avg_cls_loss = -1; real_t avg_att_loss = -1; char *base = basecfg(cfgfile); printf("%s\n", base); printf("%d\n", ngpus); network **nets = calloc(ngpus, sizeof(network*)); srand(time(0)); int seed = rand(); for (i = 0; i < ngpus; ++i) { srand(seed); #ifdef GPU cuda_set_device(gpus[i]); #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network *net = nets[0]; int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); list *options = read_data_cfg(datacfg); char *backup_directory = option_find_str(options, "backup", "/backup/"); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *train_list = option_find_str(options, "train", "data/train.list"); int classes = option_find_int(options, "classes", 2); char **labels = get_labels(label_list); list *plist = get_paths(train_list); char **paths = (char **) list_to_array(plist); printf("%d\n", plist->size); int N = plist->size; double time; int divs = 3; int size = 2; load_args args = { 0 }; args.w = divs * net->w / size; args.h = divs * net->h / size; args.size = divs * net->w / size; args.threads = 32; args.hierarchy = net->hierarchy; args.min = net->min_ratio * args.w; args.max = net->max_ratio * args.w; args.angle = net->angle; args.aspect = net->aspect; args.exposure = net->exposure; args.saturation = net->saturation; args.hue = net->hue; args.paths = paths; args.classes = classes; args.n = imgs; args.m = N; args.labels = labels; args.type = CLASSIFICATION_DATA; data train; data buffer; pthread_t load_thread; args.d = &buffer; load_thread = load_data(args); int epoch = (*net->seen) / N; while (get_current_batch(net) < net->max_batches || net->max_batches == 0) { time = what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); data resized = resize_data(train, net->w, net->h); extend_data_truth(&resized, divs * divs, 0); data *tiles = tile_data(train, divs, size); printf("Loaded: %lf seconds\n", what_time_is_it_now() - time); time = what_time_is_it_now(); real_t aloss = 0; real_t closs = 0; int z; for (i = 0; i < divs * divs / ngpus; ++i) { #pragma omp parallel for for (j = 0; j < ngpus; ++j) { int index = i * ngpus + j; extend_data_truth(tiles + index, divs * divs, SECRET_NUM); matrix deltas = network_loss_data(nets[j], tiles[index]); for (z = 0; z < resized.y.rows; ++z) { resized.y.vals[z][train.y.cols + index] = deltas.vals[z][0]; } free_matrix(deltas); } } int *inds = calloc(resized.y.rows, sizeof(int)); for (z = 0; z < resized.y.rows; ++z) { int index = max_index(resized.y.vals[z] + train.y.cols, divs * divs); inds[z] = index; for (i = 0; i < divs * divs; ++i) { resized.y.vals[z][train.y.cols + i] = (i == index) ? 1 : 0; } } data best = select_data(tiles, inds); free(inds); #ifdef GPU if (ngpus == 1) { closs = train_network(net, best); } else { closs = train_networks(nets, ngpus, best, 4); } #endif for (i = 0; i < divs * divs; ++i) { printf("%.2f ", resized.y.vals[0][train.y.cols + i]); if ((i + 1) % divs == 0) printf("\n"); free_data(tiles[i]); } free_data(best); printf("\n"); image im = real_t_to_image(64, 64, 3, resized.X.vals[0]); //show_image(im, "orig"); //cvWaitKey(100); /* image im1 = real_t_to_image(64,64,3,tiles[i].X.vals[0]); image im2 = real_t_to_image(64,64,3,resized.X.vals[0]); show_image(im1, "tile"); show_image(im2, "res"); */ #ifdef GPU if (ngpus == 1) { aloss = train_network(net, resized); } else { aloss = train_networks(nets, ngpus, resized, 4); } #endif for (i = 0; i < divs * divs; ++i) { printf("%f ", nets[0]->output[1000 + i]); if ((i + 1) % divs == 0) printf("\n"); } printf("\n"); free_data(resized); free_data(train); if (avg_cls_loss == -1) avg_cls_loss = closs; if (avg_att_loss == -1) avg_att_loss = aloss; avg_cls_loss = avg_cls_loss * .9 + closs * .1; avg_att_loss = avg_att_loss * .9 + aloss * .1; printf( "%ld, %.3f: Att: %f, %f avg, Class: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (real_t)(*net->seen) / N, aloss, avg_att_loss, closs, avg_cls_loss, get_current_rate(net), what_time_is_it_now() - time, *net->seen); if (*net->seen / N > epoch) { epoch = *net->seen / N; char buff[256]; sprintf(buff, "%s/%s_%d.weights", backup_directory, base, epoch); save_weights(net, buff); } if (get_current_batch(net) % 1000 == 0) { char buff[256]; sprintf(buff, "%s/%s.backup", backup_directory, base); save_weights(net, buff); } } char buff[256]; sprintf(buff, "%s/%s.weights", backup_directory, base); save_weights(net, buff); pthread_join(load_thread, 0); free_network(net); free_ptrs((void**) labels, classes); free_ptrs((void**) paths, plist->size); free_list(plist); free(base); } void validate_attention_single(char *datacfg, char *filename, char *weightfile) { int i, j; network *net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list *options = read_data_cfg(datacfg); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *leaf_list = option_find_str(options, "leaves", 0); if (leaf_list) change_leaves(net->hierarchy, leaf_list); char *valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char **labels = get_labels(label_list); list *plist = get_paths(valid_list); char **paths = (char **) list_to_array(plist); int m = plist->size; free_list(plist); real_t avg_acc = 0; real_t avg_topk = 0; int *indexes = calloc(topk, sizeof(int)); int divs = 4; int size = 2; int extra = 0; real_t *avgs = calloc(classes, sizeof(real_t)); int *inds = calloc(divs * divs, sizeof(int)); for (i = 0; i < m; ++i) { int class = -1; char *path = paths[i]; for (j = 0; j < classes; ++j) { if (strstr(path, labels[j])) { class = j; break; } } image im = load_image_color(paths[i], 0, 0); image resized = resize_min(im, net->w * divs / size); image crop = crop_image(resized, (resized.w - net->w * divs / size) / 2, (resized.h - net->h * divs / size) / 2, net->w * divs / size, net->h * divs / size); image rcrop = resize_image(crop, net->w, net->h); //show_image(im, "orig"); //show_image(crop, "cropped"); //cvWaitKey(0); real_t *pred = network_predict(net, rcrop.data); //pred[classes + 56] = 0; for (j = 0; j < divs * divs; ++j) { printf("%.2f ", pred[classes + j]); if ((j + 1) % divs == 0) printf("\n"); } printf("\n"); copy_cpu(classes, pred, 1, avgs, 1); top_k(pred + classes, divs * divs, divs * divs, inds); show_image(crop, "crop"); for (j = 0; j < extra; ++j) { int index = inds[j]; int row = index / divs; int col = index % divs; int y = row * crop.h / divs - (net->h - crop.h / divs) / 2; int x = col * crop.w / divs - (net->w - crop.w / divs) / 2; printf("%d %d %d %d\n", row, col, y, x); image tile = crop_image(crop, x, y, net->w, net->h); real_t *pred = network_predict(net, tile.data); axpy_cpu(classes, 1., pred, 1, avgs, 1); show_image(tile, "tile"); //cvWaitKey(10); } if (net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1); if (rcrop.data != resized.data) free_image(rcrop); if (resized.data != im.data) free_image(resized); free_image(im); free_image(crop); top_k(pred, classes, topk, indexes); if (indexes[0] == class) avg_acc += 1; for (j = 0; j < topk; ++j) { if (indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc / (i + 1), topk, avg_topk / (i + 1)); } } void validate_attention_multi(char *datacfg, char *filename, char *weightfile) { int i, j; network *net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list *options = read_data_cfg(datacfg); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char **labels = get_labels(label_list); list *plist = get_paths(valid_list); int scales[] = { 224, 288, 320, 352, 384 }; int nscales = sizeof(scales) / sizeof(scales[0]); char **paths = (char **) list_to_array(plist); int m = plist->size; free_list(plist); real_t avg_acc = 0; real_t avg_topk = 0; int *indexes = calloc(topk, sizeof(int)); for (i = 0; i < m; ++i) { int class = -1; char *path = paths[i]; for (j = 0; j < classes; ++j) { if (strstr(path, labels[j])) { class = j; break; } } real_t *pred = calloc(classes, sizeof(real_t)); image im = load_image_color(paths[i], 0, 0); for (j = 0; j < nscales; ++j) { image r = resize_min(im, scales[j]); resize_network(net, r.w, r.h); real_t *p = network_predict(net, r.data); if (net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1, 1); axpy_cpu(classes, 1, p, 1, pred, 1); flip_image(r); p = network_predict(net, r.data); axpy_cpu(classes, 1, p, 1, pred, 1); if (r.data != im.data) free_image(r); } free_image(im); top_k(pred, classes, topk, indexes); free(pred); if (indexes[0] == class) avg_acc += 1; for (j = 0; j < topk; ++j) { if (indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc / (i + 1), topk, avg_topk / (i + 1)); } } void predict_attention(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top) { network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", 0); if (!name_list) name_list = option_find_str(options, "labels", "data/labels.list"); if (top == 0) top = option_find_int(options, "top", 1); int i = 0; char **names = get_labels(name_list); clock_t time; int *indexes = calloc(top, sizeof(int)); char buff[256]; char *input = buff; while (1) { if (filename) { strncpy(input, filename, 256); } else { printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if (!input) return; strtok(input, "\n"); } image im = load_image_color(input, 0, 0); image r = letterbox_image(im, net->w, net->h); //resize_network(&net, r.w, r.h); //printf("%d %d\n", r.w, r.h); real_t *X = r.data; time = clock(); real_t *predictions = network_predict(net, X); if (net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1); top_k(predictions, net->outputs, top, indexes); fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock() - time)); for (i = 0; i < top; ++i) { int index = indexes[i]; //if(net->hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], (net->hierarchy->parent[index] >= 0) ? names[net->hierarchy->parent[index]] : "Root"); //else printf("%s: %f\n",names[index], predictions[index]); printf("%5.2f%%: %s\n", predictions[index] * 100, names[index]); } if (r.data != im.data) free_image(r); free_image(im); if (filename) break; } } void run_attention(int argc, char **argv) { if (argc < 4) { fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char *gpu_list = find_char_arg(argc, argv, "-gpus", 0); int ngpus; int *gpus = read_intlist(gpu_list, &ngpus, gpu_index); int top = find_int_arg(argc, argv, "-t", 0); int clear = find_arg(argc, argv, "-clear"); char *data = argv[3]; char *cfg = argv[4]; char *weights = (argc > 5) ? argv[5] : 0; char *filename = (argc > 6) ? argv[6] : 0; char *layer_s = (argc > 7) ? argv[7] : 0; if (0 == strcmp(argv[2], "predict")) predict_attention(data, cfg, weights, filename, top); else if (0 == strcmp(argv[2], "train")) train_attention(data, cfg, weights, gpus, ngpus, clear); else if (0 == strcmp(argv[2], "valid")) validate_attention_single(data, cfg, weights); else if (0 == strcmp(argv[2], "validmulti")) validate_attention_multi(data, cfg, weights); }
selectionSwap.c
int main() { int x; // Case 1: If without any else. if (x) { #pragma omp parallel { int i; i = 10; } x = 5; } if (x) { #pragma omp parallel { int i; i = 10; } x = 5; } else { x = 3; } if (x) { #pragma omp parallel { int i; i = 10; } x = 5; } else { #pragma omp parallel { x = 3; } x = 11; } if (x) { x = 13; } else { #pragma omp parallel { int i; i = 10; } x = 15; } if (x) { #pragma omp parallel { x = 3; } x = 13; } else { #pragma omp parallel { int i; i = 10; } x = 15; } }
pi.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <mpi.h> #ifdef _OPENMP #include <omp.h> #endif double compute_pi(long n, int seed); int main(int argc, char *argv[]) { int rank, size; long n; double pi, global_pi; MPI_Init(NULL, NULL); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { if (argc < 2) { n = 1000; } else { n = atol(argv[1]); } n /= size; } MPI_Bcast(&n, 1, MPI_LONG, 0, MPI_COMM_WORLD); pi = compute_pi(n, rank); printf("rank %d: %ld, %.5f\n", rank, n, pi); MPI_Reduce(&pi, &global_pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) { printf("pi = %.5f\n", global_pi/size); } MPI_Finalize(); return EXIT_SUCCESS; } double compute_pi(long n, int rank) { double count = 0.0; #pragma omp parallel shared(count, n, rank) default(none) { long i; struct timeval time; gettimeofday(&time, NULL); unsigned int seed = (unsigned int) (time.tv_usec*(17*rank + 1) + time.tv_sec/(rank + 1)); #ifdef _OPENMP int thread_nr = 0; thread_nr = omp_get_thread_num(); seed += 17*thread_nr; #endif #pragma omp for reduction(+:count) for (i = 0; i < n; i++) { double x = ((double) rand_r(&seed))/RAND_MAX; double y = ((double) rand_r(&seed))/RAND_MAX; if (x*x + y*y <= 1.0) { count += 1.0; } } } return 4.0*count/n; }
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-2,4),ceild(8*t2-Nz-3,16));t3<=min(floord(4*Nt+Ny-9,16),floord(4*t1+Ny-1,16));t3++) { for (t4=max(max(ceild(t1-6,8),ceild(8*t2-Nz-19,32)),ceild(16*t3-Ny-19,32));t4<=min(min(floord(4*Nt+Nx-9,32),floord(4*t1+Nx-1,32)),floord(16*t3+Nx+3,32));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(32*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),4*t3+2),8*t4+6);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(32*t4,4*t5+4); ubv=min(32*t4+31,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
parallel_for_simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp -verify=expected,omp50 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify=expected,omp50 %s -Wuninitialized // expected-error@+1 {{unexpected OpenMP directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd foo void test_no_clause() { int i; #pragma omp parallel for simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp parallel for simd' must be a for loop}} #pragma omp parallel for simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp parallel #pragma omp parallel for 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; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} #pragma omp parallel for simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} #pragma omp parallel for simd; for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} #pragma omp parallel for simd linear(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} #pragma omp parallel for simd private(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} #pragma omp parallel for simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp parallel for 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 parallel for simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for 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 parallel for 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 parallel for simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp parallel for simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp parallel for simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp parallel for simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp parallel for simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp parallel for 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 parallel for simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for 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 parallel for 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 parallel for simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp parallel for simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp parallel for simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp parallel for simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp parallel for simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp parallel for 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 parallel for 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 parallel for simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; #pragma omp parallel // expected-error@+1 {{expected '('}} #pragma omp parallel for simd collapse for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd collapse( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd collapse() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd collapse(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd collapse(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+2 {{extra tokens at the end of '#pragma omp parallel for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp parallel for simd collapse 4) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel #pragma omp parallel for 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(); #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp parallel for simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp parallel for simd', but found only 1}} #pragma omp parallel // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd collapse(2.5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{integer constant expression}} #pragma omp parallel for simd collapse(foo()) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp parallel for simd collapse(-5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp parallel for simd collapse(0) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp parallel for simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd collapse(2) for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) // expected-error@+1 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp parallel for simd reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for 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 parallel for simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp parallel for simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp parallel for simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp parallel for 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 parallel for 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 parallel for simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp parallel for 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 parallel for simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for 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 parallel for 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 parallel for 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 parallel for 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 parallel for 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 parallel for simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp parallel for 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 parallel for 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 parallel for simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp parallel for simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp parallel for simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp parallel for 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 parallel for 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 parallel for simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp parallel for simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp parallel for 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 parallel for simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for 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 parallel for 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 parallel for 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 parallel for 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 parallel for simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; #pragma omp parallel // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd private( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd private(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd private(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd private() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd private(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp parallel for simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp parallel for simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp parallel for simd lastprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd lastprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd lastprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd lastprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd lastprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp parallel for simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp parallel for simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp parallel for simd firstprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd firstprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd firstprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd firstprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp parallel for simd firstprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp parallel for simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp parallel for simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp parallel for simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp parallel for simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp parallel for simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void test_nontemporal() { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 2 {{expected expression}} #pragma omp parallel for simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{expected expression}} #pragma omp parallel for simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{expected expression}} #pragma omp parallel for simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} omp50-error@+1 {{expected variable name}} #pragma omp parallel for simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp parallel for simd nontemporal(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp parallel for simd nontemporal(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp parallel for simd nontemporal(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp parallel for simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp parallel for simd nontemporal(x :, ) for (i = 0; i < 16; ++i) ; // omp50-note@+2 {{defined as nontemporal}} // omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp parallel for simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp parallel for simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel for simd'}} #pragma omp parallel for simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel for simd order // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp parallel for simd'}} expected-error {{expected '(' after 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp parallel for simd order( // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp parallel for simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp parallel for simd order(none // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp parallel for simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp parallel for simd order(concurrent // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp parallel for simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 0; i < 10; ++i) ; #pragma omp parallel for simd order(concurrent) // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp parallel for simd'}} for (int i = 0; i < 10; ++i) ; }
tentusscher_epi_2004_S0.c
#include <assert.h> #include <stdlib.h> #include "tentusscher_epi_2004_S0.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.4172552153702,0.00133233093318418,0.775980725003160,0.775871451583533,0.000178484465968596,0.483518904573916,0.00297208335439809,0.999998297825169,1.98274727808946e-08,1.92952362196655e-05,0.999768268008847,1.00667048889468,0.999984854519288,5.50424977684767e-05,0.352485262813812,10.8673127043200,138.860197273148}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real 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; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated version from CellML !!! FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
machinedeps.c
/* Copyright © INRIA 2010-2011. Authors: Matthijs Douze & Herve Jegou Contact: matthijs.douze@inria.fr herve.jegou@inria.fr This software is a computer program whose purpose is to provide efficient tools for basic yet computationally demanding tasks, such as find k-nearest neighbors using exhaustive search and kmeans clustering. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <assert.h> #include <sys/time.h> #include "machinedeps.h" static int count_cpu_from_env() { int ncpu; if(!getenv("YAEL_COUNT_CPU")) return 0; if(sscanf(getenv("YAEL_COUNT_CPU"), "%d", &ncpu) != 1 || ncpu <= 0) { fprintf(stderr, "could not parse YAEL_CPU_COUNT environment variable, using default\n"); return 0; } return ncpu; } #ifdef __linux__ #define __USE_GNU #include <sched.h> int count_cpu (void) { int ncpu = count_cpu_from_env(); if(ncpu) return ncpu; cpu_set_t set; sched_getaffinity (0, sizeof (cpu_set_t), &set); int i, count = 0; for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET (i, &set)) count++; return count; } #elif defined(__APPLE__) #include <sys/types.h> #include <sys/sysctl.h> int count_cpu (void) { int ncpu = count_cpu_from_env(); if(ncpu) return ncpu; int count=-1; size_t count_size=sizeof(count); sysctlbyname("hw.ncpu",&count,&count_size,NULL,0); return count; } #else int count_cpu() { return 1; } #endif #ifndef __APPLE__ double log2(double x) { return log(x)/M_LN2; } #endif #ifndef __linux__ void *memalign (size_t ignored, size_t nbytes) { return malloc (nbytes); } #endif double getmillisecs() { struct timeval tv; gettimeofday (&tv,NULL); return tv.tv_sec*1e3 +tv.tv_usec*1e-3; } /*********************************************************************** * Implementation of the threading part * * generic thread stuff */ #ifdef _OPENMP #include <omp.h> #define GET_THREAD_NUM omp_get_thread_num() #else #define GET_THREAD_NUM 0 /* #pragma's will be ignored */ #endif void compute_tasks (int n, int nt, void (*task_fun) (void *arg, int tid, int i), void *task_arg) { int i; #pragma omp parallel for schedule(dynamic) num_threads(nt) for(i = 0; i < n; i++) (*task_fun)(task_arg, GET_THREAD_NUM, i); }
st_naive_down.c
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #include <omp.h> /* multiprocessor support */ //#include "../PaulSwissPNG/png/mypng.h" #include "mypng.h" /***********************************************************************/ double* SteepestTangent(const uint8 *Image, const size_t Nr, const size_t Nc) { /* This implements the basic Steepest Down Tangent Algorithm. Loops over all other pixels and remembers the greatest negative slope. Paul @ 09 July 2018. Allocates memory for a double precision image, fills it with the Steepest Down Tangent and returns a pointer to it. */ /***********************************************************************/ double *SteepestTangentImage = (double *)calloc(Nr*Nc, sizeof(double)); if (!SteepestTangentImage) { fprintf(stderr, "SteepestTangent(): cannot allocate memory for return image.\n"); return NULL; } #pragma omp parallel for collapse(2) for (long r=0L; r<Nr; r++) { for (long c=0L; c<Nc; c++) { const long index = r*Nc + c; const double centerPixel = (double)Image[index]; double MaxSlopeSq = 0.0D; for (long r2=0L; r2<Nr; r2++) { for (long c2=0L; c2<Nc; c2++) { const double pixelDiff = (double)Image[r2*Nc + c2] - centerPixel; if (pixelDiff < 0.0D) { const double slopeSq = (pixelDiff * pixelDiff) / (double)((c2-c)*(c2-c) + (r2-r)*(r2-r)); if (slopeSq > MaxSlopeSq) MaxSlopeSq = slopeSq; } } /* c2 */ } /* r2 */ SteepestTangentImage[index] = sqrt(MaxSlopeSq); } /* c */ } /* r */ return SteepestTangentImage; } /* SteepestTangent() */
lagrange_dual_core_state_manager.h
/*****************************************************************************/ // Copyright (c) 2020-2021 Yuji KOGUMA // Released under the MIT license // https://opensource.org/licenses/mit-license.php /*****************************************************************************/ #ifndef PRINTEMPS_SOLVER_LAGRANGE_DUAL_CORE_LAGRANGE_DUAL_CORE_STATE_MANAGER_H__ #define PRINTEMPS_SOLVER_LAGRANGE_DUAL_CORE_LAGRANGE_DUAL_CORE_STATE_MANAGER_H__ #include "lagrange_dual_core_state.h" namespace printemps { namespace solver { namespace lagrange_dual { namespace core { /*****************************************************************************/ template <class T_Variable, class T_Expression> class LagrangeDualCoreStateManager { private: LagrangeDualCoreState<T_Variable, T_Expression> m_state; model::Model<T_Variable, T_Expression>* m_model_ptr; solution::IncumbentHolder<T_Variable, T_Expression>* m_incumbent_holder_ptr; Memory<T_Variable, T_Expression>* m_memory_ptr; option::Option m_option; public: /*************************************************************************/ LagrangeDualCoreStateManager( model::Model<T_Variable, T_Expression>* a_model_ptr, solution::IncumbentHolder<T_Variable, T_Expression>* a_incumbent_holder_ptr, // Memory<T_Variable, T_Expression>* a_memory_ptr, // const option::Option& a_OPTION) { this->setup(a_model_ptr, // a_incumbent_holder_ptr, // a_memory_ptr, // a_OPTION); } /*************************************************************************/ LagrangeDualCoreStateManager(void) { this->initialize(); } /*************************************************************************/ inline void initialize(void) { m_state.initialize(); m_model_ptr = nullptr; m_incumbent_holder_ptr = nullptr; m_memory_ptr = nullptr; m_option.initialize(); } /*************************************************************************/ inline void setup(model::Model<T_Variable, T_Expression>* a_model_ptr, solution::IncumbentHolder<T_Variable, T_Expression>* a_incumbent_holder_ptr, // Memory<T_Variable, T_Expression>* a_memory_ptr, // const option::Option& a_OPTION) { this->initialize(); m_model_ptr = a_model_ptr; m_incumbent_holder_ptr = a_incumbent_holder_ptr; m_memory_ptr = a_memory_ptr; m_option = a_OPTION; /** * Evaluate the initial solution score. */ m_state.current_solution_score = m_model_ptr->evaluate({}); m_state.previous_solution_score = m_state.current_solution_score; m_state.update_status = m_incumbent_holder_ptr->try_update_incumbent( m_model_ptr, m_state.current_solution_score); m_state.total_update_status = solution::IncumbentHolderConstant::STATUS_NOT_UPDATED; /** * Initialize the update status. */ m_state.total_update_status = solution::IncumbentHolderConstant::STATUS_NOT_UPDATED; m_state.termination_status = LagrangeDualCoreTerminationStatus::ITERATION_OVER; /** * Initialize the lagrangian. */ m_state.lagrangian = -HUGE_VALF; m_state.lagrangian_incumbent = -HUGE_VALF; /** * Initialize the primal solution. */ m_state.primal = m_model_ptr->export_solution(); m_state.primal_incumbent = m_state.primal; /** * Initialize the dual solution as lagrange multipliers. */ m_state.dual = m_model_ptr->generate_constraint_parameter_proxies(0.0); this->bound_dual(); m_state.dual_incumbent = m_state.dual; /** * Initialize the step size for subgradient algorithm. */ m_state.step_size = 1.0 / m_model_ptr->number_of_variables(); /** * Set up the queue for historical lagrangians. */ m_state.queue.setup(m_option.lagrange_dual.queue_size); /** * NOTE: The values of the other members of m_state remain at their * default values. */ } /*************************************************************************/ inline constexpr void update( const solution::SolutionScore& a_SOLUTION_SCORE) { /** * Update the current solution score with keeping the previous one. */ this->update_solution_score(a_SOLUTION_SCORE); /** * Update the update status. */ this->update_update_status(); /** * Update the lagrangian value. */ this->update_lagrangian(); /** * Update the step size for subgradient algorithm. */ this->update_step_size(); } /*************************************************************************/ inline constexpr void update_solution_score( const solution::SolutionScore& a_SOLUTION_SCORE) { m_state.previous_solution_score = m_state.current_solution_score; m_state.current_solution_score = a_SOLUTION_SCORE; } /*************************************************************************/ inline constexpr void update_move( neighborhood::Move<T_Variable, T_Expression>* a_selected_move_ptr) { m_state.previous_move = m_state.current_move; m_state.current_move = *a_selected_move_ptr; } /*************************************************************************/ inline constexpr void update_update_status(void) { m_state.update_status = m_incumbent_holder_ptr->try_update_incumbent( m_model_ptr, m_state.current_solution_score); m_state.total_update_status = m_state.update_status | m_state.total_update_status; } /*************************************************************************/ inline constexpr void update_lagrangian(void) { m_state.lagrangian = m_model_ptr->compute_lagrangian(m_state.dual) * m_model_ptr->sign(); /** * Update the lagrangian incumbent. */ if (m_state.lagrangian > m_state.lagrangian_incumbent) { m_state.lagrangian_incumbent = m_state.lagrangian; m_state.primal_incumbent = m_model_ptr->export_solution(); m_state.dual_incumbent = m_state.dual; } /** * Update the lagrangian queue. */ m_state.queue.push(m_state.lagrangian); } /*************************************************************************/ inline constexpr void update_step_size(void) { if (m_state.queue.size() > 0) { if (m_state.lagrangian > m_state.queue.average()) { m_state.step_size *= m_option.lagrange_dual.step_size_extend_rate; } if (m_state.lagrangian < m_state.queue.max()) { m_state.step_size *= m_option.lagrange_dual.step_size_reduce_rate; } } } /*************************************************************************/ inline constexpr void update_dual(void) { auto& constraint_ptrs = m_model_ptr->constraint_reference().constraint_ptrs; const int CONSTRAINTS_SIZE = constraint_ptrs.size(); #ifdef _OPENMP #pragma omp parallel for if (m_option.is_enabled_parallel_evaluation) \ schedule(static) #endif for (auto i = 0; i < CONSTRAINTS_SIZE; i++) { const double CONSTRAINT_VALUE = constraint_ptrs[i]->constraint_value(); const int PROXY_INDEX = constraint_ptrs[i]->proxy_index(); const int FLAT_INDEX = constraint_ptrs[i]->flat_index(); m_state.dual[PROXY_INDEX].flat_indexed_values(FLAT_INDEX) += m_state.step_size * CONSTRAINT_VALUE; } /** * Bound the values of dual solution. */ this->bound_dual(); } /*************************************************************************/ inline void bound_dual(void) { for (auto&& proxy : this->m_model_ptr->constraint_proxies()) { for (auto&& constraint : proxy.flat_indexed_constraints()) { const int PROXY_INDEX = constraint.proxy_index(); const int FLAT_INDEX = constraint.flat_index(); auto& lagrange_multiplier = m_state.dual[PROXY_INDEX].flat_indexed_values(FLAT_INDEX); switch (constraint.sense()) { case model_component::ConstraintSense::Equal: { /// nothing to do break; } case model_component::ConstraintSense::Less: { lagrange_multiplier = std::max(lagrange_multiplier, 0.0); break; } case model_component::ConstraintSense::Greater: { lagrange_multiplier = std::min(lagrange_multiplier, 0.0); break; } default: { /// nothing to do } } } } } /*************************************************************************/ inline constexpr void set_termination_status( const LagrangeDualCoreTerminationStatus a_TERMINATION_STATUS) { m_state.termination_status = a_TERMINATION_STATUS; } /*************************************************************************/ inline constexpr void set_elapsed_time(const double a_ELAPSED_TINE) { m_state.elapsed_time = a_ELAPSED_TINE; } /*************************************************************************/ inline constexpr void reset_iteration(void) { m_state.iteration = 0; } /*************************************************************************/ inline constexpr void next_iteration(void) { m_state.iteration++; } /*************************************************************************/ inline constexpr LagrangeDualCoreState<T_Variable, T_Expression>& state( void) { return m_state; } /*************************************************************************/ inline constexpr const LagrangeDualCoreState<T_Variable, T_Expression>& state(void) const { return m_state; } }; } // namespace core } // namespace lagrange_dual } // namespace solver } // namespace printemps #endif /*****************************************************************************/ // END /*****************************************************************************/
for-17.c
/* { dg-do compile } */ extern int bar (int); void foo (void) { int j, k = 1, l = 30, m = 4; long int o = 4; long long int p = 0; #pragma omp for for (j = k; j <= l; j += m - 1) ; #pragma omp for for (j = k; j <= l; j += (m - 1)) ; #pragma omp for for (j = k; j <= l; j += bar (m - 1)) ; #pragma omp for for (j = k; j <= l; j = j + m - 1) ; #pragma omp for for (j = k; j <= l; j = j + (m - 1)) ; #pragma omp for for (j = k; j <= l; j = j + bar (m - 1)) ; #pragma omp for for (j = ({ int n; n = k; n; }); j <= l; j++) ; #pragma omp for for (j = k; j <= ({ int n; n = l; n; }); j++) ; #pragma omp for for (j = k; j <= l; j += ({ int n; n = 1; n; })) ; #pragma omp for for (j = k; j <= l; j += m + 1) ; #pragma omp for for (j = k; j <= l; j += o) ; #pragma omp for for (j = k; j <= l; j = j + o) ; #pragma omp for for (j = k; j <= l; j = o + 1 + j) ; #pragma omp for for (j = k; j <= l; j = o + m + j) ; #pragma omp for for (j = k; j <= l; j += o + p) ; #pragma omp for for (j = k; j <= l; j = j + o + p) ; #pragma omp for for (j = l; j >= k; j -= o) ; #pragma omp for for (j = l; j >= k; j -= p) ; #pragma omp for for (j = l; j >= k; j -= o + p) ; }
divsufsort.c
/* * divsufsort.c for libdivsufsort * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "divsufsort_private.h" #ifdef _OPENMP # include <omp.h> #endif #ifdef PHASET #include <stdio.h> #include <time.h> #endif /*- Private Functions -*/ saidx_t init_buckets(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n) { saidx_t i, j, t, m; saint_t c0, c1; /* Initialize bucket arrays. */ for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; } for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; } /* Count the number of occurrences of the first one or two characters of each type A, B and B* suffix. Moreover, store the beginning position of all type B* suffixes into the array SA. */ for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) { /* type A suffix. */ do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1)); if(0 <= i) { /* type B* suffix. */ ++BUCKET_BSTAR(c0, c1); SA[--m] = i; /* type B suffix. */ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { ++BUCKET_B(c0, c1); } } } m = n - m; /* note: A type B* suffix is lexicographically smaller than a type B suffix that begins with the same first two characters. */ /* Calculate the index of start/end point of each bucket. */ for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) { t = i + BUCKET_A(c0); BUCKET_A(c0) = i + j; /* start point */ i = t + BUCKET_B(c0, c0); for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) { j += BUCKET_BSTAR(c0, c1); BUCKET_BSTAR(c0, c1) = j; /* end point */ i += BUCKET_B(c0, c1); } } return m; } void init_typeBstar(const sauchar_t *T, saidx_t *SA, saidx_t *PAb, saidx_t *bucket_B, saidx_t n, saidx_t m){ saidx_t i, t; saint_t c0, c1; /* Sort the type B* suffixes by their first two characters. */ for(i = m - 2; 0 <= i; --i) { t = PAb[i], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = i; } t = PAb[m - 1], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = m - 1; } /* Sort the type B* substrings using sssort. */ void string_sort_typeBstar(const sauchar_t *T, saidx_t *SA, saidx_t *PAb, saidx_t* bucket_B, saidx_t n, saidx_t m){ saidx_t* buf; #ifdef _OPENMP saidx_t *curbuf; saidx_t l; #endif saidx_t i, j, bufsize; saint_t c0, c1; #ifdef _OPENMP saint_t d0, d1; int tmp; #endif /* Sort the type B* substrings using sssort. */ #ifdef _OPENMP tmp = omp_get_max_threads(); buf = SA + m, bufsize = (n - (2 * m)) / tmp; c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m; #pragma omp parallel default(shared) private(curbuf, k, l, d0, d1, tmp) { tmp = omp_get_thread_num(); curbuf = buf + tmp * bufsize; k = 0; for(;;) { #pragma omp critical(sssort_lock) { if(0 < (l = j)) { d0 = c0, d1 = c1; do { k = BUCKET_BSTAR(d0, d1); if(--d1 <= d0) { d1 = ALPHABET_SIZE - 1; if(--d0 < 0) { break; } } } while(((l - k) <= 1) && (0 < (l = k))); c0 = d0, c1 = d1, j = k; } } if(l == 0) { break; } sssort(T, PAb, SA + k, SA + l, curbuf, bufsize, 2, n, *(SA + k) == (m - 1)); } } #else buf = SA + m, bufsize = n - (2 * m); for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) { for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) { i = BUCKET_BSTAR(c0, c1); if(1 < (j - i)) { sssort(T, PAb, SA + i, SA + j, buf, bufsize, 2, n, *(SA + i) == (m - 1)); } } } #endif } void rank_typeBstar(saidx_t* ISAb, saidx_t* SA, saidx_t m){ saidx_t i, j; /* Compute ranks of type B* substrings. */ for(i = m - 1; 0 <= i; --i) { if(0 <= SA[i]) { j = i; do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i])); SA[i + 1] = i - j; if(i <= 0) { break; } } j = i; do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0); ISAb[SA[i]] = j; } } void update_typeBstar_order(const sauchar_t *T, saidx_t *SA, saidx_t *ISAb, saidx_t n, saidx_t m){ saidx_t i, j, t; saint_t c0, c1; /* Set the sorted order of tyoe B* suffixes. */ for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) { for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { } if(0 <= i) { t = i; for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { } SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t; } } } void update_bucket_bounds(saidx_t* SA, saidx_t* bucket_A, saidx_t* bucket_B, saidx_t n, saidx_t m) { saidx_t i, j, t, k; saint_t c0, c1; /* Calculate the index of start/end point of each bucket. */ BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */ for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) { i = BUCKET_A(c0 + 1) - 1; for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) { t = i - BUCKET_B(c0, c1); BUCKET_B(c0, c1) = i; /* end point */ /* Move all type B* suffixes to the correct position. */ for(i = t, j = BUCKET_BSTAR(c0, c1); j <= k; --i, --k) { SA[i] = SA[k]; } } BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */ BUCKET_B(c0, c0) = i; /* end point */ } } /* Sorts suffixes of type B*. */ saidx_t sort_typeBstar(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n) { saidx_t *PAb, *ISAb; saidx_t m; m = init_buckets(T, SA, bucket_A, bucket_B, n); if(0 < m) { /* Sort the type B* suffixes by their first two characters. */ PAb = SA + n - m; ISAb = SA + m; init_typeBstar(T, SA, PAb, bucket_B, n, m); /* Sort the type B* substrings using sssort. */ string_sort_typeBstar(T, SA, PAb, bucket_B, n, m); /* Compute ranks of type B* substrings. */ rank_typeBstar(ISAb, SA, m); /* Construct the inverse suffix array of type B* suffixes using trsort. */ trsort(ISAb, SA, m, 1); /* Set the sorted order of tyoe B* suffixes. */ update_typeBstar_order(T, SA, ISAb, n, m); /* Calculate the index of start/end point of each bucket. */ update_bucket_bounds(SA, bucket_A, bucket_B, n, m); } return m; } void induce_typeB(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m){ saidx_t *i, *j, *k; saidx_t s; saint_t c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); *j = ~s; c0 = T[--s]; if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else { assert(((s == 0) && (T[s] == c1)) || (s < 0)); *j = ~s; } } } } } void induce_typeB2(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m){ saidx_t *i, *j, *k; saidx_t s; saint_t c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); *j = ~s; c0 = T[--s]; if((0 < s) && (T[s - 1] > c0)) { s = ~s; } /* if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; */ k = SA + BUCKET_B(c0, c1); assert(k < j); *k-- = s; BUCKET_B(c0, c1) = k - SA; } else { assert(((s == 0) && (T[s] == c1)) || (s < 0)); *j = ~s; } } } } } void induce_typeA(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m){ saidx_t *i, *j, *k; saidx_t s; saint_t c0, c2; /* Construct the suffix array by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; if((s == 0) || (T[s - 1] < c0)) { s = ~s; } if(c0 != c2) { BUCKET_A(c2) = k - SA; k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else { assert(s < 0); *i = ~s; } } } /* Constructs the suffix array by using the sorted order of type B* suffixes. */ void construct_SA(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m) { #ifdef INDUCET clock_t start, finish; double diff; start = clock(); #endif if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ induce_typeB(T, SA, bucket_A, bucket_B, n, m); //induce_typeB2(T, SA, bucket_A, bucket_B, n, m); } #ifdef INDUCET finish = clock(); diff = (double)(finish - start) / (double)CLOCKS_PER_SEC; printf("PHASE 1 %f ms\n", diff * 1000); start = clock(); #endif /* Construct the suffix array by using the sorted order of type B suffixes. */ induce_typeA(T, SA, bucket_A, bucket_B, n, m); #ifdef INDUCET finish = clock(); diff = (double)(finish - start) / (double)CLOCKS_PER_SEC; printf("PHASE 2 %f ms\n", diff * 10000); #endif } /* Constructs the burrows-wheeler transformed string directly by using the sorted order of type B* suffixes. */ static saidx_t construct_BWT(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m) { saidx_t *i, *j, *k, *orig; saidx_t s; saint_t c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); c0 = T[--s]; *j = ~((saidx_t)c0); if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else if(s != 0) { *j = ~s; #ifndef NDEBUG } else { assert(T[s] == c1); #endif } } } } /* Construct the BWTed string by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~((saidx_t)T[n - 2]) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n, orig = SA; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; *i = c0; if((0 < s) && (T[s - 1] < c0)) { s = ~((saidx_t)T[s - 1]); } if(c0 != c2) { BUCKET_A(c2) = k - SA; k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else if(s != 0) { *i = ~s; } else { orig = i; } } return orig - SA; } /*---------------------------------------------------------------------------*/ /*- Function -*/ saint_t divsufsort(const sauchar_t *T, saidx_t *SA, saidx_t n) { saidx_t *bucket_A, *bucket_B; saidx_t m; saint_t err = 0; /* Check arguments. */ if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; } else if(n == 0) { return 0; } else if(n == 1) { SA[0] = 0; return 0; } else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; } bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t)); bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t)); /* Suffixsort. */ if((bucket_A != NULL) && (bucket_B != NULL)) { #ifdef PHASET clock_t start, finish; double diff; start = clock(); #endif m = sort_typeBstar(T, SA, bucket_A, bucket_B, n); #ifdef PHASET finish = clock(); diff = (double)(finish - start) / (double)CLOCKS_PER_SEC; printf("PHASE 1 %f ms\n", diff * 1000); start = clock(); #endif construct_SA(T, SA, bucket_A, bucket_B, n, m); #ifdef PHASET finish = clock(); diff = (double)(finish - start) / (double)CLOCKS_PER_SEC; printf("PHASE 2 %f ms\n", diff * 1000); #endif } else { err = -2; } free(bucket_B); free(bucket_A); return err; } saidx_t divbwt(const sauchar_t *T, sauchar_t *U, saidx_t *A, saidx_t n) { saidx_t *B; saidx_t *bucket_A, *bucket_B; saidx_t m, pidx, i; /* Check arguments. */ if((T == NULL) || (U == NULL) || (n < 0)) { return -1; } else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; } if((B = A) == NULL) { B = (saidx_t *)malloc((size_t)(n + 1) * sizeof(saidx_t)); } bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t)); bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t)); /* Burrows-Wheeler Transform. */ if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) { m = sort_typeBstar(T, B, bucket_A, bucket_B, n); pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m); /* Copy to output string. */ U[0] = T[n - 1]; for(i = 0; i < pidx; ++i) { U[i + 1] = (sauchar_t)B[i]; } for(i += 1; i < n; ++i) { U[i] = (sauchar_t)B[i]; } pidx += 1; } else { pidx = -2; } free(bucket_B); free(bucket_A); if(A == NULL) { free(B); } return pidx; } const char * divsufsort_version(void) { return PROJECT_VERSION_FULL; }
GB_unaryop__abs_int16_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_int16_uint8 // op(A') function: GB_tran__abs_int16_uint8 // C type: int16_t // A type: uint8_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IABS (x) ; // casting #define GB_CASTING(z, x) \ int16_t z = (int16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT16 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int16_uint8 ( int16_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_int16_uint8 ( 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
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++) { // we are allowed to update real and imaginary part independently which works atomically #pragma omp atomic __real(val[c]) += __real(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; #pragma omp atomic __imag(val[c]) += __imag(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; } }; grid_point_gen(N, dims, pos, periodic, width, kb_size, kb_table, update); } double calc_beta(float os, float width) { return M_PI * sqrt(pow((width * 2. / os) * (os - 0.5), 2.) - 0.8); } static float pos(int d, int i) { return (1 == d) ? 0. : (((float)i - (float)d / 2.) / (float)d); } void rolloff_correction(float os, float width, float beta, const long dimensions[3], complex float* dst) { #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); }
compare.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP AAA RRRR EEEEE % % C O O MM MM P P A A R R E % % C O O M M M PPPP AAAAA RRRR EEE % % C O O M M P A A R R E % % CCCC OOO M M P A A R R EEEEE % % % % % % MagickCore Image Comparison Methods % % % % Software Design % % Cristy % % December 2003 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/exception-private.h" #include "MagickCore/enhance.h" #include "MagickCore/fourier.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/statistic.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImages() compares one or more pixel channels of an image to a % reconstructed image and returns the difference image. % % The format of the CompareImages method is: % % Image *CompareImages(const Image *image,const Image *reconstruct_image, % const MetricType metric,double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) != 0) channels++; } return(channels == 0 ? (size_t) 1 : channels); } MagickExport Image *CompareImages(Image *image,const Image *reconstruct_image, const MetricType metric,double *distortion,ExceptionInfo *exception) { CacheView *highlight_view, *image_view, *reconstruct_view; const char *artifact; double fuzz; Image *clone_image, *difference_image, *highlight_image; MagickBooleanType status; PixelInfo highlight, lowlight, masklight; RectangleInfo geometry; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageDistortion(image,reconstruct_image,metric,distortion, exception); if (status == MagickFalse) return((Image *) NULL); columns=MagickMax(image->columns,reconstruct_image->columns); rows=MagickMax(image->rows,reconstruct_image->rows); SetGeometry(image,&geometry); geometry.width=columns; geometry.height=rows; clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); (void) SetImageMask(clone_image,ReadPixelMask,(Image *) NULL,exception); difference_image=ExtentImage(clone_image,&geometry,exception); clone_image=DestroyImage(clone_image); if (difference_image == (Image *) NULL) return((Image *) NULL); (void) SetImageAlphaChannel(difference_image,OpaqueAlphaChannel,exception); highlight_image=CloneImage(image,columns,rows,MagickTrue,exception); if (highlight_image == (Image *) NULL) { difference_image=DestroyImage(difference_image); return((Image *) NULL); } status=SetImageStorageClass(highlight_image,DirectClass,exception); if (status == MagickFalse) { difference_image=DestroyImage(difference_image); highlight_image=DestroyImage(highlight_image); return((Image *) NULL); } (void) SetImageMask(highlight_image,ReadPixelMask,(Image *) NULL,exception); (void) SetImageAlphaChannel(highlight_image,OpaqueAlphaChannel,exception); (void) QueryColorCompliance("#f1001ecc",AllCompliance,&highlight,exception); artifact=GetImageArtifact(image,"compare:highlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&highlight,exception); (void) QueryColorCompliance("#ffffffcc",AllCompliance,&lowlight,exception); artifact=GetImageArtifact(image,"compare:lowlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&lowlight,exception); (void) QueryColorCompliance("#888888cc",AllCompliance,&masklight,exception); artifact=GetImageArtifact(image,"compare:masklight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&masklight,exception); /* Generate difference image. */ status=MagickTrue; fuzz=GetFuzzyColorDistance(image,reconstruct_image); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); highlight_view=AcquireAuthenticCacheView(highlight_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,highlight_image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p, *magick_restrict q; Quantum *magick_restrict r; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); r=QueueCacheViewAuthenticPixels(highlight_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; MagickStatusType difference; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { SetPixelViaPixelInfo(highlight_image,&masklight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); continue; } difference=MagickFalse; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance, pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) pixel=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q); else pixel=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); distance=pixel*pixel; if (distance >= fuzz) { difference=MagickTrue; break; } } if (difference == MagickFalse) SetPixelViaPixelInfo(highlight_image,&lowlight,r); else SetPixelViaPixelInfo(highlight_image,&highlight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); } sync=SyncCacheViewAuthenticPixels(highlight_view,exception); if (sync == MagickFalse) status=MagickFalse; } highlight_view=DestroyCacheView(highlight_view); reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); (void) CompositeImage(difference_image,highlight_image,image->compose, MagickTrue,0,0,exception); highlight_image=DestroyImage(highlight_image); if (status == MagickFalse) difference_image=DestroyImage(difference_image); return(difference_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortion() compares one or more pixel channels of an image to a % reconstructed image and returns the specified distortion metric. % % The format of the GetImageDistortion method is: % % MagickBooleanType GetImageDistortion(const Image *image, % const Image *reconstruct_image,const MetricType metric, % double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double fuzz; MagickBooleanType status; size_t columns, rows; ssize_t y; /* Compute the absolute difference in pixels between two images. */ status=MagickTrue; fuzz=GetFuzzyColorDistance(image,reconstruct_image); rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t j, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; MagickBooleanType difference; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } difference=MagickFalse; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance, pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) pixel=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q); else pixel=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); distance=pixel*pixel; if (distance >= fuzz) { channel_distortion[i]++; difference=MagickTrue; } } if (difference != MagickFalse) channel_distortion[CompositePixelChannel]++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetAbsoluteDistortion) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetFuzzDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image, channel,q)); else distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetFuzzDistortion) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=(double) GetImageChannels(image); distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]); return(status); } static MagickBooleanType GetMeanAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image,channel,q))); else distance=QuantumScale*fabs((double) (Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q))); channel_distortion[i]+=distance; channel_distortion[CompositePixelChannel]+=distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanAbsoluteError) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=(double) GetImageChannels(image); return(status); } static MagickBooleanType GetMeanErrorPerPixel(Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; double area, maximum_error, mean_error; size_t columns, rows; ssize_t y; status=MagickTrue; area=0.0; maximum_error=0.0; mean_error=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image,channel,q))); else distance=fabs((double) (Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q))); distortion[i]+=distance; distortion[CompositePixelChannel]+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); image->error.mean_error_per_pixel=area*distortion[CompositePixelChannel]; image->error.normalized_mean_error=area*QuantumScale*QuantumScale*mean_error; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(status); } static MagickBooleanType GetMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image, channel,q)); else distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanSquaredError) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=GetImageChannels(image); return(status); } static MagickBooleanType GetNormalizedCrossCorrelationDistortion( const Image *image,const Image *reconstruct_image,double *distortion, ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *image_view, *reconstruct_view; ChannelStatistics *image_statistics, *reconstruct_statistics; double area; MagickBooleanType status; MagickOffsetType progress; ssize_t channels, i; size_t columns, rows; ssize_t y; /* Normalize to account for variation due to lighting and exposure condition. */ image_statistics=GetImageStatistics(image,exception); reconstruct_statistics=GetImageStatistics(reconstruct_image,exception); if ((image_statistics == (ChannelStatistics *) NULL) || (reconstruct_statistics == (ChannelStatistics *) NULL)) { if (image_statistics != (ChannelStatistics *) NULL) image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); if (reconstruct_statistics != (ChannelStatistics *) NULL) reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); return(MagickFalse); } status=MagickTrue; progress=0; for (i=0; i <= MaxPixelChannels; i++) distortion[i]=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } area=PerceptibleReciprocal(area); for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distortion[i]+=area*QuantumScale*((double) p[i]- image_statistics[channel].mean)*(GetPixelChannel(reconstruct_image, channel,q)-reconstruct_statistics[channel].mean); else distortion[i]+=area*QuantumScale*(Sa*p[i]- image_statistics[channel].mean)*(Da*GetPixelChannel( reconstruct_image,channel,q)-reconstruct_statistics[channel].mean); } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SimilarityImageTag,progress,rows); if (proceed == MagickFalse) { status=MagickFalse; break; } } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); /* Divide by the standard deviation. */ channels=0; distortion[CompositePixelChannel]=0.0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double gamma; PixelChannel channel = GetPixelChannelChannel(image,i); gamma=image_statistics[channel].standard_deviation* reconstruct_statistics[channel].standard_deviation; if (fabs(gamma) >= MagickEpsilon) { gamma=PerceptibleReciprocal(gamma); distortion[i]=QuantumRange*gamma*distortion[i]; distortion[CompositePixelChannel]+=distortion[i]*distortion[i]; channels++; } } distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]/ channels); /* Free resources. */ reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); return(status); } static MagickBooleanType GetPeakAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t j, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image,channel,q))); else distance=QuantumScale*fabs((double) (Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q))); if (distance > channel_distortion[i]) channel_distortion[i]=distance; if (distance > channel_distortion[CompositePixelChannel]) channel_distortion[CompositePixelChannel]=distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPeakAbsoluteError) #endif for (j=0; j <= MaxPixelChannels; j++) if (channel_distortion[j] > distortion[j]) distortion[j]=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } static MagickBooleanType GetPeakSignalToNoiseRatio(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) if (fabs(distortion[i]) < MagickEpsilon) distortion[i]=INFINITY; else distortion[i]=10.0*MagickLog10(1.0)-10.0*MagickLog10(distortion[i]); return(status); } static MagickBooleanType GetPerceptualHashDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { ChannelPerceptualHash *channel_phash, *reconstruct_phash; const char *artifact; MagickBooleanType normalize; ssize_t channel; /* Compute perceptual hash in the sRGB colorspace. */ channel_phash=GetImagePerceptualHash(image,exception); if (channel_phash == (ChannelPerceptualHash *) NULL) return(MagickFalse); reconstruct_phash=GetImagePerceptualHash(reconstruct_image,exception); if (reconstruct_phash == (ChannelPerceptualHash *) NULL) { channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory( channel_phash); return(MagickFalse); } artifact=GetImageArtifact(image,"phash:normalize"); normalize=(artifact == (const char *) NULL) || (IsStringTrue(artifact) == MagickFalse) ? MagickFalse : MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (channel=0; channel < MaxPixelChannels; channel++) { double difference; ssize_t i; difference=0.0; for (i=0; i < MaximumNumberOfImageMoments; i++) { double alpha, beta; ssize_t j; for (j=0; j < (ssize_t) channel_phash[0].number_colorspaces; j++) { alpha=channel_phash[channel].phash[j][i]; beta=reconstruct_phash[channel].phash[j][i]; if (normalize == MagickFalse) difference+=(beta-alpha)*(beta-alpha); else difference=sqrt((beta-alpha)*(beta-alpha)/ channel_phash[0].number_channels); } } distortion[channel]+=difference; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPerceptualHashDistortion) #endif distortion[CompositePixelChannel]+=difference; } /* Free resources. */ reconstruct_phash=(ChannelPerceptualHash *) RelinquishMagickMemory( reconstruct_phash); channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(channel_phash); return(MagickTrue); } static MagickBooleanType GetRootMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=sqrt(distortion[i]); return(status); } static MagickBooleanType GetStructuralSimilarityDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { #define SSIMRadius 5.0 #define SSIMSigma 1.5 #define SSIMBlocksize 8 #define SSIMK1 0.01 #define SSIMK2 0.03 #define SSIML 1.0 CacheView *image_view, *reconstruct_view; char geometry[MagickPathExtent]; const char *artifact; double area, c1, c2, radius, sigma; KernelInfo *kernel_info; MagickBooleanType status; ssize_t j; size_t columns, rows; ssize_t y; /* Compute structural similarity index @ https://en.wikipedia.org/wiki/Structural_similarity. */ radius=SSIMRadius; artifact=GetImageArtifact(image,"compare:ssim-radius"); if (artifact != (const char *) NULL) radius=StringToDouble(artifact,(char **) NULL); sigma=SSIMSigma; artifact=GetImageArtifact(image,"compare:ssim-sigma"); if (artifact != (const char *) NULL) sigma=StringToDouble(artifact,(char **) NULL); (void) FormatLocaleString(geometry,MagickPathExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); c1=pow(SSIMK1*SSIML,2.0); artifact=GetImageArtifact(image,"compare:ssim-k1"); if (artifact != (const char *) NULL) c1=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0); c2=pow(SSIMK2*SSIML,2.0); artifact=GetImageArtifact(image,"compare:ssim-k2"); if (artifact != (const char *) NULL) c2=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0); status=MagickTrue; area=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,reconstruct_image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; const Quantum *magick_restrict p, *magick_restrict q; ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) kernel_info->width/2L),y- ((ssize_t) kernel_info->height/2L),columns+kernel_info->width, kernel_info->height,exception); q=GetCacheViewVirtualPixels(reconstruct_view,-((ssize_t) kernel_info->width/ 2L),y-((ssize_t) kernel_info->height/2L),columns+kernel_info->width, kernel_info->height,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) memset(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double x_pixel_mu[MaxPixelChannels+1], x_pixel_sigma_squared[MaxPixelChannels+1], xy_sigma[MaxPixelChannels+1], y_pixel_mu[MaxPixelChannels+1], y_pixel_sigma_squared[MaxPixelChannels+1]; const Quantum *magick_restrict reference, *magick_restrict target; MagickRealType *k; ssize_t v; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } (void) memset(x_pixel_mu,0,sizeof(x_pixel_mu)); (void) memset(x_pixel_sigma_squared,0,sizeof(x_pixel_sigma_squared)); (void) memset(xy_sigma,0,sizeof(xy_sigma)); (void) memset(x_pixel_sigma_squared,0,sizeof(y_pixel_sigma_squared)); (void) memset(y_pixel_mu,0,sizeof(y_pixel_mu)); (void) memset(y_pixel_sigma_squared,0,sizeof(y_pixel_sigma_squared)); k=kernel_info->values; reference=p; target=q; for (v=0; v < (ssize_t) kernel_info->height; v++) { ssize_t u; for (u=0; u < (ssize_t) kernel_info->width; u++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double x_pixel, y_pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits( reconstruct_image,channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; x_pixel=QuantumScale*reference[i]; x_pixel_mu[i]+=(*k)*x_pixel; x_pixel_sigma_squared[i]+=(*k)*x_pixel*x_pixel; y_pixel=QuantumScale* GetPixelChannel(reconstruct_image,channel,target); y_pixel_mu[i]+=(*k)*y_pixel; y_pixel_sigma_squared[i]+=(*k)*y_pixel*y_pixel; xy_sigma[i]+=(*k)*x_pixel*y_pixel; } k++; reference+=GetPixelChannels(image); target+=GetPixelChannels(reconstruct_image); } reference+=GetPixelChannels(image)*columns; target+=GetPixelChannels(reconstruct_image)*columns; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double ssim, x_pixel_mu_squared, x_pixel_sigmas_squared, xy_mu, xy_sigmas, y_pixel_mu_squared, y_pixel_sigmas_squared; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits( reconstruct_image,channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; x_pixel_mu_squared=x_pixel_mu[i]*x_pixel_mu[i]; y_pixel_mu_squared=y_pixel_mu[i]*y_pixel_mu[i]; xy_mu=x_pixel_mu[i]*y_pixel_mu[i]; xy_sigmas=xy_sigma[i]-xy_mu; x_pixel_sigmas_squared=x_pixel_sigma_squared[i]-x_pixel_mu_squared; y_pixel_sigmas_squared=y_pixel_sigma_squared[i]-y_pixel_mu_squared; ssim=((2.0*xy_mu+c1)*(2.0*xy_sigmas+c2))/ ((x_pixel_mu_squared+y_pixel_mu_squared+c1)* (x_pixel_sigmas_squared+y_pixel_sigmas_squared+c2)); channel_distortion[i]+=ssim; channel_distortion[CompositePixelChannel]+=ssim; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif area++; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetStructuralSimilarityDistortion) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } image_view=DestroyCacheView(image_view); reconstruct_view=DestroyCacheView(reconstruct_view); for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0)) continue; distortion[j]/=area; } distortion[CompositePixelChannel]/=area; distortion[CompositePixelChannel]/=(double) GetImageChannels(image); kernel_info=DestroyKernelInfo(kernel_info); return(status); } static MagickBooleanType GetStructuralDisimilarityDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; ssize_t i; status=GetStructuralSimilarityDistortion(image,reconstruct_image, distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=(1.0-(distortion[i]))/2.0; return(status); } MagickExport MagickBooleanType GetImageDistortion(Image *image, const Image *reconstruct_image,const MetricType metric,double *distortion, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Get image distortion. */ length=MaxPixelChannels+1UL; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_distortion,0,length* sizeof(*channel_distortion)); switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetPerceptualHashDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralSimilarityErrorMetric: { status=GetStructuralSimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralDissimilarityErrorMetric: { status=GetStructuralDisimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } } *distortion=channel_distortion[CompositePixelChannel]; channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); (void) FormatImageProperty(image,"distortion","%.*g",GetMagickPrecision(), *distortion); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortions() compares the pixel channels of an image to a % reconstructed image and returns the specified distortion metric for each % channel. % % The format of the GetImageDistortions method is: % % double *GetImageDistortions(const Image *image, % const Image *reconstruct_image,const MetricType metric, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o exception: return any errors or warnings in this structure. % */ MagickExport double *GetImageDistortions(Image *image, const Image *reconstruct_image,const MetricType metric, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Get image distortion. */ length=MaxPixelChannels+1UL; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_distortion,0,length* sizeof(*channel_distortion)); status=MagickTrue; switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralSimilarityErrorMetric: { status=GetStructuralSimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralDissimilarityErrorMetric: { status=GetStructuralDisimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } } if (status == MagickFalse) { channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); return((double *) NULL); } return(channel_distortion); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e s E q u a l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImagesEqual() compare the pixels of two images and returns immediately % if any pixel is not identical. % % The format of the IsImagesEqual method is: % % MagickBooleanType IsImagesEqual(const Image *image, % const Image *reconstruct_image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsImagesEqual(const Image *image, const Image *reconstruct_image,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image, channel,q))); if (distance >= MagickEpsilon) break; } if (i < (ssize_t) GetPixelChannels(image)) break; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } if (x < (ssize_t) columns) break; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(y < (ssize_t) rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r M e t r i c % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColorMetric() measures the difference between colors at each pixel % location of two images. A value other than 0 means the colors match % exactly. Otherwise an error measure is computed by summing over all % pixels in an image the distance squared in RGB space between each image % pixel and its corresponding pixel in the reconstruct image. The error % measure is assigned to these image members: % % o mean_error_per_pixel: The mean error for any single pixel in % the image. % % o normalized_mean_error: The normalized mean quantization error for % any single pixel in the image. This distance measure is normalized to % a range between 0 and 1. It is independent of the range of red, green, % and blue values in the image. % % o normalized_maximum_error: The normalized maximum quantization % error for any single pixel in the image. This distance measure is % normalized to a range between 0 and 1. It is independent of the range % of red, green, and blue values in your image. % % A small normalized mean square error, accessed as % image->normalized_mean_error, suggests the images are very similar in % spatial layout and color. % % The format of the SetImageColorMetric method is: % % MagickBooleanType SetImageColorMetric(Image *image, % const Image *reconstruct_image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColorMetric(Image *image, const Image *reconstruct_image,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area, maximum_error, mean_error, mean_error_per_pixel; MagickBooleanType status; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); area=0.0; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image, channel,q))); if (distance >= MagickEpsilon) { mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; } area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=(double) (mean_error_per_pixel/area); image->error.normalized_mean_error=(double) (QuantumScale*QuantumScale* mean_error/area); image->error.normalized_maximum_error=(double) (QuantumScale*maximum_error); status=image->error.mean_error_per_pixel == 0.0 ? MagickTrue : MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i m i l a r i t y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SimilarityImage() compares the reference image of the image and returns the % best match offset. In addition, it returns a similarity image such that an % exact match location is completely white and if none of the pixels match, % black, otherwise some gray level in-between. % % The format of the SimilarityImageImage method is: % % Image *SimilarityImage(const Image *image,const Image *reference, % const MetricType metric,const double similarity_threshold, % RectangleInfo *offset,double *similarity,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reference: find an area of the image that closely resembles this image. % % o metric: the metric. % % o similarity_threshold: minimum distortion for (sub)image match. % % o offset: the best match offset of the reference image within the image. % % o similarity: the computed similarity between the images. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_HDRI_SUPPORT) && defined(MAGICKCORE_FFTW_DELEGATE) static Image *CrossCorrelationImage(const Image *alpha_image, const Image *beta_image,ExceptionInfo *exception) { Image *clone_image, *complex_conjugate, *complex_multiplication, *cross_correlation, *fft_images; /* Take the FFT of beta image. */ clone_image=CloneImage(beta_image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return(clone_image); (void) SetImageArtifact(clone_image,"fourier:normalize","inverse"); fft_images=ForwardFourierTransformImage(clone_image,MagickFalse, exception); clone_image=DestroyImageList(clone_image); if (fft_images == (Image *) NULL) return(fft_images); /* Take the complex conjugate of beta image. */ complex_conjugate=ComplexImages(fft_images,ConjugateComplexOperator, exception); fft_images=DestroyImageList(fft_images); if (complex_conjugate == (Image *) NULL) return(complex_conjugate); /* Take the FFT of the alpha image. */ clone_image=CloneImage(alpha_image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) { complex_conjugate=DestroyImageList(complex_conjugate); return(clone_image); } (void) SetImageArtifact(clone_image,"fourier:normalize","inverse"); fft_images=ForwardFourierTransformImage(clone_image,MagickFalse,exception); clone_image=DestroyImageList(clone_image); if (fft_images == (Image *) NULL) { complex_conjugate=DestroyImageList(complex_conjugate); return(fft_images); } complex_conjugate->next->next=fft_images; /* Do complex multiplication. */ (void) SetImageArtifact(complex_conjugate,"compose:clamp","false"); complex_multiplication=ComplexImages(complex_conjugate, MultiplyComplexOperator,exception); complex_conjugate=DestroyImageList(complex_conjugate); if (fft_images == (Image *) NULL) return(fft_images); /* Do the IFT and return the cross-correlation result. */ cross_correlation=InverseFourierTransformImage(complex_multiplication, complex_multiplication->next,MagickFalse,exception); complex_multiplication=DestroyImageList(complex_multiplication); return(cross_correlation); } static Image *NCCDivideImage(const Image *alpha_image,const Image *beta_image, ExceptionInfo *exception) { CacheView *alpha_view, *beta_view; Image *divide_image; MagickBooleanType status; ssize_t y; /* Divide one image into another. */ divide_image=CloneImage(alpha_image,0,0,MagickTrue,exception); if (divide_image == (Image *) NULL) return(divide_image); status=MagickTrue; alpha_view=AcquireAuthenticCacheView(divide_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(beta_image,divide_image,divide_image->rows,1) #endif for (y=0; y < (ssize_t) divide_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1, exception); q=GetCacheViewAuthenticPixels(alpha_view,0,y,divide_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) divide_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(divide_image); i++) { PixelChannel channel = GetPixelChannelChannel(divide_image,i); PixelTrait traits = GetPixelChannelTraits(divide_image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(p[i]) >= MagickEpsilon) q[i]*=PerceptibleReciprocal(QuantumScale*p[i]); } p+=GetPixelChannels(beta_image); q+=GetPixelChannels(divide_image); } if (SyncCacheViewAuthenticPixels(alpha_view,exception) == MagickFalse) status=MagickFalse; } beta_view=DestroyCacheView(beta_view); alpha_view=DestroyCacheView(alpha_view); if (status == MagickFalse) divide_image=DestroyImage(divide_image); return(divide_image); } static MagickBooleanType NCCMaximaImage(const Image *image,double *maxima, RectangleInfo *offset,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Identify the maxima value in the image and its location. */ status=MagickTrue; *maxima=0.0; offset->x=0; offset->y=0; 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 sum = 0.0; ssize_t channels = 0, 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; sum+=p[i]; channels++; } if ((channels != 0) && ((sum/channels) > *maxima)) { *maxima=sum/channels; offset->x=x; offset->y=y; } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType NCCMultiplyImage(Image *image,const double factor, const ChannelStatistics *channel_statistics,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Multiply each pixel by a factor. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { 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 (channel_statistics != (const ChannelStatistics *) NULL) q[i]*=QuantumScale*channel_statistics[channel].standard_deviation; q[i]*=factor; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static Image *NCCSquareImage(const Image *image,ExceptionInfo *exception) { CacheView *image_view; Image *square_image; MagickBooleanType status; ssize_t y; /* Square each pixel in the image. */ square_image=CloneImage(image,0,0,MagickTrue,exception); if (square_image == (Image *) NULL) return(square_image); status=MagickTrue; image_view=AcquireAuthenticCacheView(square_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(square_image,square_image,square_image->rows,1) #endif for (y=0; y < (ssize_t) square_image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,square_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) square_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(square_image); i++) { PixelChannel channel = GetPixelChannelChannel(square_image,i); PixelTrait traits = GetPixelChannelTraits(square_image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]*=QuantumScale*q[i]; } q+=GetPixelChannels(square_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) square_image=DestroyImage(square_image); return(square_image); } static Image *NCCSubtractImageMean(const Image *alpha_image, const Image *beta_image,const ChannelStatistics *channel_statistics, ExceptionInfo *exception) { CacheView *beta_view, *image_view; Image *gamma_image; MagickBooleanType status; ssize_t y; /* Subtract the image mean and pad. */ gamma_image=CloneImage(beta_image,alpha_image->columns,alpha_image->rows, MagickTrue,exception); if (gamma_image == (Image *) NULL) return(gamma_image); status=MagickTrue; image_view=AcquireAuthenticCacheView(gamma_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(beta_image,gamma_image,gamma_image->rows,1) #endif for (y=0; y < (ssize_t) gamma_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,0,y,gamma_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) gamma_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(gamma_image); i++) { PixelChannel channel = GetPixelChannelChannel(gamma_image,i); PixelTrait traits = GetPixelChannelTraits(gamma_image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((x >= (ssize_t) beta_image->columns) || (y >= (ssize_t) beta_image->rows)) q[i]=(Quantum) 0; else q[i]=p[i]-channel_statistics[channel].mean; } p+=GetPixelChannels(beta_image); q+=GetPixelChannels(gamma_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } beta_view=DestroyCacheView(beta_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) gamma_image=DestroyImage(gamma_image); return(gamma_image); } static Image *NCCUnityImage(const Image *alpha_image,const Image *beta_image, ExceptionInfo *exception) { CacheView *image_view; Image *unity_image; MagickBooleanType status; ssize_t y; /* Create a padded unity image. */ unity_image=CloneImage(alpha_image,alpha_image->columns,alpha_image->rows, MagickTrue,exception); if (unity_image == (Image *) NULL) return(unity_image); status=MagickTrue; image_view=AcquireAuthenticCacheView(unity_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(unity_image,unity_image,unity_image->rows,1) #endif for (y=0; y < (ssize_t) unity_image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,unity_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) unity_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(unity_image); i++) { PixelChannel channel = GetPixelChannelChannel(unity_image,i); PixelTrait traits = GetPixelChannelTraits(unity_image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=QuantumRange; if ((x >= (ssize_t) beta_image->columns) || (y >= (ssize_t) beta_image->rows)) q[i]=(Quantum) 0; } q+=GetPixelChannels(unity_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) unity_image=DestroyImage(unity_image); return(unity_image); } static Image *NCCVarianceImage(Image *alpha_image,const Image *beta_image, ExceptionInfo *exception) { CacheView *beta_view, *image_view; Image *variance_image; MagickBooleanType status; ssize_t y; /* Compute the variance of the two images. */ variance_image=CloneImage(alpha_image,0,0,MagickTrue,exception); if (variance_image == (Image *) NULL) return(variance_image); status=MagickTrue; image_view=AcquireAuthenticCacheView(variance_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(beta_image,variance_image,variance_image->rows,1) #endif for (y=0; y < (ssize_t) variance_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,0,y,variance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) variance_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(variance_image); i++) { PixelChannel channel = GetPixelChannelChannel(variance_image,i); PixelTrait traits = GetPixelChannelTraits(variance_image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum((QuantumRange*sqrt(fabs((double) QuantumScale* (q[i]-p[i])))))/sqrt((double) QuantumRange); } p+=GetPixelChannels(beta_image); q+=GetPixelChannels(variance_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } beta_view=DestroyCacheView(beta_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) variance_image=DestroyImage(variance_image); return(variance_image); } static Image *NCCSimilarityImage(const Image *image,const Image *reference, const MetricType metric,const double similarity_threshold, RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception) { #define DestroySimilarityResources() \ { \ if (channel_statistics != (ChannelStatistics *) NULL) \ channel_statistics=(ChannelStatistics *) \ RelinquishMagickMemory(channel_statistics); \ if (beta_image != (Image *) NULL) \ beta_image=DestroyImage(beta_image); \ if (gamma_image != (Image *) NULL) \ gamma_image=DestroyImage(gamma_image); \ if (ncc_image != (Image *) NULL) \ ncc_image=DestroyImage(ncc_image); \ if (normalize_image != (Image *) NULL) \ normalize_image=DestroyImage(normalize_image); \ if (square_image != (Image *) NULL) \ square_image=DestroyImage(square_image); \ if (unity_image != (Image *) NULL) \ unity_image=DestroyImage(unity_image); \ } #define ThrowSimilarityException() \ { \ DestroySimilarityResources() \ return((Image *) NULL); \ } ChannelStatistics *channel_statistics = (ChannelStatistics *) NULL; double maxima = 0.0; Image *beta_image = (Image *) NULL, *correlation_image = (Image *) NULL, *gamma_image = (Image *) NULL, *ncc_image = (Image *) NULL, *normalize_image = (Image *) NULL, *square_image = (Image *) NULL, *unity_image = (Image *) NULL; MagickBooleanType status; RectangleInfo geometry; /* Accelerated correlation-based image similary using FFT local statistics. Contributed by Fred Weinhaus. */ square_image=NCCSquareImage(image,exception); if (square_image == (Image *) NULL) ThrowSimilarityException(); unity_image=NCCUnityImage(image,reference,exception); if (unity_image == (Image *) NULL) ThrowSimilarityException(); /* Compute the cross correlation of the square and unity images. */ ncc_image=CrossCorrelationImage(square_image,unity_image,exception); square_image=DestroyImage(square_image); \ if (ncc_image == (Image *) NULL) ThrowSimilarityException(); status=NCCMultiplyImage(ncc_image,(double) QuantumRange*reference->columns* reference->rows,(const ChannelStatistics *) NULL,exception); if (status == MagickFalse) ThrowSimilarityException(); /* Compute the cross correlation of the source and unity images. */ gamma_image=CrossCorrelationImage(image,unity_image,exception); unity_image=DestroyImage(unity_image); if (gamma_image == (Image *) NULL) ThrowSimilarityException(); square_image=NCCSquareImage(gamma_image,exception); gamma_image=DestroyImage(gamma_image); status=NCCMultiplyImage(square_image,(double) QuantumRange, (const ChannelStatistics *) NULL,exception); if (status == MagickFalse) ThrowSimilarityException(); /* Compute the variance of the two images. */ gamma_image=NCCVarianceImage(ncc_image,square_image,exception); square_image=DestroyImage(square_image); ncc_image=DestroyImage(ncc_image); if (gamma_image == (Image *) NULL) ThrowSimilarityException(); channel_statistics=GetImageStatistics(reference,exception); if (channel_statistics == (ChannelStatistics *) NULL) ThrowSimilarityException(); /* Subtract the image mean. */ status=NCCMultiplyImage(gamma_image,1.0,channel_statistics,exception); if (status == MagickFalse) ThrowSimilarityException(); normalize_image=NCCSubtractImageMean(image,reference,channel_statistics, exception); if (normalize_image == (Image *) NULL) ThrowSimilarityException(); ncc_image=CrossCorrelationImage(image,normalize_image,exception); normalize_image=DestroyImage(normalize_image); if (ncc_image == (Image *) NULL) ThrowSimilarityException(); /* Divide the two images. */ beta_image=NCCDivideImage(ncc_image,gamma_image,exception); ncc_image=DestroyImage(ncc_image); gamma_image=DestroyImage(gamma_image); if (beta_image == (Image *) NULL) ThrowSimilarityException(); (void) ResetImagePage(beta_image,"0x0+0+0"); SetGeometry(image,&geometry); geometry.width=image->columns-reference->columns; geometry.height=image->rows-reference->rows; /* Crop padding. */ correlation_image=CropImage(beta_image,&geometry,exception); beta_image=DestroyImage(beta_image); if (correlation_image == (Image *) NULL) ThrowSimilarityException(); (void) ResetImagePage(correlation_image,"0x0+0+0"); /* Identify the maxima value in the image and its location. */ status=GrayscaleImage(correlation_image,AveragePixelIntensityMethod, exception); if (status == MagickFalse) ThrowSimilarityException(); status=NCCMaximaImage(correlation_image,&maxima,offset,exception); if (status == MagickFalse) { correlation_image=DestroyImage(correlation_image); ThrowSimilarityException(); } *similarity_metric=1.0-QuantumScale*maxima; DestroySimilarityResources(); return(correlation_image); } #endif static double GetSimilarityMetric(const Image *image,const Image *reference, const MetricType metric,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { double distortion; Image *similarity_image; MagickBooleanType status; RectangleInfo geometry; SetGeometry(reference,&geometry); geometry.x=x_offset; geometry.y=y_offset; similarity_image=CropImage(image,&geometry,exception); if (similarity_image == (Image *) NULL) return(0.0); distortion=0.0; status=GetImageDistortion(similarity_image,reference,metric,&distortion, exception); similarity_image=DestroyImage(similarity_image); if (status == MagickFalse) return(0.0); return(distortion); } MagickExport Image *SimilarityImage(const Image *image,const Image *reference, const MetricType metric,const double similarity_threshold, RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *similarity_view; Image *similarity_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; 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); assert(offset != (RectangleInfo *) NULL); SetGeometry(reference,offset); *similarity_metric=MagickMaximumValue; #if defined(MAGICKCORE_HDRI_SUPPORT) && defined(MAGICKCORE_FFTW_DELEGATE) { const char *artifact = GetImageArtifact(image,"compare:accelerate-ncc"); MagickBooleanType accelerate = (artifact != (const char *) NULL) && (IsStringTrue(artifact) == MagickFalse) ? MagickFalse : MagickTrue; if ((accelerate != MagickFalse) && (metric == NormalizedCrossCorrelationErrorMetric)) { similarity_image=NCCSimilarityImage(image,reference,metric, similarity_threshold,offset,similarity_metric,exception); return(similarity_image); } } #endif similarity_image=CloneImage(image,image->columns-reference->columns+1, image->rows-reference->rows+1,MagickTrue,exception); if (similarity_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(similarity_image,DirectClass,exception); if (status == MagickFalse) { similarity_image=DestroyImage(similarity_image); return((Image *) NULL); } (void) SetImageAlphaChannel(similarity_image,DeactivateAlphaChannel, exception); /* Measure similarity of reference image against image. */ status=MagickTrue; progress=0; similarity_view=AcquireAuthenticCacheView(similarity_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ shared(progress,status,similarity_metric) \ magick_number_threads(image,image,image->rows-reference->rows+1,1) #endif for (y=0; y < (ssize_t) (image->rows-reference->rows+1); y++) { double similarity; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) continue; q=GetCacheViewAuthenticPixels(similarity_view,0,y,similarity_image->columns, 1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) (image->columns-reference->columns+1); x++) { ssize_t i; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) break; similarity=GetSimilarityMetric(image,reference,metric,x,y,exception); if ((metric == NormalizedCrossCorrelationErrorMetric) || (metric == UndefinedErrorMetric)) similarity=1.0-similarity; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SimilarityImage) #endif if (similarity < *similarity_metric) { offset->x=x; offset->y=y; *similarity_metric=similarity; } if (metric == PerceptualHashErrorMetric) similarity=MagickMin(0.01*similarity,1.0); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait similarity_traits=GetPixelChannelTraits(similarity_image, channel); if ((traits == UndefinedPixelTrait) || (similarity_traits == UndefinedPixelTrait) || ((similarity_traits & UpdatePixelTrait) == 0)) continue; SetPixelChannel(similarity_image,channel,ClampToQuantum(QuantumRange- QuantumRange*similarity),q); } q+=GetPixelChannels(similarity_image); } if (SyncCacheViewAuthenticPixels(similarity_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,SimilarityImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } similarity_view=DestroyCacheView(similarity_view); if (status == MagickFalse) similarity_image=DestroyImage(similarity_image); return(similarity_image); }
nco_ply_lst.c
/* $Header$ */ /* Purpose: Functions that manipulate lists of polygons */ /* Copyright (C) 2018--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ #include "nco_ply_lst.h" void nco_poly_re_org_lst( /* for each poly_sct* in list re-order points so that first point is the leftermost point */ poly_sct **pl_lst, int arr_nbr) { int idx=0; int jdx=0; int max_crn_nbr=0; double *lcl_dp_x; double *lcl_dp_y; /* max crn_nbr */ for(idx=0 ; idx<arr_nbr ;idx++) if( pl_lst[idx]->crn_nbr > max_crn_nbr ) max_crn_nbr = pl_lst[idx]->crn_nbr; lcl_dp_x=(double*)nco_calloc(max_crn_nbr, sizeof(double)); lcl_dp_y=(double*)nco_calloc(max_crn_nbr, sizeof(double)); for(idx=0; idx<arr_nbr; idx++) { int lcl_min=0; int crn_nbr=pl_lst[idx]->crn_nbr; double x_min=1.0e-30; /* de-reference */ poly_sct *pl=pl_lst[idx]; /* find index of min X value */ for(jdx=0; jdx<crn_nbr; jdx++) if( pl->dp_x[jdx] < x_min ) { x_min=pl->dp_x[jdx]; lcl_min=jdx;} /* first point already x_min so do nothing */ if( lcl_min == 0) continue; for(jdx=0; jdx<crn_nbr; jdx++) { lcl_dp_x[jdx]=pl->dp_x[(jdx+lcl_min)%crn_nbr]; lcl_dp_y[jdx]=pl->dp_y[(jdx+lcl_min)%crn_nbr]; } /* copy over values */ memcpy(pl->dp_x, lcl_dp_x, (size_t)crn_nbr*sizeof(double)); memcpy(pl->dp_y, lcl_dp_y, (size_t)crn_nbr*sizeof(double)); } lcl_dp_x=(double*)nco_free(lcl_dp_x); lcl_dp_y=(double*)nco_free(lcl_dp_y); return; } poly_sct ** /* [O] [nbr] size of array */ nco_poly_lst_mk( double *area, /* I [sr] Area of source grid */ int *msk, /* I [flg] Mask on source grid */ double *lat_ctr, /* I [dgr] Latitude centers of source grid */ double *lon_ctr, /* I [dgr] Longitude centers of source grid */ double *lat_crn, /* I [dgr] Latitude corners of source grid */ double *lon_crn, /* I [dgr] Longitude corners of source grid */ size_t grd_sz, /* I [nbr] Number of elements in single layer of source grid */ long grd_crn_nbr, /* I [nbr] Maximum number of corners in source gridcell */ nco_grd_lon_typ_enm grd_lon_typ, /* I [num] if not nil then split cells that straddle Greenwich or Dateline */ poly_typ_enm pl_typ, int *pl_nbr) { const char fnc_nm[]="nco_poly_lst_mk()"; int idx=0; int idx_cnt=0; int cnt_wrp_good=0; nco_bool bwrp; double *lat_ptr=lat_crn; double *lon_ptr=lon_crn; /* buffers used in nco-poly_re_org() */ double lcl_dp_x[VP_MAX]={0}; double lcl_dp_y[VP_MAX]={0}; poly_sct *pl; poly_sct *pl_wrp_left; poly_sct *pl_wrp_right; poly_sct **pl_lst; /* start with twice the grid size as we may be splitting the cells along the Greenwich meridian or dateline */ /* realloc at the end */ pl_lst=(poly_sct**)nco_malloc( sizeof (poly_sct*) * grd_sz *2 ); // printf("About to print poly sct grd_sz=%d grd_crn_nbr=%d\n", grd_sz, grd_crn_nbr); for(idx=0;idx<grd_sz; idx++) { /* check mask and area */ if( msk[idx]==0 || area[idx] == 0.0) continue; pl=nco_poly_init_lst(pl_typ, grd_crn_nbr,0, idx, lon_ptr, lat_ptr); lon_ptr+=(size_t)grd_crn_nbr; lat_ptr+=(size_t)grd_crn_nbr; /* if poly is less than a triangle then null is returned*/ if(!pl) continue; /* add min max */ nco_poly_minmax_add(pl, grd_lon_typ, False); nco_poly_re_org(pl, lcl_dp_x, lcl_dp_y); /* use Charlie's formula */ nco_poly_area_add(pl); //if(pl->dp_x_minmax[0] <0.0 || (pl->dp_x_minmax[1] - pl->dp_x_minmax[0]) > 30 ) if( !(pl->dp_x_minmax[1] - pl->dp_x_minmax[0] < 180.0 && lon_ctr[idx] >= pl->dp_x_minmax[0] && lon_ctr[idx] <= pl->dp_x_minmax[1] )) { (void)fprintf(stdout, "/***%s: %s: invalid polygon to follow *******?", nco_prg_nm_get(), fnc_nm); nco_poly_prn(pl, 0); pl=nco_poly_free(pl); continue; } //fprintf(stdout,"/***** input polygon pl lon center=%f convex=%s\n ********************/\n", lon_ctr[idx], (nco_poly_is_convex(pl) ? "True": "False") ); //nco_poly_prn(pl, 0); /* check for wrapping -center outside min/max range */ bwrp=( lon_ctr[idx] < pl->dp_x_minmax[0] || lon_ctr[idx] > pl->dp_x_minmax[1] ); if( grd_lon_typ == nco_grd_lon_nil || grd_lon_typ == nco_grd_lon_unk ) { if( !bwrp ) { pl_lst[idx_cnt++]=pl; } else { (void)fprintf(stdout, "%s: polygon(%d) wrapped - but grd_lon_typ not specified \n", nco_prg_nm_get(), idx); (void)fprintf(stdout, "/*******************************************/\n"); pl=nco_poly_free(pl); } continue; } /* if we are here then grd_lon_typ specifys a grid type */ if( !bwrp) { pl_lst[idx_cnt++]=pl; } /* cell width exceeds max so assume wrapping */ else if( nco_poly_wrp_splt(pl, grd_lon_typ, &pl_wrp_left, &pl_wrp_right ) == NCO_NOERR ) { fprintf(stdout,"/***** pl, wrp_left, wrp_right ********************/\n"); if(pl_wrp_left) { nco_poly_re_org(pl_wrp_left, lcl_dp_x, lcl_dp_y); pl_lst[idx_cnt++]=pl_wrp_left; nco_poly_prn(pl_wrp_left, 2); } if(pl_wrp_right) { nco_poly_re_org(pl_wrp_right, lcl_dp_x, lcl_dp_y); pl_lst[idx_cnt++]=pl_wrp_right; nco_poly_prn(pl_wrp_right, 2); } pl=nco_poly_free(pl); fprintf(stdout,"/**********************************/\n"); cnt_wrp_good++; } else { if(nco_dbg_lvl_get() >= nco_dbg_std ){ (void)fprintf(stdout, "%s: split wrapping didn't work on this polygon(%d)\n", nco_prg_nm_get(), idx ); (void)fprintf(stdout, "/********************************/\n"); } pl=nco_poly_free(pl); } } if(nco_dbg_lvl_get() >= nco_dbg_std ) (void)fprintf(stdout, "%s: %s size input list(%lu), size output list(%d), num of split polygons(%d)\n", nco_prg_nm_get(),fnc_nm, grd_sz, idx_cnt, cnt_wrp_good); pl_lst=(poly_sct**)nco_realloc( pl_lst, (size_t)idx_cnt * sizeof (poly_sct*) ); *pl_nbr=idx_cnt; return pl_lst; } poly_sct ** /* [O] [nbr] size of array */ nco_poly_lst_mk_rll( double *area, /* I [sr] Area of source grid */ int *msk, /* I [flg] Mask on source grid */ double *lat_ctr, /* I [dgr] Latitude centers of source grid */ double *lon_ctr, /* I [dgr] Longitude centers of source grid */ double *lat_crn, /* I [dgr] Latitude corners of source grid */ double *lon_crn, /* I [dgr] Longitude corners of source grid */ size_t grd_sz, /* I [nbr] Number of elements in single layer of source grid */ long grd_crn_nbr, /* I [nbr] Maximum number of corners in source gridcell */ nco_grd_lon_typ_enm grd_lon_typ) /* I [num] */ { int idx=0; int wrp_cnt=0; int wrp_y_cnt=0; int msk_cnt=0; const char fnc_nm[]="nco_poly_lst_mk_rll()"; nco_bool bwrp; /* no polar caps on a RLL grid */ nco_bool bchk_caps=False; double tot_area=0.0; double *lat_ptr=lat_crn; double *lon_ptr=lon_crn; poly_sct *pl=(poly_sct*)NULL_CEWI; /* contains plain struct sct with bmsk=False; */ poly_sct *pl_msk=((poly_sct*)NULL_CEWI); poly_sct **pl_lst; /* list size is grd_sz - invalid or masked polygons are repesented by a poly_sct->bmsk=False */ pl_lst=(poly_sct**)nco_malloc( sizeof (poly_sct*) * grd_sz); pl_msk=nco_poly_init(); pl_msk->bmsk=False; /* filter out wrapped lon cells */ if( grd_lon_typ == nco_grd_lon_nil || grd_lon_typ == nco_grd_lon_unk || grd_lon_typ == nco_grd_lon_bb ) bwrp=False; else bwrp=True; // printf("About to print poly sct grd_sz=%d grd_crn_nbr=%d\n", grd_sz, grd_crn_nbr); for(idx=0;idx<grd_sz; idx++) { /* check mask and area */ if( msk[idx]==0 || area[idx] == 0.0 ) { pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } pl=nco_poly_init_lst(poly_rll, grd_crn_nbr,0, idx, lon_ptr, lat_ptr); lon_ptr+=(size_t)grd_crn_nbr; lat_ptr+=(size_t)grd_crn_nbr; /* if poly is less than a triangle then null is returned*/ if(!pl ) { if(nco_dbg_lvl_get()>= nco_dbg_dev) fprintf(stderr, "%s(): WARNING cell(id=%d) less than a triange\n", fnc_nm, idx); pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } /* add centroid from input */ pl->dp_x_ctr=lon_ctr[idx]; pl->dp_y_ctr=lat_ctr[idx]; /* pop shp */ nco_poly_shp_pop(pl); /* add min max */ nco_poly_minmax_add(pl, grd_lon_typ, bchk_caps); /* if coords cannot deal with wrapping */ if( pl->bwrp && bwrp==False ) { pl=nco_poly_free(pl); pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } /* The area of an RLL grid needs to be re-calculated as we have to take account of lines of latitude as great circles */ nco_poly_area_add(pl); /* area NOT set so add to the area - nb this will be eventually written to the map file in nco_map_mk */ if(area[idx]==-1.0) area[idx]=pl->area; /* simple center of a rll cell - should always be inside of polygon */ nco_poly_ctr_add(pl, grd_lon_typ); if(nco_dbg_lvl_get()>= nco_dbg_dev ) if(pl->bwrp) nco_poly_prn(pl,0); /* for debugging */ tot_area+=pl->area; /* for debugging total number of wrapped cells */ wrp_cnt+=pl->bwrp; pl_lst[idx]=pl; } if(nco_dbg_lvl_get() >= nco_dbg_dev ) (void)fprintf(stderr, "%s: %s size input list(%lu), size output list(%lu) total area=%.15e num wrapped= %d num caps=%d num masked=%d\n", nco_prg_nm_get(),fnc_nm, grd_sz, grd_sz, tot_area, wrp_cnt, wrp_y_cnt, msk_cnt); pl_msk=nco_poly_free(pl_msk); return pl_lst; } poly_sct ** /* [O] [nbr] size of array */ nco_poly_lst_mk_sph( double *area, /* I [sr] Area of source grid */ int *msk, /* I [flg] Mask on source grid */ double *lat_ctr, /* I [dgr] Latitude centers of source grid */ double *lon_ctr, /* I [dgr] Longitude centers of source grid */ double *lat_crn, /* I [dgr] Latitude corners of source grid */ double *lon_crn, /* I [dgr] Longitude corners of source grid */ size_t grd_sz, /* I [nbr] Number of elements in single layer of source grid */ long grd_crn_nbr, /* I [nbr] Maximum number of corners in source gridcell */ nco_grd_lon_typ_enm grd_lon_typ) /* I [num] */ { int idx=0; int wrp_cnt=0; int wrp_y_cnt=0; int msk_cnt=0; const char fnc_nm[]="nco_poly_lst_mk_sph()"; nco_bool bwrp; /* check to see if cell is a polar cap */ nco_bool bchk_caps=True; double tot_area=0.0; double *lat_ptr=lat_crn; double *lon_ptr=lon_crn; /* buffers used in nco-poly_re_org() */ poly_sct *pl=(poly_sct*)NULL_CEWI; /* contains plain struct sct with bmsk=False; */ poly_sct *pl_msk=((poly_sct*)NULL_CEWI); poly_sct **pl_lst; /* list size is grd_sz - invalid or masked polygons are repesented by a poly_sct->bmsk=False */ pl_lst=(poly_sct**)nco_malloc( sizeof (poly_sct*) * grd_sz); pl_msk=nco_poly_init(); pl_msk->bmsk=False; /* filter out wrapped lon cells */ if( grd_lon_typ == nco_grd_lon_nil || grd_lon_typ == nco_grd_lon_unk || grd_lon_typ == nco_grd_lon_bb ) bwrp=False; else bwrp=True; // printf("About to print poly sct grd_sz=%d grd_crn_nbr=%d\n", grd_sz, grd_crn_nbr); for(idx=0;idx<grd_sz; idx++) { /* check mask and area */ if( msk[idx]==0 || area[idx] == 0.0 ) { pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } pl=nco_poly_init_lst(poly_sph, grd_crn_nbr,0, idx, lon_ptr, lat_ptr); lon_ptr+=(size_t)grd_crn_nbr; lat_ptr+=(size_t)grd_crn_nbr; /* if poly is less than a triangle then null is returned*/ if(!pl ) { if(nco_dbg_lvl_get()>= nco_dbg_dev) fprintf(stderr, "%s(): WARNING cell(id=%d) less than a triange\n", fnc_nm, idx); pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } /* add centroid from input */ pl->dp_x_ctr=lon_ctr[idx]; pl->dp_y_ctr=lat_ctr[idx]; /* pop shp */ nco_poly_shp_pop(pl); /* add min max */ nco_poly_minmax_add(pl, grd_lon_typ, bchk_caps); /* if coords cannot deal with wrapping */ if( pl->bwrp && bwrp==False ) { pl=nco_poly_free(pl); pl_lst[idx]= nco_poly_dpl(pl_msk); msk_cnt++; continue; } /* The area of an RLL grid needs to be re-calculated as we have to take account of lines of latitude as great circles */ nco_poly_area_add(pl); /* area NOT set so add to the area - nb this will be eventually written to the map file in nco_map_mk */ if(area[idx]==-1.0) area[idx]=pl->area; /* fxm:2019-06-07 - there is a problem using the polygon center as a control point as * for some RLL grids the center of a polar triangle can be the pole */ /* The centroid can be outside of a convex polygon * for nco_sph_intersect_pre() to work correctly it requires a point INSIDE the convex polygon * So we use a custom function : * just remember FROM HERE on that the pl->dp_x_ctr, pl->dp_y_ctr iS NOT the Centroid * */ /* if(nco_sph_inside_mk(pl,pControl )) { pl->dp_x_ctr=R2D(pControl[3]); pl->dp_y_ctr=R2D(pControl[4]); } else nco_poly_ctr_add(pl, grd_lon_typ); */ if(nco_dbg_lvl_get()>= nco_dbg_dev ) if(pl->bwrp) nco_poly_prn(pl,0); /* for debugging */ tot_area+=pl->area; /* for debugging total number of wrapped cells */ wrp_cnt+=pl->bwrp; wrp_y_cnt+=pl->bwrp_y; pl_lst[idx]=pl; } if(nco_dbg_lvl_get() >= nco_dbg_dev ) (void)fprintf(stderr, "%s: %s size input list(%lu), size output list(%lu) total area=%.15e num wrapped= %d num caps=%d num masked=%d\n", nco_prg_nm_get(),fnc_nm, grd_sz, grd_sz, tot_area, wrp_cnt, wrp_y_cnt, msk_cnt); pl_msk=nco_poly_free(pl_msk); return pl_lst; } poly_sct ** nco_poly_lst_free( poly_sct **pl_lst, int arr_nbr) { int idx; for(idx=0; idx<arr_nbr; idx++) pl_lst[idx]=nco_poly_free(pl_lst[idx]); pl_lst=(poly_sct**)nco_free(pl_lst); return pl_lst; } void nco_poly_set_priority( int nbr_lst, KDPriority *list){ int idx; for(idx=0;idx<nbr_lst;idx++){ list[idx].dist = 1.1; list[idx].elem = (KDElem*)NULL; } return ; } poly_sct ** nco_poly_lst_mk_vrl_crt( /* create overlap mesh for crt polygons */ poly_sct **pl_lst_in, int pl_cnt_in, KDTree *rtree, int *pl_cnt_vrl_ret){ /* just duplicate output list to overlap */ size_t idx; size_t jdx; int max_nbr_vrl=1000; int pl_cnt_vrl=0; //nco_bool bSort=True; const char fnc_nm[]="nco_poly_mk_vrl_crt()"; /* buffers used in nco-poly_re_org() */ double lcl_dp_x[VP_MAX]={0}; double lcl_dp_y[VP_MAX]={0}; kd_box size; poly_sct ** pl_lst_vrl=NULL_CEWI; KDPriority *list; list = (KDPriority *)nco_calloc(sizeof(KDPriority),(size_t)max_nbr_vrl); printf("INFO - entered function nco_poly_mk_vrl\n"); /* start main loop over input polygons */ for(idx=0 ; idx<pl_cnt_in ;idx++ ) { int cnt_vrl=0; int cnt_vrl_on=0; (void)nco_poly_set_priority(max_nbr_vrl,list); /* get bounds of polygon in */ size[KD_LEFT] = pl_lst_in[idx]->dp_x_minmax[0]; size[KD_RIGHT] = pl_lst_in[idx]->dp_x_minmax[1]; size[KD_BOTTOM] = pl_lst_in[idx]->dp_y_minmax[0]; size[KD_TOP] = pl_lst_in[idx]->dp_y_minmax[1]; /* find overlapping polygons */ // cnt_vrl=kd_nearest_intersect(rtree, size, max_nbr_vrl,list,bSort ); /* nco_poly_prn(2, pl_lst_in[idx] ); */ for(jdx=0; jdx <cnt_vrl ;jdx++){ poly_sct *pl_vrl=(poly_sct*)NULL_CEWI; poly_sct *pl_out=(poly_sct*)list[jdx].elem->item; ; // nco_poly_prn(2, pl_out); /* check for polygon in polygon first */ if( nco_crt_poly_in_poly(pl_lst_in[idx], pl_out) == pl_out->crn_nbr ) { //fprintf(stderr,"%s: using poly_in_poly()\n", fnc_nm); pl_vrl=nco_poly_dpl(pl_out); } else pl_vrl= nco_poly_vrl_do(pl_lst_in[idx], pl_out, 0, (char*)NULL); if(pl_vrl){ nco_poly_re_org(pl_vrl, lcl_dp_x, lcl_dp_y); /* add area */ nco_poly_area_add(pl_vrl); /* shp not needed */ nco_poly_shp_free(pl_vrl); pl_lst_vrl=(poly_sct**)nco_realloc(pl_lst_vrl, sizeof(poly_sct*) * (pl_cnt_vrl+1)); pl_lst_vrl[pl_cnt_vrl]=pl_vrl; pl_cnt_vrl++; cnt_vrl_on++; if(nco_poly_is_convex(pl_vrl) == False ) { fprintf(stderr,"%s: %s vrl polygon convex=0 vrl ,in convex=%d ,out convex=%d\n", nco_prg_nm_get(), fnc_nm, nco_poly_is_convex(pl_lst_in[idx]), nco_poly_is_convex(pl_out) ); nco_poly_prn(pl_vrl, 2); nco_poly_prn(pl_lst_in[idx], 2); nco_poly_prn(pl_out, 2); } //fprintf(stderr,"Overlap polygon to follow\n"); //nco_poly_prn(2, pl_vrl); } } if( nco_dbg_lvl_get() >= nco_dbg_dev ) (void) fprintf(stderr, "%s: total overlaps=%d for polygon %lu - potential overlaps=%d actual overlaps=%d\n", nco_prg_nm_get(), pl_cnt_vrl, idx, cnt_vrl, cnt_vrl_on); } list = (KDPriority *)nco_free(list); /* return size of list */ *pl_cnt_vrl_ret=pl_cnt_vrl; return pl_lst_vrl; } void ** nco_poly_lst_mk_vrl( /* create overlap mesh for sph polygons */ poly_sct **pl_lst_in, int pl_cnt_in, nco_grd_lon_typ_enm grd_lon_typ, poly_typ_enm pl_typ, KDTree **tree, int nbr_tr, int lst_out_typ, int *pl_cnt_vrl_ret){ /* just duplicate output list to overlap */ const char fnc_nm[]="nco_poly_lst_mk_vrl()"; nco_bool bDirtyRats=False; nco_bool bSort=True; int pl_cnt_vrl=0; int thr_idx=0; int pl_cnt_dbg=0; int tot_nan_cnt=0; int tot_wrp_cnt=0; /* approx number of input cells each thread will process */ int thr_quota; /* reporting step */ int thr_quota_step; size_t idx; int lcl_thr_nbr; omp_mem_sct *mem_lst=NULL_CEWI; double tot_area=0.0; void** void_lst_vrl=NULL_CEWI; poly_sct** pl_lst_dbg=NULL_CEWI; FILE * const fp_stderr=stderr; lcl_thr_nbr=omp_get_max_threads(); mem_lst=(omp_mem_sct*)nco_malloc(sizeof(omp_mem_sct)*lcl_thr_nbr); for(idx=0;idx<lcl_thr_nbr;idx++) { mem_lst[idx].pl_lst=NULL_CEWI; mem_lst[idx].wgt_lst=NULL_CEWI; mem_lst[idx].blk_nbr=0; mem_lst[idx].pl_cnt=0; mem_lst[idx].kd_list=(KDPriority *)nco_calloc(sizeof(KDPriority),(size_t)(NCO_VRL_BLOCKSIZE)); mem_lst[idx].kd_cnt=0; mem_lst[idx].kd_blk_nbr=1; mem_lst[idx].idx_cnt=0; } thr_quota=pl_cnt_in/lcl_thr_nbr; thr_quota_step=thr_quota/20; if( thr_quota_step <2000 ) thr_quota_step=2000; /* NB: "OpenMP notes" section of nco_rgr.c has detailed discussion of these settings Henry, please keep the variables in alphabetical order within a clause and remember to update Intel */ #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ #endif /* !__GNUC__ */ #if defined(__INTEL_COMPILER) # pragma omp parallel for private(idx,thr_idx) schedule(dynamic,40) shared(bDirtyRats,bSort,grd_lon_typ,nbr_tr,pl_cnt_dbg,pl_typ,tree,tot_nan_cnt,tot_wrp_cnt) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) private(idx,thr_idx) shared(bDirtyRats,bSort,grd_lon_typ,nbr_tr,pl_cnt_dbg,pl_typ,tree,tot_nan_cnt,tot_wrp_cnt) # else /* !old g++ */ # pragma omp parallel for private(idx,thr_idx) schedule(dynamic,40) shared(bDirtyRats,bSort,grd_lon_typ,nbr_tr,pl_cnt_dbg,pl_typ,tree,tot_nan_cnt,tot_wrp_cnt) # endif /* !old g++ */ #endif /* !__INTEL_COMPILER */ for(idx=0 ; idx<pl_cnt_in ;idx++ ) { nco_bool bSplit=False; int vrl_cnt = 0; int vrl_cnt_on = 0; int nan_cnt=0; int wrp_cnt=0; size_t jdx; double vrl_area = 0.0; kd_box size1; kd_box size2; // (void) nco_poly_set_priority(max_nbr_vrl, list); thr_idx=omp_get_thread_num(); if (0 && nco_dbg_lvl_get() >= nco_dbg_dev) fprintf(fp_stderr, "%s(): idx=%lu thr=%d\n",fnc_nm, idx, thr_idx); if(pl_lst_in[idx]->bmsk==False) goto cont_msk; /* need to iterate mem_lst diagnostics at end of loop*/ mem_lst[thr_idx].kd_cnt=0; if(mem_lst[thr_idx].kd_blk_nbr >1) { mem_lst[thr_idx].kd_blk_nbr=1; mem_lst[thr_idx].kd_list=(KDPriority*)nco_free(mem_lst[thr_idx].kd_list); //mem_lst[thr_idx].kd_list=(KDPriority*)nco_realloc(mem_lst[idx].kd_list, sizeof(KDPriority) * NCO_VRL_BLOCKSIZE ); mem_lst[idx].kd_list=(KDPriority *)nco_calloc(sizeof(KDPriority),(size_t)(NCO_VRL_BLOCKSIZE)); } /* get bounds of polygon in */ bSplit=nco_poly_minmax_split(pl_lst_in[idx],grd_lon_typ, size1,size2 ); /* if a wrapped polygon then do two searches */ if(bSplit) vrl_cnt = kd_nearest_intersect_wrp(tree, nbr_tr, size1, size2, &mem_lst[thr_idx]); else vrl_cnt = kd_nearest_intersect(tree, nbr_tr, size1, &mem_lst[thr_idx], bSort); /* nco_poly_prn(2, pl_lst_in[idx] ); */ for (jdx = 0; jdx < vrl_cnt; jdx++) { poly_sct *pl_vrl = NULL_CEWI; poly_sct *pl_out = (poly_sct *) mem_lst[thr_idx].kd_list[jdx].elem->item; /* for area debug only */ mem_lst[thr_idx].kd_list[jdx].area=-1.0; mem_lst[thr_idx].kd_list[jdx].dbg_sng[0]='\0'; /* if (pl_lst_in[idx]->pl_typ != pl_out->pl_typ) { fprintf(stderr, "%s: %s poly type mismatch\n", nco_prg_nm_get(), fnc_nm); continue; } */ if(pl_typ== poly_rll) { pl_vrl = nco_poly_vrl_do(pl_lst_in[idx], pl_out, 0, (char*)NULL); /* if pl_vrl is NULL from, nco_poly_do_vrl() then there are 3 possible senario's * * 1) pl_lst_in[idx] and pl_out are seperate and distinct * * 2) pl_lst_in[idx] is entirely inside pl_out. * to check for this it is sufficent to check the * the minmax bounds and then also check that a single vertex * from pl_lst_in[idx] is inside pl_out * * 3) pl_out is entirely inside pl_lst_in[idx] * check minmax bounds then check a single vertex from * pl_out */ if(!pl_vrl) { if (nco_poly_in_poly_minmax(pl_lst_in[idx], pl_out)) pl_vrl = nco_poly_dpl(pl_out); else if (nco_poly_in_poly_minmax(pl_out, pl_lst_in[idx])) pl_vrl = nco_poly_dpl(pl_lst_in[idx]); } if(pl_vrl) { /* add area nb also sets wrapping */ nco_poly_minmax_add(pl_vrl, grd_lon_typ, False); /* REMEMBER poly_rll area uses minmax limits AND NOT VERTEX's */ nco_poly_area_add(pl_vrl); } } if(pl_typ== poly_sph ) { int lret = 0; int lret2=0; /* [flg] set by nco_sph_intersect_pre - if True it means that scan hase detected a genuine intersection so * so no need to do further processing */ nco_bool bGenuine=False; nco_bool bBadArea=False; char in_sng[VP_MAX]; char out_sng[VP_MAX]; int flg_snp_to=2; in_sng[0]='\0'; out_sng[0]='\0'; nco_sph_intersect_pre(pl_lst_in[idx], pl_out, in_sng); if(0 && nco_dbg_lvl_get() >= nco_dbg_dev) (void)fprintf(stderr,"%s:%s(): sp_sng=%s \n",nco_prg_nm_get(),fnc_nm, in_sng ); lret = nco_sph_process_pre(pl_out, in_sng, &bGenuine); switch(lret) { case 1: pl_vrl = nco_poly_dpl(pl_out); break; case 2: pl_vrl = nco_poly_vrl_do(pl_lst_in[idx], pl_out, flg_snp_to, (char *)NULL); break; case 3: pl_vrl = nco_poly_vrl_do(pl_lst_in[idx], pl_out, flg_snp_to, in_sng); break; case 4: pl_vrl = nco_poly_vrl_do(pl_lst_in[idx], pl_out, flg_snp_to, (char*)NULL); break; case 5: pl_vrl = nco_poly_vrl_do(pl_lst_in[idx], pl_out, flg_snp_to, in_sng); break; } if(pl_vrl) { double min_area= ( pl_out->area < pl_lst_in[idx]->area ? pl_out->area : pl_lst_in[idx]->area ); /* add area nb also sets wrapping */ nco_poly_minmax_add(pl_vrl, grd_lon_typ, False); /* REMEMBER poly_rll area uses minmax limits AND NOT VERTEX's */ nco_poly_area_add(pl_vrl); if( isnan( pl_vrl->area) || pl_vrl->area == 0.0 || (pl_vrl->area - min_area)/ min_area > 1.0e-04 ) { pl_vrl = nco_poly_free(pl_vrl); bBadArea=True; } } /* swap args around and try again */ if(!pl_vrl && ( (bGenuine==False && lret !=1 ) || bBadArea ) ) //if(!pl_vrl && ( (bGenuine==False && lret !=1 ) || bBadArea ) ) { flg_snp_to=1; nco_sph_intersect_pre(pl_out, pl_lst_in[idx], out_sng); lret2 = nco_sph_process_pre(pl_lst_in[idx], out_sng, &bGenuine); switch(lret2) { case 1: pl_vrl = nco_poly_dpl(pl_lst_in[idx]); break; case 2: pl_vrl = nco_poly_vrl_do(pl_out, pl_lst_in[idx], flg_snp_to, (char *)NULL); break; case 3: pl_vrl = nco_poly_vrl_do(pl_out, pl_lst_in[idx], flg_snp_to, out_sng); break; case 4: pl_vrl = nco_poly_vrl_do(pl_out, pl_lst_in[idx], flg_snp_to, (char*)NULL); break; case 5: pl_vrl = nco_poly_vrl_do(pl_out, pl_lst_in[idx], flg_snp_to, out_sng); break; } if(pl_vrl) { nco_poly_minmax_add(pl_vrl, grd_lon_typ, False); nco_poly_area_add(pl_vrl); } } if(bDirtyRats ) sprintf(mem_lst[thr_idx].kd_list[jdx].dbg_sng, "lret=%d in_sng=%s lret2=%d out_sng=%s\n",lret, in_sng, lret2, out_sng); if(bDirtyRats && pl_vrl && !nco_sph_is_convex(pl_vrl->shp, pl_vrl->crn_nbr) ) { (void) fprintf(stderr, "/************* concave overlap plygon***********/\n"); nco_poly_prn(pl_lst_in[idx],0); nco_poly_prn(pl_out,0); nco_poly_prn(pl_vrl, 0); (void) fprintf(stderr, "/***********************************************/\n"); } } /* end if poly_sph */ if (pl_vrl) { // nco_poly_re_org(pl_vrl, lcl_dp_x, lcl_dp_y); /* add aprropriate id's */ pl_vrl->src_id = pl_lst_in[idx]->src_id; pl_vrl->dst_id = pl_out->src_id; /* shp not needed */ nco_poly_shp_free(pl_vrl); /* calculate weight -simple ratio of areas */ pl_vrl->wgt=pl_vrl->area / pl_out->area; /* add lat/lon centers */ nco_poly_ctr_add(pl_vrl, grd_lon_typ); wrp_cnt+=pl_vrl->bwrp; if( isnan(pl_vrl->area) || pl_vrl->area ==0.0 ) { nan_cnt++; pl_vrl->area=0.0; pl_vrl=nco_poly_free(pl_vrl); continue; } /* for input polygon wgt is used to calculate frac_a */ pl_lst_in[idx]->wgt+= ( pl_vrl->area / pl_lst_in[idx]->area ); /* #ifdef _OPENMP #pragma omp critical #endif { pl_out->wgt+=pl_vrl->wgt; } */ vrl_area += pl_vrl->area; mem_lst[thr_idx].kd_list[jdx].area=pl_vrl->area; if( mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE < mem_lst[thr_idx].pl_cnt +1 ){ if(lst_out_typ==1) mem_lst[thr_idx].wgt_lst= (wgt_sct**)nco_realloc(mem_lst[thr_idx].wgt_lst, sizeof(wgt_sct*) * ++mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE ); else if(lst_out_typ==2) mem_lst[thr_idx].pl_lst= (poly_sct**)nco_realloc(mem_lst[thr_idx].pl_lst, sizeof(poly_sct*) * ++mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE ); } if(lst_out_typ==1) { wgt_sct *wgt_lcl=(wgt_sct*)nco_calloc(1,sizeof(wgt_sct)); wgt_lcl->src_id=pl_vrl->src_id; wgt_lcl->dst_id=pl_vrl->dst_id; wgt_lcl->area=pl_vrl->area; wgt_lcl->wgt=pl_vrl->wgt; mem_lst[thr_idx].wgt_lst[mem_lst[thr_idx].pl_cnt++] =wgt_lcl; pl_vrl=nco_poly_free(pl_vrl); } else if(lst_out_typ==2 ) mem_lst[thr_idx].pl_lst[mem_lst[thr_idx].pl_cnt++] = pl_vrl; vrl_cnt_on++; /* for area debug only */ } } /* end jdx */ if (nco_dbg_lvl_get() >= nco_dbg_dev) { #ifdef _OPENMP #pragma omp critical #endif { tot_nan_cnt += nan_cnt; tot_wrp_cnt += wrp_cnt; tot_area += vrl_area; } /* end OMP critical */ /* area diff by more than 10% */ int kdx; double eps = 1e-8; double frc = vrl_area / pl_lst_in[idx]->area; if (frc < (1 - eps) || frc > 1 + eps) { (void) fprintf(fp_stderr, "%s: polygon %lu - potential overlaps=%d actual overlaps=%d area_in=%.10e vrl_area=%.10e adiff=%.15e bSplit=%d\n", nco_prg_nm_get(), idx, vrl_cnt, vrl_cnt_on, pl_lst_in[idx]->area, vrl_area, (pl_lst_in[idx]->area - vrl_area), bSplit); if (bDirtyRats) { //if (pl_lst_in[idx]->bwrp ) { if (1) { (void) fprintf(fp_stderr, "# /** following pl_lst_in[%lu] **/\n", idx); nco_poly_prn(pl_lst_in[idx], 0); (void) fprintf(fp_stderr, "# /** overlaps to follow **/\n"); for (kdx = 0; kdx < vrl_cnt; kdx++) { nco_poly_prn((poly_sct *) mem_lst[thr_idx].kd_list[kdx].elem->item, 0); (void)fprintf(fp_stderr, "# vrl_area=%.15e\n",mem_lst[thr_idx].kd_list[kdx].area ); (void)fprintf(fp_stderr, "# dbg_sng=%s\n",mem_lst[thr_idx].kd_list[kdx].dbg_sng ); } (void) fprintf(stderr, "/************* end dirty rats ***************/\n"); } if(1 && vrl_cnt_on>0 && lst_out_typ==2 ) { pl_lst_dbg = (poly_sct **) nco_realloc(pl_lst_dbg, sizeof(poly_sct *) * (pl_cnt_dbg + vrl_cnt_on)); /* write overlaps maybe */ for (kdx = 0; kdx < vrl_cnt_on; kdx++) { poly_sct * lcl_poly=mem_lst[thr_idx].pl_lst[mem_lst[thr_idx].pl_cnt - vrl_cnt_on + kdx]; if(lcl_poly->src_id== pl_lst_in[idx]->src_id ) pl_lst_dbg[pl_cnt_dbg++] = nco_poly_dpl(lcl_poly); } } } } } /* end dbg */ cont_msk: ; /* output some usefull tracking stuff - not debug but informative */ if ( ++mem_lst[thr_idx].idx_cnt % thr_quota_step == 0 && nco_dbg_lvl_get() >=3 ) (void)fprintf(fp_stderr, "%s: thread %d has processed %2.2f%% (%ld) of src cells quota and output %ld overlap cells\n", nco_prg_nm_get(), thr_idx, (float)mem_lst[thr_idx].idx_cnt/(float)thr_quota *100.0, mem_lst[thr_idx].idx_cnt, mem_lst[thr_idx].pl_cnt ); } /* end for idx */ /* turn tot_area into a % of 4*PI */ /* tot_area = tot_area / 4.0 / M_PI *100.0; */ /* final report */ if (nco_dbg_lvl_get() >= nco_dbg_dev) (void) fprintf(stderr, "%s: total overlaps=%d, total_area=%.15f (area=%3.10f%%) total num wrapped= %d total nan nbr=%d \n", nco_prg_nm_get(), pl_cnt_vrl, tot_area, tot_area /4.0 / M_PI *100.0, tot_wrp_cnt, tot_nan_cnt); /* write filtered polygons to file */ if(bDirtyRats && pl_cnt_dbg) { nco_msh_poly_lst_wrt("tst-wrt-dbg.nc", pl_lst_dbg, pl_cnt_dbg, grd_lon_typ,NC_FORMAT_NETCDF4); pl_lst_dbg=(poly_sct**)nco_poly_lst_free(pl_lst_dbg, pl_cnt_dbg); } /* concatenate memory list, place results into first member list */ nco_mem_lst_cat(mem_lst, lcl_thr_nbr); /* free up kd_list's */ for(idx=0;idx<lcl_thr_nbr;idx++) mem_lst[idx].kd_list= (KDPriority*) nco_free(mem_lst[idx].kd_list); *pl_cnt_vrl_ret=mem_lst[0].pl_cnt; if(lst_out_typ==1) void_lst_vrl=(void**) mem_lst[0].wgt_lst; else if( lst_out_typ==2 ) void_lst_vrl=(void**) mem_lst[0].pl_lst; mem_lst=(omp_mem_sct*)nco_free(mem_lst); /* REMEMBER the void type can be a wgt_sct** array or a poly_sct** array * wgt_sct is a subset of poly_sct - with simple members */ return void_lst_vrl; } /* check areas - nb WARNING modifies area in pl_lst_in and pl_lst_out */ void nco_poly_lst_chk( poly_sct **pl_lst_in, int pl_cnt_in, poly_sct **pl_lst_out, int pl_cnt_out, poly_sct **pl_lst_vrl, int pl_cnt_vrl) { int id; int idx; int jdx; double epsilon=1.0e-8; const char fnc_nm[]="nco_poly_lst_chk()"; for(idx=0;idx<pl_cnt_vrl;idx++) { id=pl_lst_vrl[idx]->src_id; for(jdx=0;jdx<pl_cnt_in;jdx++) if(pl_lst_in[jdx]->src_id==id) break; if(jdx < pl_cnt_in ) pl_lst_in[jdx]->area-=pl_lst_vrl[idx]->area; } fprintf(stderr, "%s():WARNING following is list of incomplete src cells, by src_id no\n",fnc_nm); for(idx=0;idx<pl_cnt_in;idx++) if( fabs( pl_lst_in[idx]->area) > epsilon) fprintf(stderr, "src_id=%d area=%.10f\n", pl_lst_in[idx]->src_id, pl_lst_in[idx]->area ); for(idx=0;idx<pl_cnt_vrl;idx++) { id=pl_lst_vrl[idx]->dst_id; for(jdx=0;jdx<pl_cnt_out;jdx++) if(pl_lst_out[jdx]->src_id==id) break; if(jdx < pl_cnt_out ) pl_lst_out[jdx]->area-=pl_lst_vrl[idx]->area; } fprintf(stderr, "%s():WARNING following is list of incomplete dst cells, by src_id no\n",fnc_nm); for(idx=0;idx<pl_cnt_out;idx++) if( fabs( pl_lst_out[idx]->area) > epsilon) fprintf(stderr, "src_id=%d area=%.10f\n", pl_lst_out[idx]->src_id, pl_lst_out[idx]->area ); return; } poly_sct ** nco_poly_lst_chk_dbg( poly_sct **pl_lst, int pl_cnt, poly_sct **pl_lst_vrl, int pl_cnt_vrl, int io_flg, /* [flg] 0 - use src_id from vrl, 1 - use dst_id from vrl */ int *pl_cnt_dbg) /* size of output dbg grid */ { int id; int idx; int jdx; int pl_nbr_dbg=0; double epsilon=1.0e-12; double *area=NULL_CEWI; nco_bool is_lst_cnt=False; /* if true then pl_cnt matches max src_id There are no missing records from NetCDF SCRIP input */ is_lst_cnt=( pl_cnt== pl_lst[pl_cnt-1]->src_id +1); poly_sct **pl_lst_dbg=NULL_CEWI; const char fnc_nm[]="nco_poly_lst_chk_dbg()"; area=(double*)nco_malloc(sizeof(double)*pl_cnt); for(idx=0;idx<pl_cnt;idx++) area[idx]=pl_lst[idx]->area; for(idx=0;idx<pl_cnt_vrl;idx++) { id = (io_flg ? pl_lst_vrl[idx]->dst_id : pl_lst_vrl[idx]->src_id); if(is_lst_cnt ) area[id] -= pl_lst_vrl[idx]->area; else { for (jdx = 0; jdx < pl_cnt; jdx++) if (pl_lst[jdx]->src_id == id) break; if (jdx < pl_cnt) area[jdx] -= pl_lst_vrl[idx]->area; } } for(idx=0;idx<pl_cnt;idx++) { if (fabs(area[idx]) > epsilon) { if (nco_dbg_lvl_get() >= nco_dbg_dev) fprintf(stderr, "%s() src_id=%d area=%.15e\n", fnc_nm, pl_lst[idx]->src_id, area[idx]); pl_lst_dbg = (poly_sct **) nco_realloc(pl_lst_dbg, sizeof(poly_sct*) * (pl_nbr_dbg + 1)); pl_lst_dbg[pl_nbr_dbg] = nco_poly_dpl(pl_lst[idx]); pl_nbr_dbg++; } } area=(double*)nco_free(area); *pl_cnt_dbg=pl_nbr_dbg; return pl_lst_dbg; } wgt_sct ** nco_poly_lst_mk_dwe_sph( rgr_sct *const rgr_nfo, poly_sct **pl_lst_out, int pl_cnt, nco_grd_lon_typ_enm grd_lon_typ, KDTree **tree, int nbr_tr, int *wgt_cnt_bln_ret) { /* just duplicate output list to overlap */ const char fnc_nm[] = "nco_poly_lst_mk_dwe_sph()"; int thr_idx = 0; /* approx number of input cells each thread will process */ int thr_quota; /* reporting step */ int thr_quota_step; /* max number of nearest neighbours to consider - nr-reference from rgr_nfo */ int const max_nbr_dwe=20; int nbr_dwe=0; double pow_dwe=0.0; double min_dist=1.0e-12; double min_wgt=1.0e-20; poly_typ_enm pl_typ; size_t idx; int lcl_thr_nbr; omp_mem_sct *mem_lst = NULL_CEWI; wgt_sct **wgt_lst_dwe = NULL_CEWI; FILE *const fp_stderr = stderr; pl_typ = pl_lst_out[0]->pl_typ; lcl_thr_nbr = omp_get_max_threads(); nbr_dwe= ( rgr_nfo->xtr_nsp > max_nbr_dwe ? max_nbr_dwe : rgr_nfo->xtr_nsp ); pow_dwe=rgr_nfo->xtr_xpn; mem_lst = (omp_mem_sct *) nco_malloc(sizeof(omp_mem_sct) * lcl_thr_nbr); for (idx = 0; idx < lcl_thr_nbr; idx++) { mem_lst[idx].wgt_lst = NULL_CEWI; mem_lst[idx].blk_nbr = 0; mem_lst[idx].pl_cnt = 0; mem_lst[idx].kd_list = (KDPriority *) nco_calloc(sizeof(KDPriority), (size_t) (NCO_VRL_BLOCKSIZE)); mem_lst[idx].kd_cnt = 0; mem_lst[idx].kd_blk_nbr = 1; mem_lst[idx].idx_cnt = 0; } thr_quota = pl_cnt / lcl_thr_nbr; thr_quota_step = thr_quota / 20; if (thr_quota_step < 2000) thr_quota_step = 2000; /* NB: "OpenMP notes" section of nco_rgr.c has detailed discussion of these settings Henry, please keep the variables in alphabetical order within a clause and remember to update Intel */ #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ #endif /* !__GNUC__ */ #if defined(__INTEL_COMPILER) # pragma omp parallel for private(idx,thr_idx) schedule(dynamic,40) shared(grd_lon_typ,nbr_tr,pl_typ,tree) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) private(idx,thr_idx) shared(bDirtyRats,grd_lon_typ,max_nbr_vrl,nbr_tr,pl_cnt_dbg,pl_typ,tree,tot_nan_cnt,tot_wrp_cnt) # else /* !old g++ */ # pragma omp parallel for private(idx,thr_idx) schedule(dynamic,40) shared(grd_lon_typ,nbr_tr,pl_typ,tree) # endif /* !old g++ */ #endif /* !__INTEL_COMPILER */ for (idx = 0; idx < pl_cnt; idx++) { double dp_x_wrp; /* used to do a wrapped lon search */ double wgt_ttl=0.0; int nbr_dwe_cnt; /* equal to or less than nbr_nni */ wgt_sct wgt_pre[max_nbr_dwe]; wgt_sct * wgt_lcl=NULL_CEWI; poly_sct *pl=NULL_CEWI; size_t jdx; size_t kdx; size_t nbr_lst_lcl; // (void) nco_poly_set_priority(max_nbr_vrl, list); thr_idx = omp_get_thread_num(); if (0 && nco_dbg_lvl_get() >= nco_dbg_dev) fprintf(fp_stderr, "%s(): idx=%lu thr=%d\n", fnc_nm, idx, thr_idx); if (pl_lst_out[idx]->bmsk == False) continue; mem_lst[thr_idx].kd_cnt = 0; if (mem_lst[thr_idx].kd_blk_nbr > 1) { mem_lst[thr_idx].kd_blk_nbr = 1; mem_lst[thr_idx].kd_list = (KDPriority *) nco_free(mem_lst[thr_idx].kd_list); //mem_lst[thr_idx].kd_list=(KDPriority*)nco_realloc(mem_lst[idx].kd_list, sizeof(KDPriority) * NCO_VRL_BLOCKSIZE ); mem_lst[idx].kd_list = (KDPriority *) nco_calloc(sizeof(KDPriority), (size_t) (NCO_VRL_BLOCKSIZE)); } /* get bounds of polygon in */ //bSplit = nco_poly_minmax_split(pl_lst_out[idx], grd_lon_typ, size1, size2); dp_x_wrp=KD_DBL_MAX; for(kdx=0;kdx<nbr_tr;kdx++) kd_nearest(tree[kdx], pl_lst_out[idx]->dp_x_ctr, pl_lst_out[idx]->dp_y_ctr, pl_typ, nbr_dwe, mem_lst[thr_idx].kd_list + nbr_dwe *kdx ); nbr_lst_lcl=nbr_dwe*nbr_tr; switch(grd_lon_typ) { case nco_grd_lon_nil: case nco_grd_lon_unk: case nco_grd_lon_Grn_ctr: case nco_grd_lon_Grn_wst: case nco_grd_lon_bb: if(pl_lst_out[idx]->dp_x_ctr <180.0) dp_x_wrp=pl_lst_out[idx]->dp_x_ctr+360.0; else if(pl_lst_out[idx]->dp_x_ctr >180.0) dp_x_wrp=pl_lst_out[idx]->dp_x_ctr-360.0; break; case nco_grd_lon_180_wst: case nco_grd_lon_180_ctr: if(pl_lst_out[idx]->dp_x_ctr <0.0) dp_x_wrp=pl_lst_out[idx]->dp_x_ctr+360.0; else if(pl_lst_out[idx]->dp_x_ctr >0.0) dp_x_wrp=pl_lst_out[idx]->dp_x_ctr-360.0; break; } if(dp_x_wrp != KD_DBL_MAX) { for (kdx = 0; kdx < nbr_tr; kdx++) kd_nearest(tree[kdx], dp_x_wrp, pl_lst_out[idx]->dp_y_ctr, pl_typ, nbr_dwe, mem_lst[thr_idx].kd_list + nbr_lst_lcl+nbr_dwe * kdx); nbr_lst_lcl+=nbr_dwe*nbr_tr; } if(nbr_tr >1 ) qsort((void *)mem_lst[thr_idx].kd_list, nbr_lst_lcl, sizeof(KDPriority), kd_priority_cmp_dist); /* remember kd list sorted according to distance */ /* check first member distance if min then output singleton */ if(mem_lst[thr_idx].kd_list[0].dist <= min_dist) { pl=(poly_sct*)mem_lst[thr_idx].kd_list[0].elem->item; wgt_lcl=(wgt_sct*)nco_malloc(sizeof(wgt_sct)); wgt_lcl->src_id=pl->src_id; wgt_lcl->dst_id=pl_lst_out[idx]->src_id; wgt_lcl->area=pl->area; wgt_lcl->dist=mem_lst[thr_idx].kd_list[0].dist; wgt_lcl->wgt=1.0; if( mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE < mem_lst[thr_idx].pl_cnt +1 ) mem_lst[thr_idx].wgt_lst= (wgt_sct**)nco_realloc(mem_lst[thr_idx].wgt_lst, sizeof(wgt_sct*) * ++mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE ); mem_lst[thr_idx].wgt_lst[mem_lst[thr_idx].pl_cnt++] =wgt_lcl; if (nco_dbg_lvl_get() >= nco_dbg_dev) (void)fprintf(fp_stderr,"%s:%s: singleton x_ctr=%f y_ctr=%f\n", nco_prg_nm_get(), fnc_nm, pl_lst_out[idx]->dp_x_ctr, pl_lst_out[idx]->dp_y_ctr ); }else{ /* check for duplicates in first nbr_nni by sorting again with ->item !!!*/ kd_priority_list_sort(mem_lst[thr_idx].kd_list,nbr_dwe, nbr_dwe,&nbr_dwe_cnt ); if (nco_dbg_lvl_get() >= nco_dbg_dev && nbr_dwe_cnt < nbr_dwe ) (void)fprintf(fp_stderr,"%s:%s: nbr_nni_cnt=%d x_ctr=%f y_ctr=%f\n", nco_prg_nm_get(), fnc_nm, nbr_dwe_cnt, pl_lst_out[idx]->dp_x_ctr, pl_lst_out[idx]->dp_y_ctr ); /* output at least one */ for (jdx = 0; jdx < nbr_dwe_cnt; jdx++) { pl = (poly_sct *) mem_lst[thr_idx].kd_list[jdx].elem->item; /* remember src is in tree and dst is in list */ wgt_pre[jdx].src_id = pl->src_id; wgt_pre[jdx].dst_id = pl_lst_out[idx]->src_id; wgt_pre[jdx].area = pl->area; wgt_pre[jdx].dist = mem_lst[thr_idx].kd_list[jdx].dist; /* use dist squared */ wgt_pre[jdx].wgt = 1.0 / pow(wgt_pre[jdx].dist, pow_dwe); } /* find weights total */ for (jdx = 0; jdx < nbr_dwe_cnt; jdx++) wgt_ttl += wgt_pre[jdx].wgt; /* normalize weights */ for (jdx = 0; jdx < nbr_dwe_cnt; jdx++) wgt_pre[jdx].wgt /= wgt_ttl; for (jdx = 0; jdx < nbr_dwe_cnt; jdx++) { if (wgt_pre[jdx].wgt < min_wgt) continue; wgt_lcl = (wgt_sct *) nco_malloc(sizeof(wgt_sct)); *wgt_lcl = wgt_pre[jdx]; if (mem_lst[thr_idx].blk_nbr * NCO_VRL_BLOCKSIZE < mem_lst[thr_idx].pl_cnt + 1) mem_lst[thr_idx].wgt_lst = (wgt_sct **) nco_realloc(mem_lst[thr_idx].wgt_lst,sizeof(wgt_sct *) * ++mem_lst[thr_idx].blk_nbr *NCO_VRL_BLOCKSIZE); mem_lst[thr_idx].wgt_lst[mem_lst[thr_idx].pl_cnt++] = wgt_lcl; //(void)fprintf(stderr,"%s: weight(%lu)=%f ",fnc_nm, mem_lst[thr_idx].pl_cnt, wgt_lcl->wgt); } /* end jdx */ } /* output some usefull tracking stuff - not debug but informative */ if ( ++mem_lst[thr_idx].idx_cnt % thr_quota_step == 0 && nco_dbg_lvl_get() >=3 ) (void)fprintf(fp_stderr, "%s: thread %d has processed %2.2f%% (%ld) of src cells quota and output %ld overlap cells\n", nco_prg_nm_get(), thr_idx, (float)mem_lst[thr_idx].idx_cnt/(float)thr_quota *100.0, mem_lst[thr_idx].idx_cnt, mem_lst[thr_idx].pl_cnt ); } /* end idx */ nco_mem_lst_cat(mem_lst, lcl_thr_nbr); /* free up kd_list's */ for(idx=0;idx<lcl_thr_nbr;idx++) mem_lst[idx].kd_list= (KDPriority*) nco_free(mem_lst[idx].kd_list); wgt_lst_dwe=mem_lst[0].wgt_lst; *wgt_cnt_bln_ret=mem_lst[0].pl_cnt; mem_lst=(omp_mem_sct*)nco_free(mem_lst); return wgt_lst_dwe; } /* !nco_poly_lst_mk_dwe_sph() */ void nco_poly_lst_ctr_add( poly_sct **pl_lst, int pl_cnt, int ctr_typ) { int idx; double pControl[NBR_SPH]; for(idx=0;idx<pl_cnt;idx++) { if(pl_lst[idx]->crn_nbr <3 || pl_lst[idx]->area==0.0 ) continue; if(ctr_typ==1){ nco_sph_inside_mk(pl_lst[idx], pControl); pl_lst[idx]->dp_x_ctr=R2D(pControl[3]); pl_lst[idx]->dp_y_ctr=R2D(pControl[4]); } } return; } /* !nco_poly_lst_ctr_add() */ void nco_mem_lst_cat( omp_mem_sct *mem_lst, int sz_lst) { int idx; int i_typ; size_t tot_cnt = 0; if(mem_lst->wgt_lst) i_typ = 1; else if(mem_lst->pl_lst) i_typ = 2; else i_typ=0; /* quick return if list empty */ if(!i_typ) return; /* find total size of lists */ for (idx = 0; idx < sz_lst; idx++) tot_cnt += mem_lst[idx].pl_cnt; if(!tot_cnt) return; else if( i_typ==1 ){ wgt_sct **tmp_wgt_lst = NULL; tmp_wgt_lst = mem_lst[0].wgt_lst = (wgt_sct **) nco_realloc(mem_lst[0].wgt_lst, sizeof(wgt_sct *) * tot_cnt); tmp_wgt_lst += mem_lst[0].pl_cnt; for (idx = 1; idx < sz_lst; idx++) { if (mem_lst[idx].wgt_lst) { memcpy(tmp_wgt_lst, mem_lst[idx].wgt_lst, sizeof(wgt_sct *) * mem_lst[idx].pl_cnt); tmp_wgt_lst += mem_lst[idx].pl_cnt; /* free up list */ mem_lst[idx].wgt_lst = (wgt_sct **) nco_free(mem_lst[idx].wgt_lst); } } } else if(i_typ==2) { poly_sct **tmp_ply_lst = NULL; tmp_ply_lst = mem_lst[0].pl_lst = (poly_sct **) nco_realloc(mem_lst[0].pl_lst, sizeof(poly_sct *) * tot_cnt); tmp_ply_lst += mem_lst[0].pl_cnt; for (idx = 1; idx < sz_lst; idx++) { if (mem_lst[idx].pl_lst) { memcpy(tmp_ply_lst, mem_lst[idx].pl_lst, sizeof(poly_sct *) * mem_lst[idx].pl_cnt); tmp_ply_lst += mem_lst[idx].pl_cnt; /* free up list */ mem_lst[idx].pl_lst = (poly_sct **) nco_free(mem_lst[idx].pl_lst); } } } /* update first list with total */ mem_lst[0].pl_cnt=tot_cnt; return; } /* !nco_mem_lst_cat() */
naive_bayes.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <string.h> #include <memory.h> #include <sys/time.h> #define REAL double #define EPSILON 0.000001 #define MICRO_IN_SEC 1000000.00 __declspec(target(mic)) double begin, end; __declspec(target(mic)) double microtime(){ int tv_sec,tv_usec; double time; struct timeval tv; struct timezone tz; gettimeofday(&tv,&tz); return tv.tv_sec+tv.tv_usec/MICRO_IN_SEC; } int caculateNB_train(char *ifn) ; int main(int argc,char* argv[]) { char *ifn=NULL,*argument=NULL; if(argc<3) { printf("Wrong command format! usage:COMMAND ARGUMENT INPUTFILENAME\nARGUMENT:\n\ttrain:\ttrain the classifier\n\tclassify:\tclassify the dataset\n"); return 0; } else { ifn=argv[2]; argument=argv[1]; if(!strcmp(argument,"train")) { caculateNB_train(ifn); } else if(!strcmp(argument,"classify")) { caculateNB_classify(ifn); } else { printf("Error command!\n"); } return 0; } } int caculateNB_train(char *ifn) { char *ofn="nb_train_result.txt"; FILE *ifp,*ofp; int i,j,k,class,a,linen,propertyn,classn,*array_valuen,*array_class,*array_property_class,*array_counts,*array_index,array_length; REAL *array_class_probability,*array_probability; begin = microtime(); if((ifp=fopen(ifn,"r"))==NULL) { printf("%s file open error!\n",ifn); exit(0); } else { printf("%s file opened success!\n",ifn); } if((ofp=fopen(ofn,"w"))==NULL) { printf("%s file open error!\n",ofn); fclose(ifp); exit(0); } else { printf("%s file opened success!\n",ofn); } printf("Get base info\n"); fscanf(ifp,"%d%d%d",&linen,&propertyn,&classn); //linen is the number of dataset lines, \ propertyn is the number of property of every dataset, classn is the number of classes; printf("Read data\n"); //array_valuen is an array of the max value of every property if((array_valuen=(int *)malloc(propertyn*sizeof(int)))==NULL) { printf("Memory alloc ERROR!\n"); fclose(ifp); fclose(ofp); exit(0); } printf("Get property number\n"); for(i=0;i<propertyn;i++) { fscanf(ifp,"%d",array_valuen+i); } //array_index is an array of the index of every property in array_probability if((array_index=(int *)malloc(propertyn*sizeof(int)))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); exit(0); } for(i=0;i<propertyn;i++) { array_index[i] = 0; } array_length = array_valuen[0] * classn; array_index[0] = 0; if(propertyn>1) { for(i=1;i<propertyn;i++) { array_length += array_valuen[i] * classn; array_index[i] = array_valuen[i-1] * classn + array_index[i-1]; } } //the array_class is the array of count of class if((array_class=(int *)malloc(classn*(sizeof(int))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_index); exit(0); } memset(array_class,0,classn*sizeof(int)); //the array_property_class is the array of the count of every property of every class if((array_property_class=(int *)malloc(propertyn*classn*(sizeof(int))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_class); free(array_index); exit(0); } memset(array_property_class,0,propertyn*classn*sizeof(int)); //array_counts is an array of the pointer of counter of every property of every class if((array_counts=(int *)malloc(array_length*(sizeof(int))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_index); free(array_class); free(array_property_class); exit(0); } memset(array_counts,0,array_length*(sizeof(int))); printf("Get every needed info\n"); for(i=0;i<linen;i++) { fscanf(ifp,"%d",&class); array_class[class]++; for(j=0;j<propertyn;j++) { fscanf(ifp,"%d",&a); array_counts[ array_index[j] + a*classn + class ] ++; array_property_class[j*classn+class]++; } } //array_class_probability is an array of the classes if((array_class_probability=(REAL *)malloc(classn*(sizeof(REAL))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_index); free(array_counts); free(array_class); free(array_property_class); exit(0); } //array_probability is an array of the pointer of probability of every property of every class if((array_probability=(REAL *)malloc(array_length*(sizeof(REAL))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_index); free(array_counts); free(array_class); free(array_class_probability); free(array_property_class); exit(0); } end = microtime(); printf("\nalloc memory and reading data consuming time: %fs\n\n",end-begin); begin = end; printf("Get P(C)\n"); //caculate the p(c) #pragma offload target(mic) \ inout(array_class_probability:length(classn)) \ in(array_class:length(classn)) #pragma omp parallel for for(i=0;i<classn;i++) { array_class_probability[i]=(REAL)(array_class[i]+1)/(REAL)(linen+classn); } printf("Get P(A|C)\n"); //caculate the p(a|c) #pragma offload target(mic) \ inout(array_probability:length(array_length)) \ in(array_counts:length(array_length)) \ in(array_index:length(propertyn)) \ in(array_property_class:length(propertyn*classn)) \ in(array_valuen:length(propertyn)) #pragma omp parallel for for(i=0;i<propertyn;i++) { for(j=0;j<array_valuen[i];j++) { for(k=0;k<classn;k++) { array_probability[ array_index[i] + j*classn+k ]=(REAL)( array_counts[ array_index[i] + j*classn+k ] + 1 )/(REAL)(array_property_class[i*classn+k]+array_valuen[i]); } } } end = microtime(); printf("\ntrain the classifier consuming time: %fs\n\n",end - begin); begin = end; //p(c) and p(a|c) is the training result printf("Outputing the training result to %s\n",ofn); fprintf(ofp,"%d %d\n",propertyn,classn); for(i=0;i<propertyn;i++) { fprintf(ofp,"%d ",array_valuen[i]); } fprintf(ofp,"\n"); for(i=0;i<classn;i++) { fprintf(ofp,"%f ",array_class_probability[i]); } fprintf(ofp,"\n"); for(i=0;i<propertyn;i++) { for(j=0;j<array_valuen[i];j++) { for(k=0;k<classn;k++) { fprintf(ofp,"%f ",array_probability[ array_index[i] + j*classn+k]); } fprintf(ofp,"\n"); } } printf("Recycle all resources\n"); //recycle all resources fclose(ifp); fclose(ofp); free(array_valuen); free(array_index); free(array_property_class); free(array_probability); free(array_counts); free(array_class); free(array_class_probability); printf("\nPlease DON'T change %s either its name and content!!\n",ofn); return 0; } int caculateNB_classify(char *ifn) { char *ofn="nb_classify_result.txt",*ifn_classifier="nb_train_result.txt"; FILE *ifp,*ofp,*ifp_classifier; int i,j,k,max,linen,propertyn,classn,*array_valuen,*array_test_class,*array_test,*array_probability_index,array_probability_length; REAL *array_class_probability,*array_probability,*array_test_class_probability; begin = microtime(); if((ifp_classifier=fopen(ifn_classifier,"r"))==NULL) { printf("%s file open error!\n",ifn_classifier); exit(0); } else { printf("%s file opened success!\n",ifn_classifier); } if((ifp=fopen(ifn,"r"))==NULL) { printf("%s file open error!\n",ifn); exit(0); } else { printf("%s file opened success!\n",ifn); } if((ofp=fopen(ofn,"w"))==NULL) { printf("%s file open error!\n",ofn); fclose(ifp); exit(0); } else { printf("%s file opened success!\n",ofn); } printf("Get base info from %s and configure the classifier\n",ifn_classifier); fscanf(ifp_classifier,"%d%d",&propertyn,&classn); //propertyn is the number of property of every dataset, classn is the number of classes; //array_valuen is an array of the max value of every property if((array_valuen=(int *)malloc(propertyn*sizeof(int)))==NULL) { printf("Memory alloc ERROR!\n"); fclose(ifp); fclose(ofp); exit(0); } for(i=0;i<propertyn;i++) { fscanf(ifp_classifier,"%d",array_valuen+i); } //array_class_probability is an array of the classes if((array_class_probability=(REAL *)malloc(classn*(sizeof(REAL))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); exit(0); } for(i=0;i<classn;i++) { fscanf(ifp_classifier,"%f",array_class_probability+i); } //array_probability_index is an array of the index of every property in array_probability if((array_probability_index=(int *)malloc(propertyn*sizeof(int)))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_class_probability); exit(0); } for(i=0;i<propertyn;i++) { array_probability_index[i] = 0; } array_probability_length = array_valuen[0] * classn; array_probability_index[0] = 0; if(propertyn>1) { for(i=1;i<propertyn;i++) { array_probability_length += array_valuen[i] * classn; array_probability_index[i] = array_valuen[i-1] * classn + array_probability_index[i-1]; } } //array_probability is an array of probability of every property of every class if((array_probability=(REAL *)malloc(array_probability_length*(sizeof(REAL))))==NULL) { printf("memory alloc error!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_class_probability); exit(0); } for(i=0;i<propertyn;i++) { for(j=0;j<array_valuen[i];j++) { for(k=0;k<classn;k++) { fscanf(ifp_classifier,"%f",&array_probability[ array_probability_index[i] + j*classn + k ]); } } } printf("Classifier initialize done!\n"); printf("Begin classify the dataset\n"); fscanf(ifp,"%d",&linen); //array_test is an array of the input data if((array_test=(int *)malloc(linen*propertyn*sizeof(int)))==NULL) { printf("Memory alloc ERROR!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_probability); free(array_class_probability); exit(0); } for(i=0;i<linen*propertyn;i++) { fscanf(ifp,"%d",array_test+i); } //array_test_class is an array of the classify result of every test data record if((array_test_class=(int *)malloc(linen*sizeof(int)))==NULL) { printf("Memory alloc ERROR!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_probability); free(array_class_probability); free(array_test); exit(0); } //array_test_class_probability is an array of the probability of every test data record of every class if((array_test_class_probability=(REAL *)malloc(linen*classn*sizeof(REAL)))==NULL) { printf("Memory alloc ERROR!\n"); fclose(ifp); fclose(ofp); free(array_valuen); free(array_probability); free(array_class_probability); free(array_test_class); free(array_test); exit(0); } end = microtime(); printf("\nalloc memory and reading data consuming time: %fs\n\n",end-begin); begin = end; #pragma offload target(mic) \ nocopy(array_test_class_probability:length(linen*classn) alloc_if(1) free_if(1)) \ in(array_class_probability:length(classn)) \ in(array_probability:length(array_probability_length)) \ in(array_probability_index:length(propertyn)) \ in(array_test:length(linen*propertyn)) \ out(array_test_class:length(linen)) #pragma omp parallel for for(i=0;i<linen;i++) { for(j=0;j<classn;j++) { array_test_class_probability[i*classn+j] = log( array_class_probability[j] ); } for(j=0;j<propertyn;j++) { for(k=0;k<classn;k++) { array_test_class_probability[i*classn+k] += log( array_probability[ array_probability_index[j] + array_test[i*propertyn+j]*classn + k] ); // printf("j=%d k=%d p=%f\n",j,k,array_test_class_probability[i*classn+k]); } } // exit(0); max=0; for(j=0;j<classn;j++) { if(array_test_class_probability[i*classn+j]-array_test_class_probability[i*classn+max]>EPSILON) { max=j; } } array_test_class[i]=max; } end = microtime(); printf("\nclassify the data consuming time: %fs\n\n",end - begin); begin = end; printf("Classify done\n"); for(i=0;i<linen;i++) { fprintf(ofp,"%d %d\n",i,array_test_class[i]); } printf("Result outputed to %s\n",ofn); fclose(ifp); fclose(ofp); free(array_valuen); free(array_probability); free(array_class_probability); free(array_test_class); free(array_test_class_probability); free(array_test); return 0; }
critical.c
/* This program finds number of threads*(sum of n elements) using critical construct in parallel region. This can be used instead of reduction in RaceConditions. * Sai Suraj * 20/09/2021 * */ #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc, char* argv[]) { omp_set_num_threads(8); int total = 0; #pragma omp parallel default(none) shared(total) { int my_value = 1; int n = 10; for(int i = 2; i <= n; i++) { my_value += i; } #pragma omp critical { printf("[Thread %d] Total before I add my value (%d): %d.\n", omp_get_thread_num(), my_value, total); total += my_value; printf("[Thread %d] Total after I added my value: %d.\n", omp_get_thread_num(), total); } printf("Product of Sum of first %d numbers and %d Threads is %d. \n",n,omp_get_num_threads(),total); } return 0; }
cnvt_coord.c
/******************************************************************************* * 2pt/cnvt_coord.c: this file is part of the FCFC program. * FCFC: Fast Correlation Function Calculator. * Github repository: https://github.com/cheng-zhao/FCFC * Copyright (c) 2020 -- 2021 Cheng Zhao <zhaocheng03@gmail.com> [MIT license] *******************************************************************************/ #include "define.h" #include "read_file.h" #include "timsort.h" #include "cspline.h" #include "legauss.h" #include "cnvt_coord.h" #include <stdlib.h> #include <limits.h> #include <float.h> #include <math.h> #ifdef OMP #include <omp.h> #endif /*============================================================================*\ Functions for coordinate interpolation \*============================================================================*/ /****************************************************************************** Function `read_sample`: Read sample points from a file. Arguments: * `fname`: name of the file for coordinate conversion; * `cnvt`: the structure for coordinate interpolation. Return: Zero on success; non-zero on error. ******************************************************************************/ static int read_sample(const char *fname, COORD_CNVT *cnvt) { if (!fname || !cnvt) return FCFC_ERR_ARG; if (read_ascii_table(fname, &cnvt->z, &cnvt->d, &cnvt->nsp)) return FCFC_ERR_FILE; /* Sort the sample points. */ tim_sort(cnvt->z, cnvt->d, cnvt->nsp); return 0; } /****************************************************************************** Function `sample_interp`: Interpolate the coordinate conversion samples with binary search. Arguments: * `cnvt`: data structure for storing sample points; * `z`: the redshift to be converted to a comoving distance. Return: The radial comoving distance on success; HUGE_VAL on error. ******************************************************************************/ static inline double sample_interp(const COORD_CNVT *cnvt, const double z) { size_t i, l, u; i = l = 0; u = cnvt->nsp - 1; if (z < cnvt->z[l] || z >= cnvt->z[u]) return HUGE_VAL; while (l <= u) { i = (l + u) >> 1; if (cnvt->z[i + 1] <= z) l = i + 1; else if (cnvt->z[i] > z) u = i - 1; else break; } return cspline_eval(cnvt->z, cnvt->d, cnvt->ypp, z, i); } /****************************************************************************** Function `cnvt_coord_interp`: Apply coordinate conversion for a catalog using cubic spline interpolation. Arguments: * `cnvt`: data structure for storing sample points; * `data`: data strucutre for the coordinates; * `ndata`: number of objects. ******************************************************************************/ static void cnvt_coord_interp(const COORD_CNVT *cnvt, DATA *data, const size_t ndata) { #ifdef OMP #pragma omp parallel for #endif for (size_t i = 0; i < ndata; i++) { double ra = data[i].x[0] * DEGREE_2_RAD; double dec = data[i].x[1] * DEGREE_2_RAD; double dist = sample_interp(cnvt, data[i].x[2]); data[i].x[0] = dist * cos(dec) * cos(ra); data[i].x[1] = dist * cos(dec) * sin(ra); data[i].x[2] = dist * sin(dec); } } /*============================================================================*\ Functions for coordinate integration \*============================================================================*/ /****************************************************************************** Function `cnvt_z_sample`: Sample redshifts uniformly in the redshift range of a catalog. Arguments: * `data`: structure for storing the input catalog; * `ndata`: number of elements of the input catalog; * `num`: number of sample points for the redshifts. Return: Address of the sampled redshift array. ******************************************************************************/ static double *cnvt_z_sample(const DATA *data, const size_t ndata, const int num) { if (num < 1) return NULL; double zmax = -DBL_MAX; double zmin = DBL_MAX; #ifdef OMP const int nomp = omp_get_max_threads(); double *pmax; /* thread-private maximum redshift */ double *pmin; /* thread-private minimum redshift */ if (!(pmax = malloc(nomp * sizeof(double)))) { P_ERR("failed to allocate memory for thread-private redshift\n"); return NULL; } if (!(pmin = malloc(nomp * sizeof(double)))) { P_ERR("failed to allocate memory for thread-private redshift\n"); free(pmax); return NULL; } for (int i = 0; i < nomp; i++) { pmax[i] = -DBL_MAX; pmin[i] = DBL_MAX; } /* Determine the minimum and maximum redshift of the samples. */ #pragma omp parallel num_threads(nomp) { const int tid = omp_get_thread_num(); #pragma omp for #endif for (size_t n = 0; n < ndata; n++) { double z = data[n].x[2]; if (z < 0) { P_ERR("invalid negative redshift in the data catalog:\n" "(%g, %g, %g)\n", data[n].x[0], data[n].x[1], data[n].x[2]); #ifdef OMP exit(FCFC_ERR_DATA); #else return NULL; #endif } #ifdef OMP if (pmax[tid] < z) pmax[tid] = z; if (pmin[tid] > z) pmin[tid] = z; #else if (zmax < z) zmax = z; if (zmin > z) zmin = z; #endif } #ifdef OMP } /* Gather the largest redshift from all threads. */ for (int i = 0; i < nomp; i++) { if (zmax < pmax[i]) zmax = pmax[i]; if (zmin > pmin[i]) zmin = pmin[i]; } free(pmax); free(pmin); #endif if (zmin > zmax) { P_ERR("invalid redshift value in the catalogs\n"); return NULL; } /* Generate sample points. */ double *zsp = malloc(num * sizeof(double)); if (!zsp) { P_ERR("failed to allocate memory for sample points of redshifts\n"); return NULL; } for (int i = 0; i < num; i++) zsp[i] = zmin + i * (zmax - zmin) / (num - 1); return zsp; } /****************************************************************************** Function `cnvt_integrand`: Integrand for the redshift to radial comoving distance conversion. Arguments: * `Omega_m`: density parameter of matter at z = 0; * `Omega_L`: density parameter of Lambda at z = 0; * `Omega_k`: density parameter of curvature at z = 0; * `widx`: power index related to the dark energy equation of state; * `z`: the redshift to be converted to comoving distance; Return: The integrand for comoving distance integration. ******************************************************************************/ static inline double cnvt_integrand(const double Omega_m, const double Omega_L, const double Omega_k, const double widx, const double z) { double z1 = z + 1; double z2 = z1 * z1; double d = Omega_m * z2 * z1; if (Omega_k) d += Omega_k * z2; if (widx) d += Omega_L * pow(z1, widx); else d += Omega_L; d = SPEED_OF_LIGHT * 0.01 / sqrt(d); return d; } /****************************************************************************** Function `cnvt_legauss`: Convert redshift to comoving distance using the Legendre-Gauss integration. Arguments: * `Omega_m`: density parameter of matter at z = 0; * `Omega_L`: density parameter of Lambda at z = 0; * `Omega_k`: density parameter of curvature at z = 0; * `widx`: power index related to the dark energy equation of state; * `order`: order of the integration; * `z`: redshift to be converted to comoving distance; Return: The radial comoving distance on success; HUGE_VAL on error. ******************************************************************************/ static inline double cnvt_legauss(const double Omega_m, const double Omega_L, const double Omega_k, const double widx, const int order, const double z) { /* Variable transformation for integration from 0 to z. */ double zp = z * 0.5; double sum = 0; int i; for (i = LEGAUSS_IDX(order); i < LEGAUSS_IDX(order) + LEGAUSS_LEN_NONZERO(order); i++) { /* Look up the abscissas and weights. */ double x = legauss_x[i]; double w = legauss_w[i]; /* Integrate for both positive and negative abscissas. */ double z1 = zp * (1 + x); double z2 = zp * (1 - x); sum += w * (cnvt_integrand(Omega_m, Omega_L, Omega_k, widx, z1) + cnvt_integrand(Omega_m, Omega_L, Omega_k, widx, z2)); } /* For odd orders, there is also the abscissas x = 0. */ if (order & 1) sum += legauss_w[i] * cnvt_integrand(Omega_m, Omega_L, Omega_k, widx, zp); return sum * zp; } /****************************************************************************** Function `cnvt_legauss_order`: Check the order of Legendre-Gauss integration given the desired precision. Arguments: * `Omega_m`: density parameter of matter at z = 0; * `Omega_L`: density parameter of Lambda at z = 0; * `Omega_k`: density parameter of curvature at z = 0; * `widx`: power index related to the dark energy equation of state; * `err`: maximum allowed error for the integration; * `data`: structure for storing the input catalog; * `ndata`: number of elements of the input catalog; * `num`: the length of the redshift array. Return: The order on success; INT_MAX on error. ******************************************************************************/ static int cnvt_legauss_order(const double Omega_m, const double Omega_L, const double Omega_k, const double widx, const double err, const DATA *data, const size_t ndata, const int num) { /* Uniformly sample redshifts from the data. */ double *ztest = cnvt_z_sample(data, ndata, num); if (!ztest) return INT_MAX; int order = 0; #ifdef OMP #pragma omp parallel { int priv = 0; #pragma omp for #endif for (int i = 0; i < num; i++) { double oint, nint = 0; int n = LEGAUSS_MIN_ORDER - 1; do { if (n > LEGAUSS_MAX_ORDER) { n = INT_MAX; break; } oint = nint; nint = cnvt_legauss(Omega_m, Omega_L, Omega_k, widx, ++n, ztest[i]); } while (fabs(nint - oint) > nint * err); #ifdef OMP if (priv < n) priv = n; #else if (order < n) order = n; #endif } #ifdef OMP #pragma omp critical if (order < priv) order = priv; } #endif free(ztest); return order; } /****************************************************************************** Function `cnvt_cata_integr`: Apply coordinate conversion for a catalog with integration. Arguments: * `Omega_m`: density parameter of matter at z = 0; * `Omega_L`: density parameter of Lambda at z = 0; * `Omega_k`: density parameter of curvature at z = 0; * `widx`: power index related to the dark energy equation of state; * `order`: order of the integration; * `data`: data strucutre for the coordinates; * `ndata`: number of objects. ******************************************************************************/ static void cnvt_coord_integr(const double Omega_m, const double Omega_L, const double Omega_k, const double widx, const int order, DATA *data, const size_t ndata) { #ifdef OMP #pragma omp parallel for #endif for (size_t i = 0; i < ndata; i++) { double ra = data[i].x[0] * DEGREE_2_RAD; double dec = data[i].x[1] * DEGREE_2_RAD; double dist = cnvt_legauss(Omega_m, Omega_L, Omega_k, widx, order, data[i].x[2]); data[i].x[0] = dist * cos(dec) * cos(ra); data[i].x[1] = dist * cos(dec) * sin(ra); data[i].x[2] = dist * sin(dec); } } /*============================================================================*\ Interfaces for coordinate conversion \*============================================================================*/ /****************************************************************************** Function `cnvt_init`: Initialise the structure for coordinate conversion. Return: Address of the structure. ******************************************************************************/ COORD_CNVT *cnvt_init(void) { COORD_CNVT *cnvt = malloc(sizeof *cnvt); if (!cnvt) return NULL; cnvt->nsp = 0; cnvt->z = cnvt->d = cnvt->ypp = NULL; return cnvt; } /****************************************************************************** Function `cnvt_destroy`: Deconstruct the structure for coordinate conversion. Arguments: * `cnvt`: the structure to be deconstrcuted. ******************************************************************************/ void cnvt_destroy(COORD_CNVT *cnvt) { if (!cnvt) return; if (cnvt->z) free(cnvt->z); if (cnvt->d) free(cnvt->d); if (cnvt->ypp) free(cnvt->ypp); free(cnvt); } /****************************************************************************** Function `cnvt_coord`: Interface for applying coordinate conversion. Arguments: * `conf`: the structure for configurations; * `data`: structure for storing the input catalog; * `ndata`: number of elements of the input catalog; * `coord`: structure for redshift to comoving distance interpolation. Return: Zero on success; non-zero on error. ******************************************************************************/ int cnvt_coord(const CONF *conf, DATA *data, const size_t ndata, COORD_CNVT *coord) { if (!conf) { P_ERR("configuration parameters not loaded\n"); return FCFC_ERR_CONF; } if (!data) { P_ERR("catalog not read before applying coordinate concersion\n"); return FCFC_ERR_CNVT; } /* Apply coordinate conversion. */ if (conf->fcnvt) { /* binary search and cubic spline interpolation */ if (!coord) { P_ERR("coordinate interpolation not initialised\n"); return FCFC_ERR_CNVT; } /* Setup the interpolation sample. */ if (!coord->nsp) { /* Read the sample from file. */ if (read_sample(conf->fcnvt, coord)) return FCFC_ERR_FILE; /* Compute the second derivative for cubic spline interpolation. */ if (!(coord->ypp = cspline_ypp(coord->z, coord->d, coord->nsp))) { P_ERR("failed to interpolate the sample coordinates for conversion\n"); return FCFC_ERR_CNVT; } } /* Apply cubic spline interpolation. */ cnvt_coord_interp(coord, data, ndata); if (conf->verbose) printf(" Coordinates converted using cubic spline interpolation\n"); } else { /* Legendre-Gauss integration */ /* Pre-compute the power index for Lambda. */ double widx = (conf->dew == -1) ? 0 : 3 * (1 + conf->dew); /* Choose the integration order via convergency test. */ int order = cnvt_legauss_order(conf->omega_m, conf->omega_l, conf->omega_k, widx, conf->ecnvt, data, ndata, FCFC_INT_NUM_ZSP); if (order == INT_MAX) { P_ERR("failed to perform the convergency test for integrations.\n"); return FCFC_ERR_CNVT; } /* Apply Legendre-Gauss integration. */ cnvt_coord_integr(conf->omega_m, conf->omega_l, conf->omega_k, widx, order, data, ndata); if (conf->verbose) printf(" Coordinates converted using Legendre-Gauss integration " "with order %d\n", order); } return 0; }
vector.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) ******************************************************************************/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "_hypre_utilities.hpp" //RL: TODO vector_device.c, include cuda there #include "seq_mv.h" /*-------------------------------------------------------------------------- * hypre_SeqVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector *hypre_SeqVectorCreate(HYPRE_Int size) { hypre_Vector *vector; vector = hypre_CTAlloc(hypre_Vector, 1, HYPRE_MEMORY_HOST); hypre_VectorData(vector) = NULL; hypre_VectorSize(vector) = size; hypre_VectorNumVectors(vector) = 1; hypre_VectorMultiVecStorageMethod(vector) = 0; /* set defaults */ hypre_VectorOwnsData(vector) = 1; hypre_VectorMemoryLocation(vector) = hypre_HandleMemoryLocation(hypre_handle()); return vector; } /*-------------------------------------------------------------------------- * hypre_SeqMultiVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector *hypre_SeqMultiVectorCreate(HYPRE_Int size, HYPRE_Int num_vectors) { hypre_Vector *vector = hypre_SeqVectorCreate(size); hypre_VectorNumVectors(vector) = num_vectors; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorDestroy(hypre_Vector *vector) { HYPRE_Int ierr = 0; if (vector) { HYPRE_MemoryLocation memory_location = hypre_VectorMemoryLocation(vector); if (hypre_VectorOwnsData(vector)) { hypre_TFree(hypre_VectorData(vector), memory_location); } hypre_TFree(vector, HYPRE_MEMORY_HOST); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorInitialize_v2(hypre_Vector *vector, HYPRE_MemoryLocation memory_location) { HYPRE_Int size = hypre_VectorSize(vector); HYPRE_Int ierr = 0; HYPRE_Int num_vectors = hypre_VectorNumVectors(vector); HYPRE_Int multivec_storage_method = hypre_VectorMultiVecStorageMethod(vector); hypre_VectorMemoryLocation(vector) = memory_location; /* Caveat: for pre-existing data, the memory location must be guaranteed * to be consistent with `memory_location' * Otherwise, mismatches will exist and problems will be encountered * when being used, and freed */ if (!hypre_VectorData(vector)) { hypre_VectorData(vector) = hypre_CTAlloc(HYPRE_Complex, num_vectors * size, memory_location); } if (multivec_storage_method == 0) { hypre_VectorVectorStride(vector) = size; hypre_VectorIndexStride(vector) = 1; } else if (multivec_storage_method == 1) { hypre_VectorVectorStride(vector) = 1; hypre_VectorIndexStride(vector) = num_vectors; } else { ++ierr; } return ierr; } HYPRE_Int hypre_SeqVectorInitialize(hypre_Vector *vector) { HYPRE_Int ierr; ierr = hypre_SeqVectorInitialize_v2(vector, hypre_VectorMemoryLocation(vector)); return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetDataOwner(hypre_Vector *vector, HYPRE_Int owns_data) { HYPRE_Int ierr = 0; hypre_VectorOwnsData(vector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * ReadVector *--------------------------------------------------------------------------*/ hypre_Vector *hypre_SeqVectorRead(char *file_name) { hypre_Vector *vector; FILE *fp; HYPRE_Complex *data; HYPRE_Int size; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &size); vector = hypre_SeqVectorCreate(size); hypre_VectorMemoryLocation(vector) = HYPRE_MEMORY_HOST; hypre_SeqVectorInitialize(vector); data = hypre_VectorData(vector); for (j = 0; j < size; j++) { hypre_fscanf(fp, "%le", &data[j]); } fclose(fp); /* multivector code not written yet */ hypre_assert(hypre_VectorNumVectors(vector) == 1); return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorPrint(hypre_Vector *vector, char *file_name) { FILE *fp; HYPRE_Complex *data; HYPRE_Int size, num_vectors, vecstride, idxstride; HYPRE_Int i, j; HYPRE_Complex value; HYPRE_Int ierr = 0; num_vectors = hypre_VectorNumVectors(vector); vecstride = hypre_VectorVectorStride(vector); idxstride = hypre_VectorIndexStride(vector); /*---------------------------------------------------------- * Print in the data *----------------------------------------------------------*/ data = hypre_VectorData(vector); size = hypre_VectorSize(vector); fp = fopen(file_name, "w"); if (hypre_VectorNumVectors(vector) == 1) { hypre_fprintf(fp, "%d\n", size); } else { hypre_fprintf(fp, "%d vectors of size %d\n", num_vectors, size); } if (num_vectors > 1) { for (j = 0; j < num_vectors; ++j) { hypre_fprintf(fp, "vector %d\n", j); for (i = 0; i < size; i++) { value = data[j * vecstride + i * idxstride]; #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(value), hypre_cimag(value)); #else hypre_fprintf(fp, "%.14e\n", value); #endif } } } else { for (i = 0; i < size; i++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(data[i]), hypre_cimag(data[i])); #else hypre_fprintf(fp, "%.14e\n", data[i]); #endif } } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetConstantValues(hypre_Vector *v, HYPRE_Complex value) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int ierr = 0; size *= hypre_VectorNumVectors(v); // hypre_SeqVectorPrefetch(v, HYPRE_MEMORY_DEVICE); #if defined(HYPRE_USING_CUDA) if (size > 0) { HYPRE_THRUST_CALL(fill_n, vector_data, size, value); } #else HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) \ is_device_ptr(vector_data) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) { vector_data[i] = value; } #endif /* defined(HYPRE_USING_CUDA) */ #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetRandomValues(hypre_Vector *v, HYPRE_Int seed) { HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int i; HYPRE_Int ierr = 0; hypre_SeedRand(seed); size *= hypre_VectorNumVectors(v); if (hypre_GetActualMemLocation(hypre_VectorMemoryLocation(v)) == hypre_MEMORY_HOST) { /* RDF: threading this loop may cause problems because of hypre_Rand() */ for (i = 0; i < size; i++) { vector_data[i] = 2.0 * hypre_Rand() - 1.0; } } else { HYPRE_Complex *h_data = hypre_TAlloc(HYPRE_Complex, size, HYPRE_MEMORY_HOST); for (i = 0; i < size; i++) { h_data[i] = 2.0 * hypre_Rand() - 1.0; } hypre_TMemcpy(vector_data, h_data, HYPRE_Complex, size, hypre_VectorMemoryLocation(v), HYPRE_MEMORY_HOST); hypre_TFree(h_data, HYPRE_MEMORY_HOST); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCopy * copies data from x to y * if size of x is larger than y only the first size_y elements of x are * copied to y *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorCopy(hypre_Vector *x, hypre_Vector *y) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Int ierr = 0; size_t size = hypre_min(hypre_VectorSize(x), hypre_VectorSize(y)) * hypre_VectorNumVectors(x); hypre_TMemcpy(hypre_VectorData(y), hypre_VectorData(x), HYPRE_Complex, size, hypre_VectorMemoryLocation(y), hypre_VectorMemoryLocation(x)); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneDeep * Returns a complete copy of x - a deep copy, with its own copy of the data. *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneDeep_v2(hypre_Vector *x, HYPRE_MemoryLocation memory_location) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector *y = hypre_SeqMultiVectorCreate(size, num_vectors); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_SeqVectorInitialize_v2(y, memory_location); hypre_SeqVectorCopy(x, y); return y; } hypre_Vector *hypre_SeqVectorCloneDeep(hypre_Vector *x) { return hypre_SeqVectorCloneDeep_v2(x, hypre_VectorMemoryLocation(x)); } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneShallow * Returns a complete copy of x - a shallow copy, pointing the data of x *--------------------------------------------------------------------------*/ hypre_Vector *hypre_SeqVectorCloneShallow(hypre_Vector *x) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector *y = hypre_SeqMultiVectorCreate(size, num_vectors); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_VectorMemoryLocation(y) = hypre_VectorMemoryLocation(x); hypre_VectorData(y) = hypre_VectorData(x); hypre_SeqVectorSetDataOwner(y, 0); hypre_SeqVectorInitialize(y); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorScale(HYPRE_Complex alpha, hypre_Vector *y) { /* special cases */ if (alpha == 1.0) { return 0; } if (alpha == 0.0) { return hypre_SeqVectorSetConstantValues(y, 0.0); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(y); HYPRE_Int ierr = 0; size *= hypre_VectorNumVectors(y); // hypre_SeqVectorPrefetch(y, HYPRE_MEMORY_DEVICE); #if defined(HYPRE_USING_CUDA) #if defined(HYPRE_USING_CUBLAS) HYPRE_CUBLAS_CALL(cublasDscal(hypre_HandleCublasHandle(hypre_handle()), size, &alpha, y_data, 1)); #else HYPRE_THRUST_CALL(transform, y_data, y_data + size, y_data, alpha * _1); #endif #else HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) \ is_device_ptr(y_data) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) { y_data[i] *= alpha; } #endif /* defined(HYPRE_USING_CUDA) */ #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorAxpy(HYPRE_Complex alpha, hypre_Vector *x, hypre_Vector *y) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int ierr = 0; size *= hypre_VectorNumVectors(x); // hypre_SeqVectorPrefetch(x, HYPRE_MEMORY_DEVICE); // hypre_SeqVectorPrefetch(y, HYPRE_MEMORY_DEVICE); #ifndef __ve__ #if defined(HYPRE_USING_CUDA) #if defined(HYPRE_USING_CUBLAS) HYPRE_CUBLAS_CALL(cublasDaxpy(hypre_HandleCublasHandle(hypre_handle()), size, &alpha, x_data, 1, y_data, 1)); #else HYPRE_THRUST_CALL(transform, x_data, x_data + size, y_data, y_data, alpha * _1 + _2); #endif #else HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) \ is_device_ptr(y_data, x_data) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) { y_data[i] += alpha * x_data[i]; } #endif /* defined(HYPRE_USING_CUDA) */ #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif #else int i; #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE for (i = 0; i < size; i++) { y_data[i] += alpha * x_data[i]; } #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_SeqVectorInnerProd(hypre_Vector *x, hypre_Vector *y) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Real result = 0.0; size *= hypre_VectorNumVectors(x); // hypre_SeqVectorPrefetch(x, HYPRE_MEMORY_DEVICE); // hypre_SeqVectorPrefetch(y, HYPRE_MEMORY_DEVICE); #ifndef __ve__ #if defined(HYPRE_USING_CUDA) #ifndef HYPRE_COMPLEX #if defined(HYPRE_USING_CUBLAS) HYPRE_CUBLAS_CALL(cublasDdot(hypre_HandleCublasHandle(hypre_handle()), size, x_data, 1, y_data, 1, &result)); #else result = HYPRE_THRUST_CALL(inner_product, x_data, x_data + size, y_data, 0.0); #endif #else /* TODO */ #error "Complex inner product" #endif #else /* #if defined(HYPRE_USING_CUDA) */ HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) reduction(+:result) is_device_ptr(y_data,x_data) map(result) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) reduction(+ : result) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) { result += hypre_conj(y_data[i]) * x_data[i]; } #endif /* defined(HYPRE_USING_CUDA) */ #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP) hypre_SyncCudaComputeStream(hypre_handle()); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif #else #ifndef HYPRE_COMPLEX HYPRE_Int i; #if defined(HYPRE_USING_OPENMP) #pragma omp parallel shared(result) { HYPRE_Int num_threads = omp_get_num_threads(); // hypre_NumActiveThreads(); HYPRE_Int thread_id = omp_get_thread_num(); // hypre_GetThreadNum(); HYPRE_Int chunk = (size + num_threads - 1) / num_threads; HYPRE_Int strt = chunk * thread_id; HYPRE_Int end = size < (strt + chunk) ? size : (strt + chunk); double t_result = 0; for (i = strt; i < end; i++) t_result += y_data[i] * x_data[i]; #pragma omp atomic result += t_result; } #else for (i = 0; i < size; i++) result += y_data[i] * x_data[i]; #endif #else /* TODO */ #error "Complex inner product" #endif #endif return result; } // TODO /*-------------------------------------------------------------------------- * hypre_VectorSumElts: * Returns the sum of all vector elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_SeqVectorSumElts(hypre_Vector *vector) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_VectorData(vector); HYPRE_Int size = hypre_VectorSize(vector); HYPRE_Int i; #ifndef __ve__ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) reduction(+ : sum) HYPRE_SMP_SCHEDULE #endif #endif for (i = 0; i < size; ++i) sum += data[i]; return sum; } HYPRE_Int hypre_SeqVectorPrefetch(hypre_Vector *x, HYPRE_MemoryLocation memory_location) { HYPRE_Int ierr = 0; #ifdef HYPRE_USING_UNIFIED_MEMORY if (hypre_VectorMemoryLocation(x) != HYPRE_MEMORY_DEVICE) { /* hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! CUDA Prefetch with * non-unified momory\n");*/ return 1; } HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Int size = hypre_VectorSize(x) * hypre_VectorNumVectors(x); if (size == 0) { return ierr; } hypre_MemPrefetch(x_data, sizeof(HYPRE_Complex) * size, memory_location); #endif return ierr; } #if 0 /* y[i] = max(alpha*x[i], beta*y[i]) */ HYPRE_Int hypre_SeqVectorMax( HYPRE_Complex alpha, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int ierr = 0; size *= hypre_VectorNumVectors(x); //hypre_SeqVectorPrefetch(x, HYPRE_MEMORY_DEVICE); //hypre_SeqVectorPrefetch(y, HYPRE_MEMORY_DEVICE); thrust::maximum<HYPRE_Complex> mx; #if defined(HYPRE_USING_CUDA) HYPRE_THRUST_CALL( transform, thrust::make_transform_iterator(x_data, alpha * _1), thrust::make_transform_iterator(x_data + size, alpha * _1), thrust::make_transform_iterator(y_data, beta * _1), y_data, mx ); #else HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) \ is_device_ptr(y_data, x_data) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) { y_data[i] += hypre_max(alpha * x_data[i], beta * y_data[i]); } #endif /* defined(HYPRE_USING_CUDA) */ hypre_SyncCudaComputeStream(hypre_handle()); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } #endif
util.c
#include <mpi.h> #include "precision.h" #include "util.h" /* Use the modified Gram-Schmidt process to compute (in place) the portion of * the n-dimensional vector v orthogonal to each of the nv vectors s. The * projection * of the vector onto each of the basis vectors is stored in the * length-nv array c. This is actually a selective reorthogonalization scheme * to attempt to correct rounding errors. */ int cmgs (cplx *v, cplx *c, cplx *s, long n, int nv) { long i, j; cplx *sv, cv; real vnrm, lcrit; /* Perform the first modified Gram Schmidt orthogonalization. */ for (i = 0, sv = s, lcrit = 0.; i < nv; ++i, sv += n) { /* The projection of the vector onto the current basis. */ c[i] = pardot (sv, v, n); /* Track the 1-norm of the projection column. */ lcrit += cabs(c[i]); #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] -= c[i] * sv[j]; } /* Compute the norm of the vector. */ c[nv] = parnorm (v, n); vnrm = creal(c[nv]); /* Reorthogonalize if necessary. */ if (lcrit / vnrm > IMGS_L) { for (i = 0, sv = s; i < nv; ++i, sv += n) { /* Re-project the vector onto the current basis. */ cv = pardot (sv, v, n); /* Update the projection. */ c[i] += cv; /* Remove the remaining parallel component. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] -= cv * sv[j]; } /* Update the norm of the orthogonal vector. */ c[nv] = parnorm (v, n); vnrm = creal(c[nv]); } /* Don't normalize if the norm is vanishing. */ if (vnrm < REAL_EPSILON) return n; /* Finally, normalize the newly-created vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] /= vnrm; return n; } /* Compute the inner product of the distributed vectors x and y of dimension n. */ cplx pardot (cplx *x, cplx *y, long n) { /* Always compute the product in double precision to avoid rounding errors. */ complex double dp = 0.0; long i; #pragma omp parallel for default(shared) private(i) reduction(+: dp) for (i = 0; i < n; ++i) dp += conj(x[i]) * y[i]; /* Add in the contributions from other processors. */ MPI_Allreduce (MPI_IN_PLACE, &dp, 2, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); return (cplx)dp; } real parnorm (cplx *x, long n) { /* Always compute the norm in double precision to avoid rounding errors. */ double nrm = 0.0, nr, ni; long i; #pragma omp parallel for default(shared) private(nr,ni,i) reduction(+: nrm) for (i = 0; i < n; ++i) { nr = creal(x[i]); nr *= nr; ni = cimag(x[i]); ni *= ni; nrm += nr + ni; } /* Sum over processors and reduce. */ MPI_Allreduce (MPI_IN_PLACE, &nrm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); return (real)sqrt(nrm); } /* The RMS error between a test vector and a reference. */ real mse (cplx *test, cplx *ref, long n, int nrm) { long i; real err[2] = {0.0, 0.0}, tmp; /* Calculate local contributions to the mean-squared error. */ for (i = 0; i < n; ++i) { tmp = cabs(test[i] - ref[i]); err[0] += tmp * tmp; tmp = cabs(ref[i]); err[1] += tmp * tmp; } /* Sum the local contributions. */ MPI_Allreduce (MPI_IN_PLACE, err, 2, MPIREAL, MPI_SUM, MPI_COMM_WORLD); /* Return the normalized MSE if desired, otherwise just the difference. */ if (nrm) return sqrt(err[0] / err[1]); return sqrt(err[0]); } /* Compute the sinc of the argument. */ real sinc (real x) { return ((fabs(x) < REAL_EPSILON) ? 1.0 : (sin (M_PI * x) / (M_PI * x))); } /* Compute the coordinates of the indexed far-field sample. */ int sampcoords (real *s, int i, int nt, int np) { int pi, ti; real st, theta, phi; /* The first sample is the south pole. * No further computation is required. */ if (i == 0) { s[0] = s[1] = 0.0; s[2] = -1.0; return 0; } /* Compute the sample indices in phi and theta. */ pi = (i - 1) % np; ti = (i - 1) / np + 1; /* The sample is the north pole at the final theta index. */ if (ti == nt - 1) { s[0] = s[1] = 0.0; s[2] = 1.0; return 0; } /* Compute the angular position from the sample indices. */ phi = 2 * M_PI * pi / (real) np; theta = M_PI * (1. - ti / (real) (nt - 1)); /* Compute the cartesian position. */ st = sin(theta); s[0] = cos(phi) * st; s[1] = sin(phi) * st; s[2] = cos(theta); return 0; } /* Compute the relative coordinates of a cell within a group of cells. */ int cellcoords (real *r, int l, int bpd, real dx) { int idx[3]; GRID(idx, l, bpd, bpd); r[0] = 0.5 * dx * (2.0 * idx[0] + 1.0 - (real)bpd); r[1] = 0.5 * dx * (2.0 * idx[1] + 1.0 - (real)bpd); r[2] = 0.5 * dx * (2.0 * idx[2] + 1.0 - (real)bpd); return 0; } /* Determine if the elemnt i is in the set s of length l. */ int inset (int i, int *s, int l) { int j; for (j = 0; j < l; ++j) if (i == s[j]) return 1; return 0; } /* Find the index of the maximum value in set of length n, ignoring indices in * the set excl of length nex. */ int maxind (cplx *set, int n, int *excl, int nex) { real mv, cv; int mi, i; for (i = 0, mv = -1.0, mi = -1; i < n; ++i) { /* Skip the element if it is in the exclusion list. */ if (inset(i, excl, nex)) continue; /* Determine if this value is the maximum. */ cv = cabs(set[i]); if (cv > mv) { mi = i; mv = cv; } } return mi; } /* Calculate the Legendre polynomial of order m and its derivative at a point t. */ static int legendre (real *p, real *dp, real t, int m) { real p0 = 1.0, p1 = t; int k; /* Handle low orders explicitly. */ if (m < 1) { *p = 1.0; *dp = 0.0; return m; } else if (m < 2) { *p = t; *dp = 1.0; return m; } /* Otherwise, calculate the function values recursively. */ for (k = 1; k < m; ++k) { *p = ((2.0 * k + 1.0) * t * p1 - k * p0) / (1.0 + k); p0 = p1; p1 = *p; } *dp = m * (p0 - t * p1) / (1.0 - t * t); return m; } /* Compute Gaussian quadrature nodes and weights. */ int gaussleg (real *nodes, real *weights, int m) { int i, j, nroots = (m + 1) / 2; real t, p, dp, dt; const real tol = REAL_EPSILON; const int maxit = 100; for (i = 0; i < nroots; ++i) { /* Use the Chebyshev roots as an initial guess. */ t = cos (M_PI * (i + 0.75) / (m + 0.5)); for (j = 0; j < maxit; ++j) { /* Compute the value of the Legendre polynomial. */ legendre (&p, &dp, t, m); /* Perform a Newton-Raphson update. */ dt = -p / dp; t += dt; /* Break if convergence detected. */ if (fabs(dt) < tol) break; } /* Update the nodes and weights. */ nodes[i] = t; nodes[m - i - 1] = -t; weights[i] = 2.0 / (1.0 - t * t) / (dp * dp); weights[m - i - 1] = weights[i]; } return 0; }
bug51781.c
// Use the generic state machine. On some architectures, other threads in the // main thread's warp must avoid barrier instructions. // // RUN: %libomptarget-compile-run-and-check-generic // SPMDize. There is no main thread, so there's no issue. // // RUN: %libomptarget-compile-generic -O1 -Rpass=openmp-opt > %t.spmd 2>&1 // RUN: %fcheck-nvptx64-nvidia-cuda -check-prefix=SPMD -input-file=%t.spmd // RUN: %fcheck-amdgcn-amd-amdhsa -check-prefix=SPMD -input-file=%t.spmd // RUN: %libomptarget-run-generic 2>&1 | %fcheck-generic // // SPMD: Transformed generic-mode kernel to SPMD-mode. // Use the custom state machine, which must avoid the same barrier problem as // the generic state machine. // // RUN: %libomptarget-compile-generic -O1 -Rpass=openmp-opt \ // RUN: -mllvm -openmp-opt-disable-spmdization > %t.custom 2>&1 // RUN: %fcheck-nvptx64-nvidia-cuda -check-prefix=CUSTOM -input-file=%t.custom // RUN: %fcheck-amdgcn-amd-amdhsa -check-prefix=CUSTOM -input-file=%t.custom // RUN: %libomptarget-run-generic 2>&1 | %fcheck-generic // // CUSTOM: Rewriting generic-mode kernel with a customized state machine. #include <stdio.h> int main() { int x = 0, y = 1; #pragma omp target teams num_teams(1) map(tofrom:x, y) { x = 5; #pragma omp parallel y = 6; } // CHECK: 5, 6 printf("%d, %d\n", x, y); return 0; }
morphology.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y % % MM MM O O R R P P H H O O L O O G Y Y % % M M M O O RRRR PPPP HHHHH O O L O O G GGG Y % % M M O O R R P H H O O L O O G G Y % % M M OOO R R P H H OOO LLLLL OOO GGG Y % % % % % % MagickCore Morphology Methods % % % % Software Design % % Anthony Thyssen % % January 2010 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Morphology is the application of various kernels, of any size or shape, to an % image in various ways (typically binary, but not always). % % Convolution (weighted sum or average) is just one specific type of % morphology. Just one that is very common for image bluring and sharpening % effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring. % % This module provides not only a general morphology function, and the ability % to apply more advanced or iterative morphologies, but also functions for the % generation of many different types of kernel arrays from user supplied % arguments. Prehaps even the generation of a kernel from a small image. */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology.h" #include "MagickCore/morphology-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/prepress.h" #include "MagickCore/quantize.h" #include "MagickCore/resource_.h" #include "MagickCore/registry.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" /* Other global definitions used by module. */ #define Minimize(assign,value) assign=MagickMin(assign,value) #define Maximize(assign,value) assign=MagickMax(assign,value) /* Integer Factorial Function - for a Binomial kernel */ #if 1 static inline size_t fact(size_t n) { size_t f,l; for(f=1, l=2; l <= n; f=f*l, l++); return(f); } #elif 1 /* glibc floating point alternatives */ #define fact(n) ((size_t)tgamma((double)n+1)) #else #define fact(n) ((size_t)lgamma((double)n+1)) #endif /* Currently these are only internal to this module */ static void CalcKernelMetaData(KernelInfo *), ExpandMirrorKernelInfo(KernelInfo *), ExpandRotateKernelInfo(KernelInfo *, const double), RotateKernelInfo(KernelInfo *, double); /* Quick function to find last kernel in a kernel list */ static inline KernelInfo *LastKernelInfo(KernelInfo *kernel) { while (kernel->next != (KernelInfo *) NULL) kernel=kernel->next; return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelInfo() takes the given string (generally supplied by the % user) and converts it into a Morphology/Convolution Kernel. This allows % users to specify a kernel from a number of pre-defined kernels, or to fully % specify their own kernel for a specific Convolution or Morphology % Operation. % % The kernel so generated can be any rectangular array of floating point % values (doubles) with the 'control point' or 'pixel being affected' % anywhere within that array of values. % % Previously IM was restricted to a square of odd size using the exact % center as origin, this is no longer the case, and any rectangular kernel % with any value being declared the origin. This in turn allows the use of % highly asymmetrical kernels. % % The floating point values in the kernel can also include a special value % known as 'nan' or 'not a number' to indicate that this value is not part % of the kernel array. This allows you to shaped the kernel within its % rectangular area. That is 'nan' values provide a 'mask' for the kernel % shape. However at least one non-nan value must be provided for correct % working of a kernel. % % The returned kernel should be freed using the DestroyKernelInfo() when you % are finished with it. Do not free this memory yourself. % % Input kernel defintion strings can consist of any of three types. % % "name:args[[@><]" % Select from one of the built in kernels, using the name and % geometry arguments supplied. See AcquireKernelBuiltIn() % % "WxH[+X+Y][@><]:num, num, num ..." % a kernel of size W by H, with W*H floating point numbers following. % the 'center' can be optionally be defined at +X+Y (such that +0+0 % is top left corner). If not defined the pixel in the center, for % odd sizes, or to the immediate top or left of center for even sizes % is automatically selected. % % "num, num, num, num, ..." % list of floating point numbers defining an 'old style' odd sized % square kernel. At least 9 values should be provided for a 3x3 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc. % Values can be space or comma separated. This is not recommended. % % You can define a 'list of kernels' which can be used by some morphology % operators A list is defined as a semi-colon separated list kernels. % % " kernel ; kernel ; kernel ; " % % Any extra ';' characters, at start, end or between kernel defintions are % simply ignored. % % The special flags will expand a single kernel, into a list of rotated % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree % cyclic rotations, while a '>' will generate a list of 90-degree rotations. % The '<' also exands using 90-degree rotates, but giving a 180-degree % reflected kernel before the +/- 90-degree rotations, which can be important % for Thinning operations. % % Note that 'name' kernels will start with an alphabetic character while the % new kernel specification has a ':' character in its specification string. % If neither is the case, it is assumed an old style of a simple list of % numbers generating a odd-sized square kernel has been given. % % The format of the AcquireKernal method is: % % KernelInfo *AcquireKernelInfo(const char *kernel_string) % % A description of each parameter follows: % % o kernel_string: the Morphology/Convolution kernel wanted. % */ /* This was separated so that it could be used as a separate ** array input handling function, such as for -color-matrix */ static KernelInfo *ParseKernelArray(const char *kernel_string) { KernelInfo *kernel; char token[MagickPathExtent]; const char *p, *end; register ssize_t i; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ MagickStatusType flags; GeometryInfo args; kernel=(KernelInfo *) AcquireQuantumMemory(1,sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) memset(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = UserDefinedKernel; kernel->next = (KernelInfo *) NULL; kernel->signature=MagickCoreSignature; if (kernel_string == (const char *) NULL) return(kernel); /* find end of this specific kernel definition string */ end = strchr(kernel_string, ';'); if ( end == (char *) NULL ) end = strchr(kernel_string, '\0'); /* clear flags - for Expanding kernel lists thorugh rotations */ flags = NoValue; /* Has a ':' in argument - New user kernel specification FUTURE: this split on ':' could be done by StringToken() */ p = strchr(kernel_string, ':'); if ( p != (char *) NULL && p < end) { /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, kernel_string, (size_t) (p-kernel_string)); token[p-kernel_string] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); /* Size handling and checks of geometry settings */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 1.0; /* then width = 1 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ kernel->width = (size_t)args.rho; kernel->height = (size_t)args.sigma; /* Offset Handling and Checks */ if ( args.xi < 0.0 || args.psi < 0.0 ) return(DestroyKernelInfo(kernel)); kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi : (ssize_t) (kernel->width-1)/2; kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi : (ssize_t) (kernel->height-1)/2; if ( kernel->x >= (ssize_t) kernel->width || kernel->y >= (ssize_t) kernel->height ) return(DestroyKernelInfo(kernel)); p++; /* advance beyond the ':' */ } else { /* ELSE - Old old specification, forming odd-square kernel */ /* count up number of values given */ p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ for (i=0; p < end; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); } /* set the size of the kernel - old sized square */ kernel->width = kernel->height= (size_t) sqrt((double) i+1.0); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ } /* Read in the kernel values from rest of input string argument */ kernel->values=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->height*sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); kernel->minimum=MagickMaximumValue; kernel->maximum=(-MagickMaximumValue); kernel->negative_range = kernel->positive_range = 0.0; for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); if ( LocaleCompare("nan",token) == 0 || LocaleCompare("-",token) == 0 ) { kernel->values[i] = nan; /* this value is not part of neighbourhood */ } else { kernel->values[i] = StringToDouble(token,(char **) NULL); ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } } /* sanity check -- no more values in kernel definition */ (void) GetNextToken(p,&p,MagickPathExtent,token); if ( *token != '\0' && *token != ';' && *token != '\'' ) return(DestroyKernelInfo(kernel)); #if 0 /* this was the old method of handling a incomplete kernel */ if ( i < (ssize_t) (kernel->width*kernel->height) ) { Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); for ( ; i < (ssize_t) (kernel->width*kernel->height); i++) kernel->values[i]=0.0; } #else /* Number of values for kernel was not enough - Report Error */ if ( i < (ssize_t) (kernel->width*kernel->height) ) return(DestroyKernelInfo(kernel)); #endif /* check that we recieved at least one real (non-nan) value! */ if (kernel->minimum == MagickMaximumValue) return(DestroyKernelInfo(kernel)); if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */ ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */ else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */ else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */ return(kernel); } static KernelInfo *ParseKernelName(const char *kernel_string, ExceptionInfo *exception) { char token[MagickPathExtent]; const char *p, *end; GeometryInfo args; KernelInfo *kernel; MagickStatusType flags; ssize_t type; /* Parse special 'named' kernel */ (void) GetNextToken(kernel_string,&p,MagickPathExtent,token); type=ParseCommandOption(MagickKernelOptions,MagickFalse,token); if ( type < 0 || type == UserDefinedKernel ) return((KernelInfo *) NULL); /* not a valid named kernel */ while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';')) p++; end = strchr(p, ';'); /* end of this kernel defintion */ if ( end == (char *) NULL ) end = strchr(p, '\0'); /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, p, (size_t) (end-p)); token[end-p] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif /* special handling of missing values in input string */ switch( type ) { /* Shape Kernel Defaults */ case UnityKernel: if ( (flags & WidthValue) == 0 ) args.rho = 1.0; /* Default scale = 1.0, zero is valid */ break; case SquareKernel: case DiamondKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: if ( (flags & HeightValue) == 0 ) args.sigma = 1.0; /* Default scale = 1.0, zero is valid */ break; case RingKernel: if ( (flags & XValue) == 0 ) args.xi = 1.0; /* Default scale = 1.0, zero is valid */ break; case RectangleKernel: /* Rectangle - set size defaults */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 3; /* then width = 3 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ if ( (flags & XValue) == 0 ) /* center offset if not defined */ args.xi = (double)(((ssize_t)args.rho-1)/2); if ( (flags & YValue) == 0 ) args.psi = (double)(((ssize_t)args.sigma-1)/2); break; /* Distance Kernel Defaults */ case ChebyshevKernel: case ManhattanKernel: case OctagonalKernel: case EuclideanKernel: if ( (flags & HeightValue) == 0 ) /* no distance scale */ args.sigma = 100.0; /* default distance scaling */ else if ( (flags & AspectValue ) != 0 ) /* '!' flag */ args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */ else if ( (flags & PercentValue ) != 0 ) /* '%' flag */ args.sigma *= QuantumRange/100.0; /* percentage of color range */ break; default: break; } kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args, exception); if ( kernel == (KernelInfo *) NULL ) return(kernel); /* global expand to rotated kernel list - only for single kernels */ if ( kernel->next == (KernelInfo *) NULL ) { if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 45.0); else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); } return(kernel); } MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string, ExceptionInfo *exception) { KernelInfo *kernel, *new_kernel; char *kernel_cache, token[MagickPathExtent]; const char *p; if (kernel_string == (const char *) NULL) return(ParseKernelArray(kernel_string)); p=kernel_string; kernel_cache=(char *) NULL; if (*kernel_string == '@') { kernel_cache=FileToString(kernel_string+1,~0UL,exception); if (kernel_cache == (char *) NULL) return((KernelInfo *) NULL); p=(const char *) kernel_cache; } kernel=NULL; while (GetNextToken(p,(const char **) NULL,MagickPathExtent,token), *token != '\0') { /* ignore extra or multiple ';' kernel separators */ if (*token != ';') { /* tokens starting with alpha is a Named kernel */ if (isalpha((int) ((unsigned char) *token)) != 0) new_kernel=ParseKernelName(p,exception); else /* otherwise a user defined kernel array */ new_kernel=ParseKernelArray(p); /* Error handling -- this is not proper error handling! */ if (new_kernel == (KernelInfo *) NULL) { if (kernel != (KernelInfo *) NULL) kernel=DestroyKernelInfo(kernel); return((KernelInfo *) NULL); } /* initialise or append the kernel list */ if (kernel == (KernelInfo *) NULL) kernel=new_kernel; else LastKernelInfo(kernel)->next=new_kernel; } /* look for the next kernel in list */ p=strchr(p,';'); if (p == (char *) NULL) break; p++; } if (kernel_cache != (char *) NULL) kernel_cache=DestroyString(kernel_cache); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l B u i l t I n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelBuiltIn() returned one of the 'named' built-in types of % kernels used for special purposes such as gaussian blurring, skeleton % pruning, and edge distance determination. % % They take a KernelType, and a set of geometry style arguments, which were % typically decoded from a user supplied string, or from a more complex % Morphology Method that was requested. % % The format of the AcquireKernalBuiltIn method is: % % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, % const GeometryInfo args) % % A description of each parameter follows: % % o type: the pre-defined type of kernel wanted % % o args: arguments defining or modifying the kernel % % Convolution Kernels % % Unity % The a No-Op or Scaling single element kernel. % % Gaussian:{radius},{sigma} % Generate a two-dimensional gaussian kernel, as used by -gaussian. % The sigma for the curve is required. The resulting kernel is % normalized, % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % NOTE: that the 'radius' is optional, but if provided can limit (clip) % the final size of the resulting kernel to a square 2*radius+1 in size. % The radius should be at least 2 times that of the sigma value, or % sever clipping and aliasing may result. If not given or set to 0 the % radius will be determined so as to produce the best minimal error % result, which is usally much larger than is normally needed. % % LoG:{radius},{sigma} % "Laplacian of a Gaussian" or "Mexician Hat" Kernel. % The supposed ideal edge detection, zero-summing kernel. % % An alturnative to this kernel is to use a "DoG" with a sigma ratio of % approx 1.6 (according to wikipedia). % % DoG:{radius},{sigma1},{sigma2} % "Difference of Gaussians" Kernel. % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1. % The result is a zero-summing kernel. % % Blur:{radius},{sigma}[,{angle}] % Generates a 1 dimensional or linear gaussian blur, at the angle given % (current restricted to orthogonal angles). If a 'radius' is given the % kernel is clipped to a width of 2*radius+1. Kernel can be rotated % by a 90 degree angle. % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % Note that two convolutions with two "Blur" kernels perpendicular to % each other, is equivalent to a far larger "Gaussian" kernel with the % same sigma value, However it is much faster to apply. This is how the % "-blur" operator actually works. % % Comet:{width},{sigma},{angle} % Blur in one direction only, much like how a bright object leaves % a comet like trail. The Kernel is actually half a gaussian curve, % Adding two such blurs in opposite directions produces a Blur Kernel. % Angle can be rotated in multiples of 90 degrees. % % Note that the first argument is the width of the kernel and not the % radius of the kernel. % % Binomial:[{radius}] % Generate a discrete kernel using a 2 dimentional Pascel's Triangle % of values. Used for special forma of image filters. % % # Still to be implemented... % # % # Filter2D % # Filter1D % # Set kernel values using a resize filter, and given scale (sigma) % # Cylindrical or Linear. Is this possible with an image? % # % % Named Constant Convolution Kernels % % All these are unscaled, zero-summing kernels by default. As such for % non-HDRI version of ImageMagick some form of normalization, user scaling, % and biasing the results is recommended, to prevent the resulting image % being 'clipped'. % % The 3x3 kernels (most of these) can be circularly rotated in multiples of % 45 degrees to generate the 8 angled varients of each of the kernels. % % Laplacian:{type} % Discrete Lapacian Kernels, (without normalization) % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood) % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood) % Type 2 : 3x3 with center:4 edge:1 corner:-2 % Type 3 : 3x3 with center:4 edge:-2 corner:1 % Type 5 : 5x5 laplacian % Type 7 : 7x7 laplacian % Type 15 : 5x5 LoG (sigma approx 1.4) % Type 19 : 9x9 LoG (sigma approx 1.4) % % Sobel:{angle} % Sobel 'Edge' convolution kernel (3x3) % | -1, 0, 1 | % | -2, 0,-2 | % | -1, 0, 1 | % % Roberts:{angle} % Roberts convolution kernel (3x3) % | 0, 0, 0 | % | -1, 1, 0 | % | 0, 0, 0 | % % Prewitt:{angle} % Prewitt Edge convolution kernel (3x3) % | -1, 0, 1 | % | -1, 0, 1 | % | -1, 0, 1 | % % Compass:{angle} % Prewitt's "Compass" convolution kernel (3x3) % | -1, 1, 1 | % | -1,-2, 1 | % | -1, 1, 1 | % % Kirsch:{angle} % Kirsch's "Compass" convolution kernel (3x3) % | -3,-3, 5 | % | -3, 0, 5 | % | -3,-3, 5 | % % FreiChen:{angle} % Frei-Chen Edge Detector is based on a kernel that is similar to % the Sobel Kernel, but is designed to be isotropic. That is it takes % into account the distance of the diagonal in the kernel. % % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | % | 1, 0, -1 | % % FreiChen:{type},{angle} % % Frei-Chen Pre-weighted kernels... % % Type 0: default un-nomalized version shown above. % % Type 1: Orthogonal Kernel (same as type 11 below) % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 2: Diagonal form of Kernel... % | 1, sqrt(2), 0 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 0, -sqrt(2) -1 | % % However this kernel is als at the heart of the FreiChen Edge Detection % Process which uses a set of 9 specially weighted kernel. These 9 % kernels not be normalized, but directly applied to the image. The % results is then added together, to produce the intensity of an edge in % a specific direction. The square root of the pixel value can then be % taken as the cosine of the edge, and at least 2 such runs at 90 degrees % from each other, both the direction and the strength of the edge can be % determined. % % Type 10: All 9 of the following pre-weighted kernels... % % Type 11: | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 12: | 1, sqrt(2), 1 | % | 0, 0, 0 | / 2*sqrt(2) % | 1, sqrt(2), 1 | % % Type 13: | sqrt(2), -1, 0 | % | -1, 0, 1 | / 2*sqrt(2) % | 0, 1, -sqrt(2) | % % Type 14: | 0, 1, -sqrt(2) | % | -1, 0, 1 | / 2*sqrt(2) % | sqrt(2), -1, 0 | % % Type 15: | 0, -1, 0 | % | 1, 0, 1 | / 2 % | 0, -1, 0 | % % Type 16: | 1, 0, -1 | % | 0, 0, 0 | / 2 % | -1, 0, 1 | % % Type 17: | 1, -2, 1 | % | -2, 4, -2 | / 6 % | -1, -2, 1 | % % Type 18: | -2, 1, -2 | % | 1, 4, 1 | / 6 % | -2, 1, -2 | % % Type 19: | 1, 1, 1 | % | 1, 1, 1 | / 3 % | 1, 1, 1 | % % The first 4 are for edge detection, the next 4 are for line detection % and the last is to add a average component to the results. % % Using a special type of '-1' will return all 9 pre-weighted kernels % as a multi-kernel list, so that you can use them directly (without % normalization) with the special "-set option:morphology:compose Plus" % setting to apply the full FreiChen Edge Detection Technique. % % If 'type' is large it will be taken to be an actual rotation angle for % the default FreiChen (type 0) kernel. As such FreiChen:45 will look % like a Sobel:45 but with 'sqrt(2)' instead of '2' values. % % WARNING: The above was layed out as per % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf % But rotated 90 degrees so direction is from left rather than the top. % I have yet to find any secondary confirmation of the above. The only % other source found was actual source code at % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf % Neigher paper defineds the kernels in a way that looks locical or % correct when taken as a whole. % % Boolean Kernels % % Diamond:[{radius}[,{scale}]] % Generate a diamond shaped kernel with given radius to the points. % Kernel size will again be radius*2+1 square and defaults to radius 1, % generating a 3x3 kernel that is slightly larger than a square. % % Square:[{radius}[,{scale}]] % Generate a square shaped kernel of size radius*2+1, and defaulting % to a 3x3 (radius 1). % % Octagon:[{radius}[,{scale}]] % Generate octagonal shaped kernel of given radius and constant scale. % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result % in "Diamond" kernel. % % Disk:[{radius}[,{scale}]] % Generate a binary disk, thresholded at the radius given, the radius % may be a float-point value. Final Kernel size is floor(radius)*2+1 % square. A radius of 5.3 is the default. % % NOTE: That a low radii Disk kernels produce the same results as % many of the previously defined kernels, but differ greatly at larger % radii. Here is a table of equivalences... % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1" % "Disk:1.5" => "Square" % "Disk:2" => "Diamond:2" % "Disk:2.5" => "Octagon" % "Disk:2.9" => "Square:2" % "Disk:3.5" => "Octagon:3" % "Disk:4.5" => "Octagon:4" % "Disk:5.4" => "Octagon:5" % "Disk:6.4" => "Octagon:6" % All other Disk shapes are unique to this kernel, but because a "Disk" % is more circular when using a larger radius, using a larger radius is % preferred over iterating the morphological operation. % % Rectangle:{geometry} % Simply generate a rectangle of 1's with the size given. You can also % specify the location of the 'control point', otherwise the closest % pixel to the center of the rectangle is selected. % % Properly centered and odd sized rectangles work the best. % % Symbol Dilation Kernels % % These kernel is not a good general morphological kernel, but is used % more for highlighting and marking any single pixels in an image using, % a "Dilate" method as appropriate. % % For the same reasons iterating these kernels does not produce the % same result as using a larger radius for the symbol. % % Plus:[{radius}[,{scale}]] % Cross:[{radius}[,{scale}]] % Generate a kernel in the shape of a 'plus' or a 'cross' with % a each arm the length of the given radius (default 2). % % NOTE: "plus:1" is equivalent to a "Diamond" kernel. % % Ring:{radius1},{radius2}[,{scale}] % A ring of the values given that falls between the two radii. % Defaults to a ring of approximataly 3 radius in a 7x7 kernel. % This is the 'edge' pixels of the default "Disk" kernel, % More specifically, "Ring" -> "Ring:2.5,3.5,1.0" % % Hit and Miss Kernels % % Peak:radius1,radius2 % Find any peak larger than the pixels the fall between the two radii. % The default ring of pixels is as per "Ring". % Edges % Find flat orthogonal edges of a binary shape % Corners % Find 90 degree corners of a binary shape % Diagonals:type % A special kernel to thin the 'outside' of diagonals % LineEnds:type % Find end points of lines (for pruning a skeletion) % Two types of lines ends (default to both) can be searched for % Type 0: All line ends % Type 1: single kernel for 4-conneected line ends % Type 2: single kernel for simple line ends % LineJunctions % Find three line junctions (within a skeletion) % Type 0: all line junctions % Type 1: Y Junction kernel % Type 2: Diagonal T Junction kernel % Type 3: Orthogonal T Junction kernel % Type 4: Diagonal X Junction kernel % Type 5: Orthogonal + Junction kernel % Ridges:type % Find single pixel ridges or thin lines % Type 1: Fine single pixel thick lines and ridges % Type 2: Find two pixel thick lines and ridges % ConvexHull % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees % Skeleton:type % Traditional skeleton generating kernels. % Type 1: Tradional Skeleton kernel (4 connected skeleton) % Type 2: HIPR2 Skeleton kernel (8 connected skeleton) % Type 3: Thinning skeleton based on a ressearch paper by % Dan S. Bloomberg (Default Type) % ThinSE:type % A huge variety of Thinning Kernels designed to preserve conectivity. % many other kernel sets use these kernels as source definitions. % Type numbers are 41-49, 81-89, 481, and 482 which are based on % the super and sub notations used in the source research paper. % % Distance Measuring Kernels % % Different types of distance measuring methods, which are used with the % a 'Distance' morphology method for generating a gradient based on % distance from an edge of a binary shape, though there is a technique % for handling a anti-aliased shape. % % See the 'Distance' Morphological Method, for information of how it is % applied. % % Chebyshev:[{radius}][x{scale}[%!]] % Chebyshev Distance (also known as Tchebychev or Chessboard distance) % is a value of one to any neighbour, orthogonal or diagonal. One why % of thinking of it is the number of squares a 'King' or 'Queen' in % chess needs to traverse reach any other position on a chess board. % It results in a 'square' like distance function, but one where % diagonals are given a value that is closer than expected. % % Manhattan:[{radius}][x{scale}[%!]] % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi % Cab distance metric), it is the distance needed when you can only % travel in horizontal or vertical directions only. It is the % distance a 'Rook' in chess would have to travel, and results in a % diamond like distances, where diagonals are further than expected. % % Octagonal:[{radius}][x{scale}[%!]] % An interleving of Manhatten and Chebyshev metrics producing an % increasing octagonally shaped distance. Distances matches those of % the "Octagon" shaped kernel of the same radius. The minimum radius % and default is 2, producing a 5x5 kernel. % % Euclidean:[{radius}][x{scale}[%!]] % Euclidean distance is the 'direct' or 'as the crow flys' distance. % However by default the kernel size only has a radius of 1, which % limits the distance to 'Knight' like moves, with only orthogonal and % diagonal measurements being correct. As such for the default kernel % you will get octagonal like distance function. % % However using a larger radius such as "Euclidean:4" you will get a % much smoother distance gradient from the edge of the shape. Especially % if the image is pre-processed to include any anti-aliasing pixels. % Of course a larger kernel is slower to use, and not always needed. % % The first three Distance Measuring Kernels will only generate distances % of exact multiples of {scale} in binary images. As such you can use a % scale of 1 without loosing any information. However you also need some % scaling when handling non-binary anti-aliased shapes. % % The "Euclidean" Distance Kernel however does generate a non-integer % fractional results, and as such scaling is vital even for binary shapes. % */ MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, const GeometryInfo *args,ExceptionInfo *exception) { KernelInfo *kernel; register ssize_t i; register ssize_t u, v; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ /* Generate a new empty kernel if needed */ kernel=(KernelInfo *) NULL; switch(type) { case UndefinedKernel: /* These should not call this function */ case UserDefinedKernel: assert("Should not call this function" != (char *) NULL); break; case LaplacianKernel: /* Named Descrete Convolution Kernels */ case SobelKernel: /* these are defined using other kernels */ case RobertsKernel: case PrewittKernel: case CompassKernel: case KirschKernel: case FreiChenKernel: case EdgesKernel: /* Hit and Miss kernels */ case CornersKernel: case DiagonalsKernel: case LineEndsKernel: case LineJunctionsKernel: case RidgesKernel: case ConvexHullKernel: case SkeletonKernel: case ThinSEKernel: break; /* A pre-generated kernel is not needed */ #if 0 /* set to 1 to do a compile-time check that we haven't missed anything */ case UnityKernel: case GaussianKernel: case DoGKernel: case LoGKernel: case BlurKernel: case CometKernel: case BinomialKernel: case DiamondKernel: case SquareKernel: case RectangleKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: case RingKernel: case PeaksKernel: case ChebyshevKernel: case ManhattanKernel: case OctangonalKernel: case EuclideanKernel: #else default: #endif /* Generate the base Kernel Structure */ kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) memset(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = type; kernel->next = (KernelInfo *) NULL; kernel->signature=MagickCoreSignature; break; } switch(type) { /* Convolution Kernels */ case UnityKernel: { kernel->height = kernel->width = (size_t) 1; kernel->x = kernel->y = (ssize_t) 0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(1,sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); kernel->maximum = kernel->values[0] = args->rho; break; } break; case GaussianKernel: case DoGKernel: case LoGKernel: { double sigma = fabs(args->sigma), sigma2 = fabs(args->xi), A, B, R; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else if ( (type != DoGKernel) || (sigma >= sigma2) ) kernel->width = GetOptimalKernelWidth2D(args->rho,sigma); else kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2); kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* WARNING: The following generates a 'sampled gaussian' kernel. * What we really want is a 'discrete gaussian' kernel. * * How to do this is I don't know, but appears to be basied on the * Error Function 'erf()' (intergral of a gaussian) */ if ( type == GaussianKernel || type == DoGKernel ) { /* Calculate a Gaussian, OR positive half of a DoG */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } if ( type == DoGKernel ) { /* Subtract a Negative Gaussian for "Difference of Gaussian" */ if ( sigma2 > MagickEpsilon ) { sigma = sigma2; /* simplify loop expressions */ A = 1.0/(2.0*sigma*sigma); B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0; } if ( type == LoGKernel ) { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { R = ((double)(u*u+v*v))*A; kernel->values[i] = (1-R)*exp(-R)*B; } } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } /* Note the above kernels may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, and thus ** producing a very bright kernel. ** ** Normalization will still be needed. */ /* Normalize the 2D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); break; } case BlurKernel: { double sigma = fabs(args->sigma), alpha, beta; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else kernel->width = GetOptimalKernelWidth1D(args->rho,sigma); kernel->height = 1; kernel->x = (ssize_t) (kernel->width-1)/2; kernel->y = 0; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); #if 1 #define KernelRank 3 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix). ** It generates a gaussian 3 times the width, and compresses it into ** the expected range. This produces a closer normalization of the ** resulting kernel, especially for very low sigma values. ** As such while wierd it is prefered. ** ** I am told this method originally came from Photoshop. ** ** A properly normalized curve is generated (apart from edge clipping) ** even though we later normalize the result (for edge clipping) ** to allow the correct generation of a "Difference of Blurs". */ /* initialize */ v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */ (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); /* Calculate a Positive 1D Gaussian */ if ( sigma > MagickEpsilon ) { sigma *= KernelRank; /* simplify loop expressions */ alpha = 1.0/(2.0*sigma*sigma); beta= (double) (1.0/(MagickSQ2PI*sigma )); for ( u=-v; u <= v; u++) { kernel->values[(u+v)/KernelRank] += exp(-((double)(u*u))*alpha)*beta; } } else /* special case - generate a unity kernel */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; #else /* Direct calculation without curve averaging This is equivelent to a KernelRank of 1 */ /* Calculate a Positive Gaussian */ if ( sigma > MagickEpsilon ) { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ beta = 1.0/(MagickSQ2PI*sigma); for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u))*alpha)*beta; } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } #endif /* Note the above kernel may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, as a ** result of not generating a actual 'discrete' kernel, and thus ** producing a very bright 'impulse'. ** ** Becuase of these two factors Normalization is required! */ /* Normalize the 1D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); /* rotate the 1D kernel by given angle */ RotateKernelInfo(kernel, args->xi ); break; } case CometKernel: { double sigma = fabs(args->sigma), A; if ( args->rho < 1.0 ) kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1; else kernel->width = (size_t)args->rho; kernel->x = kernel->y = 0; kernel->height = 1; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* A comet blur is half a 1D gaussian curve, so that the object is ** blurred in one direction only. This may not be quite the right ** curve to use so may change in the future. The function must be ** normalised after generation, which also resolves any clipping. ** ** As we are normalizing and not subtracting gaussians, ** there is no need for a divisor in the gaussian formula ** ** It is less comples */ if ( sigma > MagickEpsilon ) { #if 1 #define KernelRank 3 v = (ssize_t) kernel->width*KernelRank; /* start/end points */ (void) memset(kernel->values,0, (size_t) kernel->width*sizeof(*kernel->values)); sigma *= KernelRank; /* simplify the loop expression */ A = 1.0/(2.0*sigma*sigma); /* B = 1.0/(MagickSQ2PI*sigma); */ for ( u=0; u < v; u++) { kernel->values[u/KernelRank] += exp(-((double)(u*u))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ } for (i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i]; #else A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */ /* B = 1.0/(MagickSQ2PI*sigma); */ for ( i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i] = exp(-((double)(i*i))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ #endif } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; } kernel->minimum = 0.0; kernel->maximum = kernel->values[0]; kernel->negative_range = 0.0; ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */ RotateKernelInfo(kernel, args->xi); /* Rotate by angle */ break; } case BinomialKernel: { size_t order_f; if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; order_f = fact(kernel->width-1); kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=0; v < (ssize_t)kernel->height; v++) { size_t alpha = order_f / ( fact((size_t) v) * fact(kernel->height-v-1) ); for ( u=0; u < (ssize_t)kernel->width; u++, i++) kernel->positive_range += kernel->values[i] = (double) (alpha * order_f / ( fact((size_t) u) * fact(kernel->height-u-1) )); } kernel->minimum = 1.0; kernel->maximum = kernel->values[kernel->x+kernel->y*kernel->width]; kernel->negative_range = 0.0; break; } /* Convolution Kernels - Well Known Named Constant Kernels */ case LaplacianKernel: { switch ( (int) args->rho ) { case 0: default: /* laplacian square filter -- default */ kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1"); break; case 1: /* laplacian diamond filter */ kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0"); break; case 2: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); break; case 3: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1"); break; case 5: /* a 5x5 laplacian */ kernel=ParseKernelArray( "5: -4,-1,0,-1,-4 -1,2,3,2,-1 0,3,4,3,0 -1,2,3,2,-1 -4,-1,0,-1,-4"); break; case 7: /* a 7x7 laplacian */ kernel=ParseKernelArray( "7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" ); break; case 15: /* a 5x5 LoG (sigma approx 1.4) */ kernel=ParseKernelArray( "5: 0,0,-1,0,0 0,-1,-2,-1,0 -1,-2,16,-2,-1 0,-1,-2,-1,0 0,0,-1,0,0"); break; case 19: /* a 9x9 LoG (sigma approx 1.4) */ /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */ kernel=ParseKernelArray( "9: 0,-1,-1,-2,-2,-2,-1,-1,0 -1,-2,-4,-5,-5,-5,-4,-2,-1 -1,-4,-5,-3,-0,-3,-5,-4,-1 -2,-5,-3,12,24,12,-3,-5,-2 -2,-5,-0,24,40,24,-0,-5,-2 -2,-5,-3,12,24,12,-3,-5,-2 -1,-4,-5,-3,-0,-3,-5,-4,-1 -1,-2,-4,-5,-5,-5,-4,-2,-1 0,-1,-1,-2,-2,-2,-1,-1,0"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; break; } case SobelKernel: { /* Simple Sobel Kernel */ kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case RobertsKernel: { kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case PrewittKernel: { kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case CompassKernel: { kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case KirschKernel: { kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case FreiChenKernel: /* Direction is set to be left to right positive */ /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */ /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */ { switch ( (int) args->rho ) { default: case 0: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +(MagickRealType) MagickSQ2; kernel->values[5] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ break; case 2: kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = kernel->values[3]= +(MagickRealType) MagickSQ2; kernel->values[5] = kernel->values[7]= -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 10: { kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19",exception); if (kernel == (KernelInfo *) NULL) return(kernel); break; } case 1: case 11: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +(MagickRealType) MagickSQ2; kernel->values[5] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 12: kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = +(MagickRealType) MagickSQ2; kernel->values[7] = +(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 13: kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[0] = +(MagickRealType) MagickSQ2; kernel->values[8] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 14: kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[2] = -(MagickRealType) MagickSQ2; kernel->values[6] = +(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 15: kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 16: kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 17: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 18: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 19: kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/3.0, NoValue); break; } if ( fabs(args->sigma) >= MagickEpsilon ) /* Rotate by correctly supplied 'angle' */ RotateKernelInfo(kernel, args->sigma); else if ( args->rho > 30.0 || args->rho < -30.0 ) /* Rotate by out of bounds 'type' */ RotateKernelInfo(kernel, args->rho); break; } /* Boolean or Shaped Kernels */ case DiamondKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case SquareKernel: case RectangleKernel: { double scale; if ( type == SquareKernel ) { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = (size_t) (2*args->rho+1); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; scale = args->sigma; } else { /* NOTE: user defaults set in "AcquireKernelInfo()" */ if ( args->rho < 1.0 || args->sigma < 1.0 ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->width = (size_t)args->rho; kernel->height = (size_t)args->sigma; if ( args->xi < 0.0 || args->xi > (double)kernel->width || args->psi < 0.0 || args->psi > (double)kernel->height ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->x = (ssize_t) args->xi; kernel->y = (ssize_t) args->psi; scale = 1.0; } kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values to scale given */ u=(ssize_t) (kernel->width*kernel->height); for ( i=0; i < u; i++) kernel->values[i] = scale; kernel->minimum = kernel->maximum = scale; /* a flat shape */ kernel->positive_range = scale*u; break; } case OctagonKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= ((long)kernel->x + (long)(kernel->x/2)) ) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case DiskKernel: { ssize_t limit = (ssize_t)(args->rho*args->rho); if (args->rho < 0.4) /* default radius approx 4.3 */ kernel->width = kernel->height = 9L, limit = 18L; else kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ((u*u+v*v) <= limit) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case PlusKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } case CrossKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == v || u == -v) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } /* HitAndMiss Kernels */ case RingKernel: case PeaksKernel: { ssize_t limit1, limit2, scale; if (args->rho < args->sigma) { kernel->width = ((size_t)args->sigma)*2+1; limit1 = (ssize_t)(args->rho*args->rho); limit2 = (ssize_t)(args->sigma*args->sigma); } else { kernel->width = ((size_t)args->rho)*2+1; limit1 = (ssize_t)(args->sigma*args->sigma); limit2 = (ssize_t)(args->rho*args->rho); } if ( limit2 <= 0 ) kernel->width = 7L, limit1 = 7L, limit2 = 11L; kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */ scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi); for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { ssize_t radius=u*u+v*v; if (limit1 < radius && radius <= limit2) kernel->positive_range += kernel->values[i] = (double) scale; else kernel->values[i] = nan; } kernel->minimum = kernel->maximum = (double) scale; if ( type == PeaksKernel ) { /* set the central point in the middle */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; kernel->maximum = 1.0; } break; } case EdgesKernel: { kernel=AcquireKernelInfo("ThinSE:482",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */ break; } case CornersKernel: { kernel=AcquireKernelInfo("ThinSE:87",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */ break; } case DiagonalsKernel: { switch ( (int) args->rho ) { case 0: default: { KernelInfo *new_kernel; kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; ExpandMirrorKernelInfo(kernel); return(kernel); } case 1: kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); break; case 2: kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineEndsKernel: { /* Kernels for finding the end of thin lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all end of lines */ return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>",exception)); case 1: /* kernel for 4-connected line ends - no rotation */ kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-"); break; case 2: /* kernel to add for 8-connected lines - no rotation */ kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1"); break; case 3: /* kernel to add for orthogonal line ends - does not find corners */ kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0"); break; case 4: /* traditional line end - fails on last T end */ kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineJunctionsKernel: { /* kernels for finding the junctions of multiple lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all line junctions */ return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>",exception)); case 1: /* Y Junction */ kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-"); break; case 2: /* Diagonal T Junctions */ kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1"); break; case 3: /* Orthogonal T Junctions */ kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-"); break; case 4: /* Diagonal X Junctions */ kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1"); break; case 5: /* Orthogonal X Junctions - minimal diamond kernel */ kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case RidgesKernel: { /* Ridges - Ridge finding kernels */ KernelInfo *new_kernel; switch ( (int) args->rho ) { case 1: default: kernel=ParseKernelArray("3x1:0,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */ break; case 2: kernel=ParseKernelArray("4x1:0,1,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */ /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */ /* Unfortunatally we can not yet rotate a non-square kernel */ /* But then we can't flip a non-symetrical kernel either */ new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; break; } break; } case ConvexHullKernel: { KernelInfo *new_kernel; /* first set of 8 kernels */ kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* append the mirror versions too - no flip function yet */ new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; ExpandRotateKernelInfo(new_kernel, 90.0); LastKernelInfo(kernel)->next = new_kernel; break; } case SkeletonKernel: { switch ( (int) args->rho ) { case 1: default: /* Traditional Skeleton... ** A cyclically rotated single kernel */ kernel=AcquireKernelInfo("ThinSE:482",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */ break; case 2: /* HIPR Variation of the cyclic skeleton ** Corners of the traditional method made more forgiving, ** but the retain the same cyclic order. */ kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;",exception); if (kernel == (KernelInfo *) NULL) return(kernel); if (kernel->next == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); kernel->type = type; kernel->next->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */ break; case 3: /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf */ kernel=AcquireKernelInfo("ThinSE:41; ThinSE:42; ThinSE:43", exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->next->type = type; kernel->next->next->type = type; ExpandMirrorKernelInfo(kernel); /* 12 kernels total */ break; } break; } case ThinSEKernel: { /* Special kernels for general thinning, while preserving connections ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf ** And ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html ** ** Note kernels do not specify the origin pixel, allowing them ** to be used for both thickening and thinning operations. */ switch ( (int) args->rho ) { /* SE for 4-connected thinning */ case 41: /* SE_4_1 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1"); break; case 42: /* SE_4_2 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-"); break; case 43: /* SE_4_3 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1"); break; case 44: /* SE_4_4 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-"); break; case 45: /* SE_4_5 */ kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-"); break; case 46: /* SE_4_6 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1"); break; case 47: /* SE_4_7 */ kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-"); break; case 48: /* SE_4_8 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1"); break; case 49: /* SE_4_9 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1"); break; /* SE for 8-connected thinning - negatives of the above */ case 81: /* SE_8_0 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-"); break; case 82: /* SE_8_2 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-"); break; case 83: /* SE_8_3 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-"); break; case 84: /* SE_8_4 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-"); break; case 85: /* SE_8_5 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-"); break; case 86: /* SE_8_6 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1"); break; case 87: /* SE_8_7 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-"); break; case 88: /* SE_8_8 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-"); break; case 89: /* SE_8_9 */ kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-"); break; /* Special combined SE kernels */ case 423: /* SE_4_2 , SE_4_3 Combined Kernel */ kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-"); break; case 823: /* SE_8_2 , SE_8_3 Combined Kernel */ kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-"); break; case 481: /* SE_48_1 - General Connected Corner Kernel */ kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-"); break; default: case 482: /* SE_48_2 - General Edge Kernel */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } /* Distance Measuring Kernels */ case ChebyshevKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*MagickMax(fabs((double)u),fabs((double)v)) ); kernel->maximum = kernel->values[0]; break; } case ManhattanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*(labs((long) u)+labs((long) v)) ); kernel->maximum = kernel->values[0]; break; } case OctagonalKernel: { if (args->rho < 2.0) kernel->width = kernel->height = 5; /* default/minimum radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { double r1 = MagickMax(fabs((double)u),fabs((double)v)), r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5); kernel->positive_range += kernel->values[i] = args->sigma*MagickMax(r1,r2); } kernel->maximum = kernel->values[0]; break; } case EuclideanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*sqrt((double)(u*u+v*v)) ); kernel->maximum = kernel->values[0]; break; } default: { /* No-Op Kernel - Basically just a single pixel on its own */ kernel=ParseKernelArray("1:1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = UndefinedKernel; break; } break; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneKernelInfo() creates a new clone of the given Kernel List so that its % can be modified without effecting the original. The cloned kernel should % be destroyed using DestoryKernelInfo() when no longer needed. % % The format of the CloneKernelInfo method is: % % KernelInfo *CloneKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be cloned % */ MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel) { register ssize_t i; KernelInfo *new_kernel; assert(kernel != (KernelInfo *) NULL); new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (new_kernel == (KernelInfo *) NULL) return(new_kernel); *new_kernel=(*kernel); /* copy values in structure */ /* replace the values with a copy of the values */ new_kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height*sizeof(*kernel->values))); if (new_kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(new_kernel)); for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) new_kernel->values[i]=kernel->values[i]; /* Also clone the next kernel in the kernel list */ if ( kernel->next != (KernelInfo *) NULL ) { new_kernel->next = CloneKernelInfo(kernel->next); if ( new_kernel->next == (KernelInfo *) NULL ) return(DestroyKernelInfo(new_kernel)); } return(new_kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyKernelInfo() frees the memory used by a Convolution/Morphology % kernel. % % The format of the DestroyKernelInfo method is: % % KernelInfo *DestroyKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be destroyed % */ MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel) { assert(kernel != (KernelInfo *) NULL); if (kernel->next != (KernelInfo *) NULL) kernel->next=DestroyKernelInfo(kernel->next); kernel->values=(MagickRealType *) RelinquishAlignedMemory(kernel->values); kernel=(KernelInfo *) RelinquishMagickMemory(kernel); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d M i r r o r K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a % sequence of 90-degree rotated kernels but providing a reflected 180 % rotatation, before the -/+ 90-degree rotations. % % This special rotation order produces a better, more symetrical thinning of % objects. % % The format of the ExpandMirrorKernelInfo method is: % % void ExpandMirrorKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ #if 0 static void FlopKernelInfo(KernelInfo *kernel) { /* Do a Flop by reversing each row. */ size_t y; register ssize_t x,r; register double *k,t; for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width) for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--) t=k[x], k[x]=k[r], k[r]=t; kernel->x = kernel->width - kernel->x - 1; angle = fmod(angle+180.0, 360.0); } #endif static void ExpandMirrorKernelInfo(KernelInfo *kernel) { KernelInfo *clone, *last; last = kernel; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 180); /* flip */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 90); /* transpose */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 180); /* flop */ LastKernelInfo(last)->next = clone; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating % incrementally by the angle given, until the kernel repeats. % % WARNING: 45 degree rotations only works for 3x3 kernels. % While 90 degree roatations only works for linear and square kernels % % The format of the ExpandRotateKernelInfo method is: % % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ /* Internal Routine - Return true if two kernels are the same */ static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1, const KernelInfo *kernel2) { register size_t i; /* check size and origin location */ if ( kernel1->width != kernel2->width || kernel1->height != kernel2->height || kernel1->x != kernel2->x || kernel1->y != kernel2->y ) return MagickFalse; /* check actual kernel values */ for (i=0; i < (kernel1->width*kernel1->height); i++) { /* Test for Nan equivalence */ if ( IsNaN(kernel1->values[i]) && !IsNaN(kernel2->values[i]) ) return MagickFalse; if ( IsNaN(kernel2->values[i]) && !IsNaN(kernel1->values[i]) ) return MagickFalse; /* Test actual values are equivalent */ if ( fabs(kernel1->values[i] - kernel2->values[i]) >= MagickEpsilon ) return MagickFalse; } return MagickTrue; } static void ExpandRotateKernelInfo(KernelInfo *kernel,const double angle) { KernelInfo *clone_info, *last; clone_info=(KernelInfo *) NULL; last=kernel; DisableMSCWarning(4127) while (1) { RestoreMSCWarning clone_info=CloneKernelInfo(last); if (clone_info == (KernelInfo *) NULL) break; RotateKernelInfo(clone_info,angle); if (SameKernelInfo(kernel,clone_info) != MagickFalse) break; LastKernelInfo(last)->next=clone_info; last=clone_info; } if (clone_info != (KernelInfo *) NULL) clone_info=DestroyKernelInfo(clone_info); /* kernel repeated - junk */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a l c M e t a K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only, % using the kernel values. This should only ne used if it is not possible to % calculate that meta-data in some easier way. % % It is important that the meta-data is correct before ScaleKernelInfo() is % used to perform kernel normalization. % % The format of the CalcKernelMetaData method is: % % void CalcKernelMetaData(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % WARNING: Minimum and Maximum values are assumed to include zero, even if % zero is not part of the kernel (as in Gaussian Derived kernels). This % however is not true for flat-shaped morphological kernels. % % WARNING: Only the specific kernel pointed to is modified, not a list of % multiple kernels. % % This is an internal function and not expected to be useful outside this % module. This could change however. */ static void CalcKernelMetaData(KernelInfo *kernel) { register size_t i; kernel->minimum = kernel->maximum = 0.0; kernel->negative_range = kernel->positive_range = 0.0; for (i=0; i < (kernel->width*kernel->height); i++) { if ( fabs(kernel->values[i]) < MagickEpsilon ) kernel->values[i] = 0.0; ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y A p p l y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyApply() applies a morphological method, multiple times using % a list of multiple kernels. This is the method that should be called by % other 'operators' that internally use morphology operations as part of % their processing. % % It is basically equivalent to as MorphologyImage() (see below) but without % any user controls. This allows internel programs to use this method to % perform a specific task without possible interference by any API user % supplied settings. % % It is MorphologyImage() task to extract any such user controls, and % pass them to this function for processing. % % More specifically all given kernels should already be scaled, normalised, % and blended appropriatally before being parred to this routine. The % appropriate bias, and compose (typically 'UndefinedComposeOp') given. % % The format of the MorphologyApply method is: % % Image *MorphologyApply(const Image *image,MorphologyMethod method, % const ssize_t iterations,const KernelInfo *kernel, % const CompositeMethod compose,const double bias, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the source image % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % % o compose: How to handle or merge multi-kernel results. % If 'UndefinedCompositeOp' use default for the Morphology method. % If 'NoCompositeOp' force image to be re-iterated by each kernel. % Otherwise merge the results using the compose method given. % % o bias: Convolution Output Bias. % % o exception: return any errors or warnings in this structure. % */ static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image, const MorphologyMethod method,const KernelInfo *kernel,const double bias, ExceptionInfo *exception) { #define MorphologyTag "Morphology/Image" CacheView *image_view, *morphology_view; OffsetInfo offset; register ssize_t j, y; size_t *changes, changed, width; MagickBooleanType status; MagickOffsetType progress; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(morphology_image != (Image *) NULL); assert(morphology_image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(morphology_image,exception); width=image->columns+kernel->width-1; offset.x=0; offset.y=0; switch (method) { case ConvolveMorphology: case DilateMorphology: case DilateIntensityMorphology: case IterativeDistanceMorphology: { /* Kernel needs to used with reflection about origin. */ offset.x=(ssize_t) kernel->width-kernel->x-1; offset.y=(ssize_t) kernel->height-kernel->y-1; break; } case ErodeMorphology: case ErodeIntensityMorphology: case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: { offset.x=kernel->x; offset.y=kernel->y; break; } default: { assert("Not a Primitive Morphology Method" != (char *) NULL); break; } } changed=0; changes=(size_t *) AcquireQuantumMemory(GetOpenMPMaximumThreads(), sizeof(*changes)); if (changes == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changes[j]=0; if ((method == ConvolveMorphology) && (kernel->width == 1)) { register ssize_t x; /* Special handling (for speed) of vertical (blur) kernels. This performs its handling in columns rather than in rows. This is only done for convolve as it is the only method that generates very large 1-D vertical kernels (such as a 'BlurKernel') */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,morphology_image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t r; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,x,-offset.y,1,image->rows+ kernel->height-1,exception); q=GetCacheViewAuthenticPixels(morphology_view,x,0,1, morphology_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*offset.y; for (r=0; r < (ssize_t) image->rows; r++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait morphology_traits, traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t v; size_t count; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); morphology_traits=GetPixelChannelTraits(morphology_image,channel); if ((traits == UndefinedPixelTrait) || (morphology_traits == UndefinedPixelTrait)) continue; if ((traits & CopyPixelTrait) != 0) { SetPixelChannel(morphology_image,channel,p[center+i],q); continue; } k=(&kernel->values[kernel->height-1]); pixels=p; pixel=bias; gamma=1.0; count=0; if (((image->alpha_trait & BlendPixelTrait) == 0) || ((morphology_traits & BlendPixelTrait) == 0)) for (v=0; v < (ssize_t) kernel->height; v++) { if (!IsNaN(*k)) { pixel+=(*k)*pixels[i]; count++; } k--; pixels+=GetPixelChannels(image); } else { gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { if (!IsNaN(*k)) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=alpha*(*k)*pixels[i]; gamma+=alpha*(*k); count++; } k--; pixels+=GetPixelChannels(image); } } if (fabs(pixel-p[center+i]) > MagickEpsilon) changes[id]++; gamma=PerceptibleReciprocal(gamma); if (count != 0) gamma*=(double) kernel->height/count; SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma* pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(morphology_image); } if (SyncCacheViewAuthenticPixels(morphology_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,MorphologyTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_image->type=image->type; morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changed+=changes[j]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t) changed : 0); } /* Normal handling of horizontal or rectangular kernels (row by row). */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,morphology_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width, kernel->height,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,morphology_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) (GetPixelChannels(image)*width*offset.y+ GetPixelChannels(image)*offset.x); 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, intensity, maximum, minimum, pixel; PixelChannel channel; PixelTrait morphology_traits, traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels, *magick_restrict quantum_pixels; register ssize_t u; size_t count; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); morphology_traits=GetPixelChannelTraits(morphology_image,channel); if ((traits == UndefinedPixelTrait) || (morphology_traits == UndefinedPixelTrait)) continue; if ((traits & CopyPixelTrait) != 0) { SetPixelChannel(morphology_image,channel,p[center+i],q); continue; } pixels=p; quantum_pixels=(const Quantum *) NULL; maximum=0.0; minimum=(double) QuantumRange; switch (method) { case ConvolveMorphology: { pixel=bias; break; } case DilateMorphology: case ErodeIntensityMorphology: { pixel=0.0; break; } case HitAndMissMorphology: case ErodeMorphology: { pixel=QuantumRange; break; } default: { pixel=(double) p[center+i]; break; } } count=0; gamma=1.0; switch (method) { case ConvolveMorphology: { /* Weighted Average of pixels using reflected kernel For correct working of this operation for asymetrical kernels, the kernel needs to be applied in its reflected form. That is its values needs to be reversed. Correlation is actually the same as this but without reflecting the kernel, and thus 'lower-level' that Convolution. However as Convolution is the more common method used, and it does not really cost us much in terms of processing to use a reflected kernel, so it is Convolution that is implemented. Correlation will have its kernel reflected before calling this function to do a Convolve. For more details of Correlation vs Convolution see http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf */ k=(&kernel->values[kernel->width*kernel->height-1]); if (((image->alpha_trait & BlendPixelTrait) == 0) || ((morphology_traits & BlendPixelTrait) == 0)) { /* No alpha blending. */ for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { pixel+=(*k)*pixels[i]; count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } /* Alpha blending. */ gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=alpha*(*k)*pixels[i]; gamma+=alpha*(*k); count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case ErodeMorphology: { /* Minimum value within kernel neighbourhood. The kernel is not reflected for this operation. In normal Greyscale Morphology, the kernel value should be added to the real value, this is currently not done, due to the nature of the boolean kernels being used. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { if ((double) pixels[i] < pixel) pixel=(double) pixels[i]; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case DilateMorphology: { /* Maximum value within kernel neighbourhood. For correct working of this operation for asymetrical kernels, the kernel needs to be applied in its reflected form. That is its values needs to be reversed. In normal Greyscale Morphology, the kernel value should be added to the real value, this is currently not done, due to the nature of the boolean kernels being used. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k > 0.5)) { if ((double) pixels[i] > pixel) pixel=(double) pixels[i]; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: { /* Minimum of foreground pixel minus maxumum of background pixels. The kernel is not reflected for this operation, and consists of both foreground and background pixel neighbourhoods, 0.0 for background, and 1.0 for foreground with either Nan or 0.5 values for don't care. This never produces a meaningless negative result. Such results cause Thinning/Thicken to not work correctly when used against a greyscale image. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if (*k > 0.7) { if ((double) pixels[i] < pixel) pixel=(double) pixels[i]; } else if (*k < 0.3) { if ((double) pixels[i] > maximum) maximum=(double) pixels[i]; } count++; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } pixel-=maximum; if (pixel < 0.0) pixel=0.0; if (method == ThinningMorphology) pixel=(double) p[center+i]-pixel; else if (method == ThickenMorphology) pixel+=(double) p[center+i]+pixel; break; } case ErodeIntensityMorphology: { /* Select pixel with minimum intensity within kernel neighbourhood. The kernel is not reflected for this operation. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { intensity=(double) GetPixelIntensity(image,pixels); if (intensity < minimum) { quantum_pixels=pixels; pixel=(double) pixels[i]; minimum=intensity; } count++; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case DilateIntensityMorphology: { /* Select pixel with maximum intensity within kernel neighbourhood. The kernel is not reflected for this operation. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { intensity=(double) GetPixelIntensity(image,pixels); if (intensity > maximum) { pixel=(double) pixels[i]; quantum_pixels=pixels; maximum=intensity; } count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case IterativeDistanceMorphology: { /* Compute th iterative distance from black edge of a white image shape. Essentually white values are decreased to the smallest 'distance from edge' it can find. It works by adding kernel values to the neighbourhood, and select the minimum value found. The kernel is rotated before use, so kernel distances match resulting distances, when a user provided asymmetric kernel is applied. This code is nearly identical to True GrayScale Morphology but not quite. GreyDilate Kernel values added, maximum value found Kernel is rotated before use. GrayErode: Kernel values subtracted and minimum value found No kernel rotation used. Note the Iterative Distance method is essentially a GrayErode, but with negative kernel values, and kernel rotation applied. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case UndefinedMorphology: default: break; } if (fabs(pixel-p[center+i]) > MagickEpsilon) changes[id]++; if (quantum_pixels != (const Quantum *) NULL) { SetPixelChannel(morphology_image,channel,quantum_pixels[i],q); continue; } gamma=PerceptibleReciprocal(gamma); if (count != 0) gamma*=(double) kernel->height*kernel->width/count; SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(morphology_image); } if (SyncCacheViewAuthenticPixels(morphology_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,MorphologyTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changed+=changes[j]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t) changed : -1); } /* This is almost identical to the MorphologyPrimative() function above, but applies the primitive directly to the actual image using two passes, once in each direction, with the results of the previous (and current) row being re-used. That is after each row is 'Sync'ed' into the image, the next row makes use of those values as part of the calculation of the next row. It repeats, but going in the oppisite (bottom-up) direction. Because of this 're-use of results' this function can not make use of multi- threaded, parellel processing. */ static ssize_t MorphologyPrimitiveDirect(Image *image, const MorphologyMethod method,const KernelInfo *kernel, ExceptionInfo *exception) { CacheView *morphology_view, *image_view; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; size_t width, changed; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=MagickTrue; changed=0; progress=0; switch(method) { case DistanceMorphology: case VoronoiMorphology: { /* Kernel reflected about origin. */ offset.x=(ssize_t) kernel->width-kernel->x-1; offset.y=(ssize_t) kernel->height-kernel->y-1; break; } default: { offset.x=kernel->x; offset.y=kernel->y; break; } } /* Two views into same image, do not thread. */ image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(image,exception); width=image->columns+kernel->width-1; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Read virtual pixels, and authentic pixels, from the same image! We read using virtual to get virtual pixel handling, but write back into the same image. Only top half of kernel is processed as we do a single pass downward through the image iterating the distance function as we go. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width,(size_t) offset.y+1,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,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; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; pixels=p; pixel=(double) QuantumRange; switch (method) { case DistanceMorphology: { k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v <= offset.y; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q-offset.x*GetPixelChannels(image); for (u=0; u < offset.x; u++) { if (!IsNaN(*k) && ((x+u-offset.x) >= 0)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } break; } case VoronoiMorphology: { k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < offset.y; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q-offset.x*GetPixelChannels(image); for (u=0; u < offset.x; u++) { if (!IsNaN(*k) && ((x+u-offset.x) >= 0)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } break; } default: break; } if (fabs(pixel-q[i]) > MagickEpsilon) changed++; q[i]=ClampToQuantum(pixel); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(morphology_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,MorphologyTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); /* Do the reverse pass through the image. */ image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(image,exception); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Read virtual pixels, and authentic pixels, from the same image. We read using virtual to get virtual pixel handling, but write back into the same image. Only the bottom half of the kernel is processed as we up the image. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y,width,(size_t) kernel->y+1,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } p+=(image->columns-1)*GetPixelChannels(image); q+=(image->columns-1)*GetPixelChannels(image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; pixels=p; pixel=(double) QuantumRange; switch (method) { case DistanceMorphology: { k=(&kernel->values[kernel->width*(kernel->y+1)-1]); for (v=offset.y; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*kernel->y+kernel->x-1]); pixels=q; for (u=offset.x+1; u < (ssize_t) kernel->width; u++) { pixels+=GetPixelChannels(image); if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; } break; } case VoronoiMorphology: { k=(&kernel->values[kernel->width*(kernel->y+1)-1]); for (v=offset.y; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q; for (u=offset.x+1; u < (ssize_t) kernel->width; u++) { pixels+=GetPixelChannels(image); if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; } break; } default: break; } if (fabs(pixel-q[i]) > MagickEpsilon) changed++; q[i]=ClampToQuantum(pixel); } p-=GetPixelChannels(image); q-=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(morphology_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,MorphologyTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); return(status ? (ssize_t) changed : -1); } /* Apply a Morphology by calling one of the above low level primitive application functions. This function handles any iteration loops, composition or re-iteration of results, and compound morphology methods that is based on multiple low-level (staged) morphology methods. Basically this provides the complex glue between the requested morphology method and raw low-level implementation (above). */ MagickPrivate Image *MorphologyApply(const Image *image, const MorphologyMethod method, const ssize_t iterations, const KernelInfo *kernel, const CompositeOperator compose,const double bias, ExceptionInfo *exception) { CompositeOperator curr_compose; Image *curr_image, /* Image we are working with or iterating */ *work_image, /* secondary image for primitive iteration */ *save_image, /* saved image - for 'edge' method only */ *rslt_image; /* resultant image - after multi-kernel handling */ KernelInfo *reflected_kernel, /* A reflected copy of the kernel (if needed) */ *norm_kernel, /* the current normal un-reflected kernel */ *rflt_kernel, /* the current reflected kernel (if needed) */ *this_kernel; /* the kernel being applied */ MorphologyMethod primitive; /* the current morphology primitive being applied */ CompositeOperator rslt_compose; /* multi-kernel compose method for results to use */ MagickBooleanType special, /* do we use a direct modify function? */ verbose; /* verbose output of results */ size_t method_loop, /* Loop 1: number of compound method iterations (norm 1) */ method_limit, /* maximum number of compound method iterations */ kernel_number, /* Loop 2: the kernel number being applied */ stage_loop, /* Loop 3: primitive loop for compound morphology */ stage_limit, /* how many primitives are in this compound */ kernel_loop, /* Loop 4: iterate the kernel over image */ kernel_limit, /* number of times to iterate kernel */ count, /* total count of primitive steps applied */ kernel_changed, /* total count of changed using iterated kernel */ method_changed; /* total count of changed over method iteration */ ssize_t changed; /* number pixels changed by last primitive operation */ char v_info[MagickPathExtent]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); count = 0; /* number of low-level morphology primitives performed */ if ( iterations == 0 ) return((Image *) NULL); /* null operation - nothing to do! */ kernel_limit = (size_t) iterations; if ( iterations < 0 ) /* negative interations = infinite (well alomst) */ kernel_limit = image->columns>image->rows ? image->columns : image->rows; verbose = IsStringTrue(GetImageArtifact(image,"debug")); /* initialise for cleanup */ curr_image = (Image *) image; curr_compose = image->compose; (void) curr_compose; work_image = save_image = rslt_image = (Image *) NULL; reflected_kernel = (KernelInfo *) NULL; /* Initialize specific methods * + which loop should use the given iteratations * + how many primitives make up the compound morphology * + multi-kernel compose method to use (by default) */ method_limit = 1; /* just do method once, unless otherwise set */ stage_limit = 1; /* assume method is not a compound */ special = MagickFalse; /* assume it is NOT a direct modify primitive */ rslt_compose = compose; /* and we are composing multi-kernels as given */ switch( method ) { case SmoothMorphology: /* 4 primitive compound morphology */ stage_limit = 4; break; case OpenMorphology: /* 2 primitive compound morphology */ case OpenIntensityMorphology: case TopHatMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case EdgeMorphology: stage_limit = 2; break; case HitAndMissMorphology: rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */ /* FALL THUR */ case ThinningMorphology: case ThickenMorphology: method_limit = kernel_limit; /* iterate the whole method */ kernel_limit = 1; /* do not do kernel iteration */ break; case DistanceMorphology: case VoronoiMorphology: special = MagickTrue; /* use special direct primative */ break; default: break; } /* Apply special methods with special requirments ** For example, single run only, or post-processing requirements */ if ( special != MagickFalse ) { rslt_image=CloneImage(image,0,0,MagickTrue,exception); if (rslt_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse) goto error_cleanup; changed=MorphologyPrimitiveDirect(rslt_image,method,kernel,exception); if (verbose != MagickFalse) (void) (void) FormatLocaleFile(stderr, "%s:%.20g.%.20g #%.20g => Changed %.20g\n", CommandOptionToMnemonic(MagickMorphologyOptions, method), 1.0,0.0,1.0, (double) changed); if ( changed < 0 ) goto error_cleanup; if ( method == VoronoiMorphology ) { /* Preserve the alpha channel of input image - but turned it off */ (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel, exception); (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp, MagickTrue,0,0,exception); (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel, exception); } goto exit_cleanup; } /* Handle user (caller) specified multi-kernel composition method */ if ( compose != UndefinedCompositeOp ) rslt_compose = compose; /* override default composition for method */ if ( rslt_compose == UndefinedCompositeOp ) rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */ /* Some methods require a reflected kernel to use with primitives. * Create the reflected kernel for those methods. */ switch ( method ) { case CorrelateMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case SmoothMorphology: reflected_kernel = CloneKernelInfo(kernel); if (reflected_kernel == (KernelInfo *) NULL) goto error_cleanup; RotateKernelInfo(reflected_kernel,180); break; default: break; } /* Loops around more primitive morpholgy methods ** erose, dilate, open, close, smooth, edge, etc... */ /* Loop 1: iterate the compound method */ method_loop = 0; method_changed = 1; while ( method_loop < method_limit && method_changed > 0 ) { method_loop++; method_changed = 0; /* Loop 2: iterate over each kernel in a multi-kernel list */ norm_kernel = (KernelInfo *) kernel; this_kernel = (KernelInfo *) kernel; rflt_kernel = reflected_kernel; kernel_number = 0; while ( norm_kernel != NULL ) { /* Loop 3: Compound Morphology Staging - Select Primative to apply */ stage_loop = 0; /* the compound morphology stage number */ while ( stage_loop < stage_limit ) { stage_loop++; /* The stage of the compound morphology */ /* Select primitive morphology for this stage of compound method */ this_kernel = norm_kernel; /* default use unreflected kernel */ primitive = method; /* Assume method is a primitive */ switch( method ) { case ErodeMorphology: /* just erode */ case EdgeInMorphology: /* erode and image difference */ primitive = ErodeMorphology; break; case DilateMorphology: /* just dilate */ case EdgeOutMorphology: /* dilate and image difference */ primitive = DilateMorphology; break; case OpenMorphology: /* erode then dialate */ case TopHatMorphology: /* open and image difference */ primitive = ErodeMorphology; if ( stage_loop == 2 ) primitive = DilateMorphology; break; case OpenIntensityMorphology: primitive = ErodeIntensityMorphology; if ( stage_loop == 2 ) primitive = DilateIntensityMorphology; break; case CloseMorphology: /* dilate, then erode */ case BottomHatMorphology: /* close and image difference */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; if ( stage_loop == 2 ) primitive = ErodeMorphology; break; case CloseIntensityMorphology: this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateIntensityMorphology; if ( stage_loop == 2 ) primitive = ErodeIntensityMorphology; break; case SmoothMorphology: /* open, close */ switch ( stage_loop ) { case 1: /* start an open method, which starts with Erode */ primitive = ErodeMorphology; break; case 2: /* now Dilate the Erode */ primitive = DilateMorphology; break; case 3: /* Reflect kernel a close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; break; case 4: /* Finish the Close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ErodeMorphology; break; } break; case EdgeMorphology: /* dilate and erode difference */ primitive = DilateMorphology; if ( stage_loop == 2 ) { save_image = curr_image; /* save the image difference */ curr_image = (Image *) image; primitive = ErodeMorphology; } break; case CorrelateMorphology: /* A Correlation is a Convolution with a reflected kernel. ** However a Convolution is a weighted sum using a reflected ** kernel. It may seem stange to convert a Correlation into a ** Convolution as the Correlation is the simplier method, but ** Convolution is much more commonly used, and it makes sense to ** implement it directly so as to avoid the need to duplicate the ** kernel when it is not required (which is typically the ** default). */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ConvolveMorphology; break; default: break; } assert( this_kernel != (KernelInfo *) NULL ); /* Extra information for debugging compound operations */ if (verbose != MagickFalse) { if ( stage_limit > 1 ) (void) FormatLocaleString(v_info,MagickPathExtent,"%s:%.20g.%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions,method),(double) method_loop,(double) stage_loop); else if ( primitive != method ) (void) FormatLocaleString(v_info, MagickPathExtent, "%s:%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions, method),(double) method_loop); else v_info[0] = '\0'; } /* Loop 4: Iterate the kernel with primitive */ kernel_loop = 0; kernel_changed = 0; changed = 1; while ( kernel_loop < kernel_limit && changed > 0 ) { kernel_loop++; /* the iteration of this kernel */ /* Create a clone as the destination image, if not yet defined */ if ( work_image == (Image *) NULL ) { work_image=CloneImage(image,0,0,MagickTrue,exception); if (work_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse) goto error_cleanup; } /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */ count++; changed = MorphologyPrimitive(curr_image, work_image, primitive, this_kernel, bias, exception); if (verbose != MagickFalse) { if ( kernel_loop > 1 ) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */ (void) (void) FormatLocaleFile(stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g", v_info,CommandOptionToMnemonic(MagickMorphologyOptions, primitive),(this_kernel == rflt_kernel ) ? "*" : "", (double) (method_loop+kernel_loop-1),(double) kernel_number, (double) count,(double) changed); } if ( changed < 0 ) goto error_cleanup; kernel_changed += changed; method_changed += changed; /* prepare next loop */ { Image *tmp = work_image; /* swap images for iteration */ work_image = curr_image; curr_image = tmp; } if ( work_image == image ) work_image = (Image *) NULL; /* replace input 'image' */ } /* End Loop 4: Iterate the kernel with primitive */ if (verbose != MagickFalse && kernel_changed != (size_t)changed) (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed); if (verbose != MagickFalse && stage_loop < stage_limit) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */ #if 0 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image); (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image); (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image); (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image); (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image); #endif } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */ /* Final Post-processing for some Compound Methods ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** Turn off SVG composition 'alpha blending'. */ switch( method ) { case EdgeOutMorphology: case EdgeInMorphology: case TopHatMorphology: case BottomHatMorphology: if (verbose != MagickFalse) (void) FormatLocaleFile(stderr, "\n%s: Difference with original image",CommandOptionToMnemonic( MagickMorphologyOptions, method) ); (void) CompositeImage(curr_image,image,DifferenceCompositeOp, MagickTrue,0,0,exception); break; case EdgeMorphology: if (verbose != MagickFalse) (void) FormatLocaleFile(stderr, "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic( MagickMorphologyOptions, method) ); (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp, MagickTrue,0,0,exception); save_image = DestroyImage(save_image); /* finished with save image */ break; default: break; } /* multi-kernel handling: re-iterate, or compose results */ if ( kernel->next == (KernelInfo *) NULL ) rslt_image = curr_image; /* just return the resulting image */ else if ( rslt_compose == NoCompositeOp ) { if (verbose != MagickFalse) { if ( this_kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " (re-iterate)"); else (void) FormatLocaleFile(stderr, " (done)"); } rslt_image = curr_image; /* return result, and re-iterate */ } else if ( rslt_image == (Image *) NULL) { if (verbose != MagickFalse) (void) FormatLocaleFile(stderr, " (save for compose)"); rslt_image = curr_image; curr_image = (Image *) image; /* continue with original image */ } else { /* Add the new 'current' result to the composition ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** IE: Turn off SVG composition 'alpha blending'. */ if (verbose != MagickFalse) (void) FormatLocaleFile(stderr, " (compose \"%s\")", CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) ); (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue, 0,0,exception); curr_image = DestroyImage(curr_image); curr_image = (Image *) image; /* continue with original image */ } if (verbose != MagickFalse) (void) FormatLocaleFile(stderr, "\n"); /* loop to the next kernel in a multi-kernel list */ norm_kernel = norm_kernel->next; if ( rflt_kernel != (KernelInfo *) NULL ) rflt_kernel = rflt_kernel->next; kernel_number++; } /* End Loop 2: Loop over each kernel */ } /* End Loop 1: compound method interation */ goto exit_cleanup; /* Yes goto's are bad, but it makes cleanup lot more efficient */ error_cleanup: if ( curr_image == rslt_image ) curr_image = (Image *) NULL; if ( rslt_image != (Image *) NULL ) rslt_image = DestroyImage(rslt_image); exit_cleanup: if ( curr_image == rslt_image || curr_image == image ) curr_image = (Image *) NULL; if ( curr_image != (Image *) NULL ) curr_image = DestroyImage(curr_image); if ( work_image != (Image *) NULL ) work_image = DestroyImage(work_image); if ( save_image != (Image *) NULL ) save_image = DestroyImage(save_image); if ( reflected_kernel != (KernelInfo *) NULL ) reflected_kernel = DestroyKernelInfo(reflected_kernel); return(rslt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyImage() applies a user supplied kernel to the image according to % the given mophology method. % % This function applies any and all user defined settings before calling % the above internal function MorphologyApply(). % % User defined settings include... % * Output Bias for Convolution and correlation ("-define convolve:bias=??") % * Kernel Scale/normalize settings ("-define convolve:scale=??") % This can also includes the addition of a scaled unity kernel. % * Show Kernel being applied ("-define morphology:showKernel=1") % % Other operators that do not want user supplied options interfering, % especially "convolve:bias" and "morphology:showKernel" should use % MorphologyApply() directly. % % The format of the MorphologyImage method is: % % Image *MorphologyImage(const Image *image,MorphologyMethod method, % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o kernel: An array of double representing the morphology kernel. % Warning: kernel may be normalized for the Convolve method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod method,const ssize_t iterations, const KernelInfo *kernel,ExceptionInfo *exception) { const char *artifact; CompositeOperator compose; double bias; Image *morphology_image; KernelInfo *curr_kernel; curr_kernel = (KernelInfo *) kernel; bias=0.0; compose = UndefinedCompositeOp; /* use default for method */ /* Apply Convolve/Correlate Normalization and Scaling Factors. * This is done BEFORE the ShowKernelInfo() function is called so that * users can see the results of the 'option:convolve:scale' option. */ if ( method == ConvolveMorphology || method == CorrelateMorphology ) { /* Get the bias value as it will be needed */ artifact = GetImageArtifact(image,"convolve:bias"); if ( artifact != (const char *) NULL) { if (IsGeometry(artifact) == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidSetting","'%s' '%s'", "convolve:bias",artifact); else bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0); } /* Scale kernel according to user wishes */ artifact = GetImageArtifact(image,"convolve:scale"); if ( artifact != (const char *) NULL ) { if (IsGeometry(artifact) == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidSetting","'%s' '%s'", "convolve:scale",artifact); else { if ( curr_kernel == kernel ) curr_kernel = CloneKernelInfo(kernel); if (curr_kernel == (KernelInfo *) NULL) return((Image *) NULL); ScaleGeometryKernelInfo(curr_kernel, artifact); } } } /* display the (normalized) kernel via stderr */ artifact=GetImageArtifact(image,"morphology:showKernel"); if (IsStringTrue(artifact) != MagickFalse) ShowKernelInfo(curr_kernel); /* Override the default handling of multi-kernel morphology results * If 'Undefined' use the default method * If 'None' (default for 'Convolve') re-iterate previous result * Otherwise merge resulting images using compose method given. * Default for 'HitAndMiss' is 'Lighten'. */ { ssize_t parse; artifact = GetImageArtifact(image,"morphology:compose"); if ( artifact != (const char *) NULL) { parse=ParseCommandOption(MagickComposeOptions, MagickFalse,artifact); if ( parse < 0 ) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'", "morphology:compose",artifact); else compose=(CompositeOperator)parse; } } /* Apply the Morphology */ morphology_image = MorphologyApply(image,method,iterations, curr_kernel,compose,bias,exception); /* Cleanup and Exit */ if ( curr_kernel != kernel ) curr_kernel=DestroyKernelInfo(curr_kernel); return(morphology_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotateKernelInfo() rotates the kernel by the angle given. % % Currently it is restricted to 90 degree angles, of either 1D kernels % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels. % It will ignore usless rotations for specific 'named' built-in kernels. % % The format of the RotateKernelInfo method is: % % void RotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is currently internal to this module only, but can be exported % to other modules if needed. */ static void RotateKernelInfo(KernelInfo *kernel, double angle) { /* angle the lower kernels first */ if ( kernel->next != (KernelInfo *) NULL) RotateKernelInfo(kernel->next, angle); /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical ** ** TODO: expand beyond simple 90 degree rotates, flips and flops */ /* Modulus the angle */ angle = fmod(angle, 360.0); if ( angle < 0 ) angle += 360.0; if ( 337.5 < angle || angle <= 22.5 ) return; /* Near zero angle - no change! - At least not at this time */ /* Handle special cases */ switch (kernel->type) { /* These built-in kernels are cylindrical kernels, rotating is useless */ case GaussianKernel: case DoGKernel: case LoGKernel: case DiskKernel: case PeaksKernel: case LaplacianKernel: case ChebyshevKernel: case ManhattanKernel: case EuclideanKernel: return; /* These may be rotatable at non-90 angles in the future */ /* but simply rotating them in multiples of 90 degrees is useless */ case SquareKernel: case DiamondKernel: case PlusKernel: case CrossKernel: return; /* These only allows a +/-90 degree rotation (by transpose) */ /* A 180 degree rotation is useless */ case BlurKernel: if ( 135.0 < angle && angle <= 225.0 ) return; if ( 225.0 < angle && angle <= 315.0 ) angle -= 180; break; default: break; } /* Attempt rotations by 45 degrees -- 3x3 kernels only */ if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 ) { if ( kernel->width == 3 && kernel->height == 3 ) { /* Rotate a 3x3 square by 45 degree angle */ double t = kernel->values[0]; kernel->values[0] = kernel->values[3]; kernel->values[3] = kernel->values[6]; kernel->values[6] = kernel->values[7]; kernel->values[7] = kernel->values[8]; kernel->values[8] = kernel->values[5]; kernel->values[5] = kernel->values[2]; kernel->values[2] = kernel->values[1]; kernel->values[1] = t; /* rotate non-centered origin */ if ( kernel->x != 1 || kernel->y != 1 ) { ssize_t x,y; x = (ssize_t) kernel->x-1; y = (ssize_t) kernel->y-1; if ( x == y ) x = 0; else if ( x == 0 ) x = -y; else if ( x == -y ) y = 0; else if ( y == 0 ) y = x; kernel->x = (ssize_t) x+1; kernel->y = (ssize_t) y+1; } angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */ kernel->angle = fmod(kernel->angle+45.0, 360.0); } else perror("Unable to rotate non-3x3 kernel by 45 degrees"); } if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 ) { if ( kernel->width == 1 || kernel->height == 1 ) { /* Do a transpose of a 1 dimensional kernel, ** which results in a fast 90 degree rotation of some type. */ ssize_t t; t = (ssize_t) kernel->width; kernel->width = kernel->height; kernel->height = (size_t) t; t = kernel->x; kernel->x = kernel->y; kernel->y = t; if ( kernel->width == 1 ) { angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else { angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */ kernel->angle = fmod(kernel->angle+270.0, 360.0); } } else if ( kernel->width == kernel->height ) { /* Rotate a square array of values by 90 degrees */ { register ssize_t i,j,x,y; register MagickRealType *k,t; k=kernel->values; for( i=0, x=(ssize_t) kernel->width-1; i<=x; i++, x--) for( j=0, y=(ssize_t) kernel->height-1; j<y; j++, y--) { t = k[i+j*kernel->width]; k[i+j*kernel->width] = k[j+x*kernel->width]; k[j+x*kernel->width] = k[x+y*kernel->width]; k[x+y*kernel->width] = k[y+i*kernel->width]; k[y+i*kernel->width] = t; } } /* rotate the origin - relative to center of array */ { register ssize_t x,y; x = (ssize_t) (kernel->x*2-kernel->width+1); y = (ssize_t) (kernel->y*2-kernel->height+1); kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2; kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2; } angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else perror("Unable to rotate a non-square, non-linear kernel 90 degrees"); } if ( 135.0 < angle && angle <= 225.0 ) { /* For a 180 degree rotation - also know as a reflection * This is actually a very very common operation! * Basically all that is needed is a reversal of the kernel data! * And a reflection of the origon */ MagickRealType t; register MagickRealType *k; ssize_t i, j; k=kernel->values; j=(ssize_t) (kernel->width*kernel->height-1); for (i=0; i < j; i++, j--) t=k[i], k[i]=k[j], k[j]=t; kernel->x = (ssize_t) kernel->width - kernel->x - 1; kernel->y = (ssize_t) kernel->height - kernel->y - 1; angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */ kernel->angle = fmod(kernel->angle+180.0, 360.0); } /* At this point angle should at least between -45 (315) and +45 degrees * In the future some form of non-orthogonal angled rotates could be * performed here, posibily with a linear kernel restriction. */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e G e o m e t r y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleGeometryKernelInfo() takes a geometry argument string, typically % provided as a "-set option:convolve:scale {geometry}" user setting, % and modifies the kernel according to the parsed arguments of that setting. % % The first argument (and any normalization flags) are passed to % ScaleKernelInfo() to scale/normalize the kernel. The second argument % is then passed to UnityAddKernelInfo() to add a scled unity kernel % into the scaled/normalized kernel. % % The format of the ScaleGeometryKernelInfo method is: % % void ScaleGeometryKernelInfo(KernelInfo *kernel, % const double scaling_factor,const MagickStatusType normalize_flags) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % o geometry: % The geometry string to parse, typically from the user provided % "-set option:convolve:scale {geometry}" setting. % */ MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel, const char *geometry) { MagickStatusType flags; GeometryInfo args; SetGeometryInfo(&args); flags = ParseGeometry(geometry, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/ args.rho *= 0.01, args.sigma *= 0.01; if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */ args.rho = 1.0; if ( (flags & SigmaValue) == 0 ) args.sigma = 0.0; /* Scale/Normalize the input kernel */ ScaleKernelInfo(kernel, args.rho, (GeometryFlags) flags); /* Add Unity Kernel, for blending with original */ if ( (flags & SigmaValue) != 0 ) UnityAddKernelInfo(kernel, args.sigma); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleKernelInfo() scales the given kernel list by the given amount, with or % without normalization of the sum of the kernel values (as per given flags). % % By default (no flags given) the values within the kernel is scaled % directly using given scaling factor without change. % % If either of the two 'normalize_flags' are given the kernel will first be % normalized and then further scaled by the scaling factor value given. % % Kernel normalization ('normalize_flags' given) is designed to ensure that % any use of the kernel scaling factor with 'Convolve' or 'Correlate' % morphology methods will fall into -1.0 to +1.0 range. Note that for % non-HDRI versions of IM this may cause images to have any negative results % clipped, unless some 'bias' is used. % % More specifically. Kernels which only contain positive values (such as a % 'Gaussian' kernel) will be scaled so that those values sum to +1.0, % ensuring a 0.0 to +1.0 output range for non-HDRI images. % % For Kernels that contain some negative values, (such as 'Sharpen' kernels) % the kernel will be scaled by the absolute of the sum of kernel values, so % that it will generally fall within the +/- 1.0 range. % % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel % will be scaled by just the sum of the postive values, so that its output % range will again fall into the +/- 1.0 range. % % For special kernels designed for locating shapes using 'Correlate', (often % only containing +1 and -1 values, representing foreground/brackground % matching) a special normalization method is provided to scale the positive % values separately to those of the negative values, so the kernel will be % forced to become a zero-sum kernel better suited to such searches. % % WARNING: Correct normalization of the kernel assumes that the '*_range' % attributes within the kernel structure have been correctly set during the % kernels creation. % % NOTE: The values used for 'normalize_flags' have been selected specifically % to match the use of geometry options, so that '!' means NormalizeValue, '^' % means CorrelateNormalizeValue. All other GeometryFlags values are ignored. % % The format of the ScaleKernelInfo method is: % % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor, % const MagickStatusType normalize_flags ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scaling_factor: % multiply all values (after normalization) by this factor if not % zero. If the kernel is normalized regardless of any flags. % % o normalize_flags: % GeometryFlags defining normalization method to use. % specifically: NormalizeValue, CorrelateNormalizeValue, % and/or PercentValue % */ MagickExport void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,const GeometryFlags normalize_flags) { register double pos_scale, neg_scale; register ssize_t i; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags); /* Normalization of Kernel */ pos_scale = 1.0; if ( (normalize_flags&NormalizeValue) != 0 ) { if ( fabs(kernel->positive_range + kernel->negative_range) >= MagickEpsilon ) /* non-zero-summing kernel (generally positive) */ pos_scale = fabs(kernel->positive_range + kernel->negative_range); else /* zero-summing kernel */ pos_scale = kernel->positive_range; } /* Force kernel into a normalized zero-summing kernel */ if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) { pos_scale = ( fabs(kernel->positive_range) >= MagickEpsilon ) ? kernel->positive_range : 1.0; neg_scale = ( fabs(kernel->negative_range) >= MagickEpsilon ) ? -kernel->negative_range : 1.0; } else neg_scale = pos_scale; /* finialize scaling_factor for positive and negative components */ pos_scale = scaling_factor/pos_scale; neg_scale = scaling_factor/neg_scale; for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) if (!IsNaN(kernel->values[i])) kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale; /* convolution output range */ kernel->positive_range *= pos_scale; kernel->negative_range *= neg_scale; /* maximum and minimum values in kernel */ kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale; kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale; /* swap kernel settings if user's scaling factor is negative */ if ( scaling_factor < MagickEpsilon ) { double t; t = kernel->positive_range; kernel->positive_range = kernel->negative_range; kernel->negative_range = t; t = kernel->maximum; kernel->maximum = kernel->minimum; kernel->minimum = 1; } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h o w K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShowKernelInfo() outputs the details of the given kernel defination to % standard error, generally due to a users 'morphology:showKernel' option % request. % % The format of the ShowKernel method is: % % void ShowKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickPrivate void ShowKernelInfo(const KernelInfo *kernel) { const KernelInfo *k; size_t c, i, u, v; for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) { (void) FormatLocaleFile(stderr, "Kernel"); if ( kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c ); (void) FormatLocaleFile(stderr, " \"%s", CommandOptionToMnemonic(MagickKernelOptions, k->type) ); if ( fabs(k->angle) >= MagickEpsilon ) (void) FormatLocaleFile(stderr, "@%lg", k->angle); (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,(unsigned long) k->height,(long) k->x,(long) k->y); (void) FormatLocaleFile(stderr, " with values from %.*lg to %.*lg\n", GetMagickPrecision(), k->minimum, GetMagickPrecision(), k->maximum); (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg", GetMagickPrecision(), k->negative_range, GetMagickPrecision(), k->positive_range); if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Zero-Summing)\n"); else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Normalized)\n"); else (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n", GetMagickPrecision(), k->positive_range+k->negative_range); for (i=v=0; v < k->height; v++) { (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v ); for (u=0; u < k->width; u++, i++) if (IsNaN(k->values[i])) (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan"); else (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3, GetMagickPrecision(), (double) k->values[i]); (void) FormatLocaleFile(stderr,"\n"); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n i t y A d d K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel % to the given pre-scaled and normalized Kernel. This in effect adds that % amount of the original image into the resulting convolution kernel. This % value is usually provided by the user as a percentage value in the % 'convolve:scale' setting. % % The resulting effect is to convert the defined kernels into blended % soft-blurs, unsharp kernels or into sharpening kernels. % % The format of the UnityAdditionKernelInfo method is: % % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scale: % scaling factor for the unity kernel to be added to % the given kernel. % */ MagickExport void UnityAddKernelInfo(KernelInfo *kernel, const double scale) { /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) UnityAddKernelInfo(kernel->next, scale); /* Add the scaled unity kernel to the existing kernel */ kernel->values[kernel->x+kernel->y*kernel->width] += scale; CalcKernelMetaData(kernel); /* recalculate the meta-data */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z e r o K e r n e l N a n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroKernelNans() replaces any special 'nan' value that may be present in % the kernel with a zero value. This is typically done when the kernel will % be used in special hardware (GPU) convolution processors, to simply % matters. % % The format of the ZeroKernelNans method is: % % void ZeroKernelNans (KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickPrivate void ZeroKernelNans(KernelInfo *kernel) { register size_t i; /* do the other kernels in a multi-kernel list first */ if (kernel->next != (KernelInfo *) NULL) ZeroKernelNans(kernel->next); for (i=0; i < (kernel->width*kernel->height); i++) if (IsNaN(kernel->values[i])) kernel->values[i]=0.0; return; }
omp_nested.c
<ompts:test> <ompts:testdescription>Test which checks the omp_nested function.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp_nested</ompts:directive> <ompts:dependences>omp critical</ompts:dependences> <ompts:testcode> /* * Test if the compiler supports nested parallelism * By Chunhua Liao, University of Houston * Oct. 2005 */ #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_nested</ompts:testcode:functionname>(FILE * logFile) { <ompts:orphan:vars> int counter = 0; </ompts:orphan:vars> #ifdef _OPENMP <ompts:check>omp_set_nested(1);</ompts:check> <ompts:crosscheck>omp_set_nested(0);</ompts:crosscheck> #endif #pragma omp parallel shared(counter) { <ompts:orphan> #pragma omp critical counter ++; #pragma omp parallel { #pragma omp critical counter --; } </ompts:orphan> } return (counter != 0); } </ompts:testcode> </ompts:test>
pgmp-chudnovsky.c
/* Pi computation using Chudnovsky's algortithm. * Copyright 2002, 2005 Hanhong Xue (macroxue at yahoo dot com) * Slightly modified 2005 by Torbjorn Granlund (tege at swox dot com) to allow more than 2G digits to be computed. * Modifed 2008 by David Carver (dcarver at tacc dot utexas dot edu) to enable multi-threading using the algorithm from "Computation of High-Precision Mathematical Constants in a Combined Cluster and Grid Environment" by Daisuke Takahashi, Mitsuhisa Sato, and Taisuke Boku. For gcc 4.3 gcc -fopenmp -Wall -O2 -o pgmp-chudnovsky pgmp-chudnovsky.c -lgmp -lm For Intel 10.1 compiler icc -openmp -O2 -o pgmp-chudnovsky pgmp-chudnovsky.c -lgmp -lm For AIX xlc xlc_r -qsmp=omp -O2 -o pgmp-chudnovsky pgmp-chudnovsky.c -lgmp -lm Note: add -DNO_FACTOR to disable factorization performance enhancement and use less memory. * 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 AUTHORS ``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 AUTHORS 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 <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/time.h> #include "gmp.h" #ifdef DMALLOC #include "dmalloc.h" #endif #define A 13591409 #define B 545140134 #define C 640320 #define D 12 #define BITS_PER_DIGIT 3.32192809488736234787 #define DIGITS_PER_ITER 14.1816474627254776555 #define DOUBLE_PREC 53 char *prog_name; #if CHECK_MEMUSAGE #undef CHECK_MEMUSAGE #define CHECK_MEMUSAGE \ do { \ char buf[100]; \ snprintf (buf, 100, \ "ps aguxw | grep '[%c]%s'", prog_name[0], prog_name+1); \ system (buf); \ } while (0) #else #undef CHECK_MEMUSAGE #define CHECK_MEMUSAGE #endif //////////////////////////////////////////////////////////////////////////// double wall_clock() { struct timeval timeval; (void) gettimeofday (&timeval, (void *) 0); return (timeval.tv_sec + (timeval.tv_usec / 1000000.0)); } //////////////////////////////////////////////////////////////////////////// mpf_t t1, t2; // r = sqrt(x) void my_sqrt_ui(mpf_t r, unsigned long x) { unsigned long prec, bits, prec0; prec0 = mpf_get_prec(r); if (prec0<=DOUBLE_PREC) { mpf_set_d(r, sqrt(x)); return; } bits = 0; for (prec=prec0; prec>DOUBLE_PREC;) { int bit = prec&1; prec = (prec+bit)/2; bits = bits*2+bit; } mpf_set_prec_raw(t1, DOUBLE_PREC); mpf_set_d(t1, 1/sqrt(x)); while (prec<prec0) { prec *=2; if (prec<prec0) { /* t1 = t1+t1*(1-x*t1*t1)/2; */ mpf_set_prec_raw(t2, prec); mpf_mul(t2, t1, t1); // half x half -> full mpf_mul_ui(t2, t2, x); mpf_ui_sub(t2, 1, t2); mpf_set_prec_raw(t2, prec/2); mpf_div_2exp(t2, t2, 1); mpf_mul(t2, t2, t1); // half x half -> half mpf_set_prec_raw(t1, prec); mpf_add(t1, t1, t2); } else { prec = prec0; /* t2=x*t1, t1 = t2+t1*(x-t2*t2)/2; */ mpf_set_prec_raw(t2, prec/2); mpf_mul_ui(t2, t1, x); mpf_mul(r, t2, t2); // half x half -> full mpf_ui_sub(r, x, r); mpf_mul(t1, t1, r); // half x half -> half mpf_div_2exp(t1, t1, 1); mpf_add(r, t1, t2); break; } prec -= (bits&1); bits /=2; } } // r = y/x WARNING: r cannot be the same as y. void my_div(mpf_t r, mpf_t y, mpf_t x) { unsigned long prec, bits, prec0; prec0 = mpf_get_prec(r); if (prec0<=DOUBLE_PREC) { mpf_set_d(r, mpf_get_d(y)/mpf_get_d(x)); return; } bits = 0; for (prec=prec0; prec>DOUBLE_PREC;) { int bit = prec&1; prec = (prec+bit)/2; bits = bits*2+bit; } mpf_set_prec_raw(t1, DOUBLE_PREC); mpf_ui_div(t1, 1, x); while (prec<prec0) { prec *=2; if (prec<prec0) { /* t1 = t1+t1*(1-x*t1); */ mpf_set_prec_raw(t2, prec); mpf_mul(t2, x, t1); // full x half -> full mpf_ui_sub(t2, 1, t2); mpf_set_prec_raw(t2, prec/2); mpf_mul(t2, t2, t1); // half x half -> half mpf_set_prec_raw(t1, prec); mpf_add(t1, t1, t2); } else { prec = prec0; /* t2=y*t1, t1 = t2+t1*(y-x*t2); */ mpf_set_prec_raw(t2, prec/2); mpf_mul(t2, t1, y); // half x half -> half mpf_mul(r, x, t2); // full x half -> full mpf_sub(r, y, r); mpf_mul(t1, t1, r); // half x half -> half mpf_add(r, t1, t2); break; } prec -= (bits&1); bits /=2; } } //////////////////////////////////////////////////////////////////////////// #ifndef NO_FACTOR #define min(x,y) ((x)<(y)?(x):(y)) #define max(x,y) ((x)>(y)?(x):(y)) typedef struct { unsigned long max_facs; unsigned long num_facs; unsigned long *fac; unsigned long *pow; } fac_t[1]; typedef struct { long int fac; long int pow; long int nxt; } sieve_t; fac_t **fpstack, **fgstack; sieve_t *sieve; long int sieve_size; fac_t *ftmp, *fmul; clock_t gcd_time = 0; #define INIT_FACS 32 void fac_show(fac_t f) { long int i; for (i=0; i<f[0].num_facs; i++) if (f[0].pow[i]==1) fprintf(stderr,"%ld ", f[0].fac[i]); else fprintf(stderr,"%ld^%ld ", f[0].fac[i], f[0].pow[i]); fprintf(stderr,"\n"); } inline void fac_reset(fac_t f) { f[0].num_facs = 0; } inline void fac_init_size(fac_t f, long int s) { if (s<INIT_FACS) s=INIT_FACS; f[0].fac = malloc(s*sizeof(unsigned long)*2); f[0].pow = f[0].fac + s; f[0].max_facs = s; fac_reset(f); } inline void fac_init(fac_t f) { fac_init_size(f, INIT_FACS); } inline void fac_clear(fac_t f) { free(f[0].fac); } inline void fac_resize(fac_t f, long int s) { if (f[0].max_facs < s) { fac_clear(f); fac_init_size(f, s); } } // f = base^pow inline void fac_set_bp(fac_t f, unsigned long base, long int pow) { long int i; assert(base<sieve_size); for (i=0, base/=2; base>0; i++, base = sieve[base].nxt) { f[0].fac[i] = sieve[base].fac; f[0].pow[i] = sieve[base].pow*pow; } f[0].num_facs = i; assert(i<=f[0].max_facs); } // r = f*g inline void fac_mul2(fac_t r, fac_t f, fac_t g) { long int i, j, k; for (i=j=k=0; i<f[0].num_facs && j<g[0].num_facs; k++) { if (f[0].fac[i] == g[0].fac[j]) { r[0].fac[k] = f[0].fac[i]; r[0].pow[k] = f[0].pow[i] + g[0].pow[j]; i++; j++; } else if (f[0].fac[i] < g[0].fac[j]) { r[0].fac[k] = f[0].fac[i]; r[0].pow[k] = f[0].pow[i]; i++; } else { r[0].fac[k] = g[0].fac[j]; r[0].pow[k] = g[0].pow[j]; j++; } } for (; i<f[0].num_facs; i++, k++) { r[0].fac[k] = f[0].fac[i]; r[0].pow[k] = f[0].pow[i]; } for (; j<g[0].num_facs; j++, k++) { r[0].fac[k] = g[0].fac[j]; r[0].pow[k] = g[0].pow[j]; } r[0].num_facs = k; assert(k<=r[0].max_facs); } // f *= g inline void fac_mul(fac_t f, fac_t g, unsigned long index) { fac_t tmp; fac_resize(fmul[index], f[0].num_facs + g[0].num_facs); fac_mul2(fmul[index], f, g); tmp[0] = f[0]; f[0] = fmul[index][0]; fmul[index][0] = tmp[0]; } // f *= base^pow inline void fac_mul_bp(fac_t f, unsigned long base, unsigned long pow, unsigned long index) { fac_set_bp(ftmp[index], base, pow); fac_mul(f, ftmp[index], index); } // remove factors of power 0 inline void fac_compact(fac_t f) { long int i, j; for (i=0, j=0; i<f[0].num_facs; i++) { if (f[0].pow[i]>0) { if (j<i) { f[0].fac[j] = f[0].fac[i]; f[0].pow[j] = f[0].pow[i]; } j++; } } f[0].num_facs = j; } // convert factorized form to number void bs_mul(mpz_t r, long int a, long int b, unsigned long index) { long int i, j; if (b-a<=32) { mpz_set_ui(r, 1); for (i=a; i<b; i++) for (j=0; j<fmul[index][0].pow[i]; j++) mpz_mul_ui(r, r, fmul[index][0].fac[i]); } else { mpz_t r2; mpz_init(r2); bs_mul(r2, a, (a+b)/2, index); bs_mul(r, (a+b)/2, b, index); mpz_mul(r, r, r2); mpz_clear(r2); } } mpz_t *gcd; // f /= gcd(f,g), g /= gcd(f,g) void fac_remove_gcd(mpz_t p, fac_t fp, mpz_t g, fac_t fg, unsigned long index) { long int i, j, k, c; fac_resize(fmul[index], min(fp->num_facs, fg->num_facs)); for (i=j=k=0; i<fp->num_facs && j<fg->num_facs; ) { if (fp->fac[i] == fg->fac[j]) { c = min(fp->pow[i], fg->pow[j]); fp->pow[i] -= c; fg->pow[j] -= c; fmul[index]->fac[k] = fp->fac[i]; fmul[index]->pow[k] = c; i++; j++; k++; } else if (fp->fac[i] < fg->fac[j]) { i++; } else { j++; } } fmul[index]->num_facs = k; assert(k <= fmul[index]->max_facs); if (fmul[index]->num_facs) { bs_mul(gcd[index], 0, fmul[index]->num_facs, index); mpz_tdiv_q(p, p, gcd[index]); mpz_tdiv_q(g, g, gcd[index]); fac_compact(fp); fac_compact(fg); } } void build_sieve(long int n, sieve_t *s) { long int m, i, j, k, id2, jd2; sieve_size = n; m = (long int)sqrt(n); memset(s, 0, sizeof(sieve_t)*n/2); s[1/2].fac = 1; s[1/2].pow = 1; for (i=3; i<=n; i+=2) { id2 = i >> 1; if (s[id2].fac == 0) { s[id2].fac = i; s[id2].pow = 1; if (i<=m) { for (j=i*i, k=id2; j<=n; j+=i+i, k++) { jd2 = j >> 1; if (s[jd2].fac==0) { s[jd2].fac = i; if (s[k].fac == i) { s[jd2].pow = s[k].pow + 1; s[jd2].nxt = s[k].nxt; } else { s[jd2].pow = 1; s[jd2].nxt = k; } } } } } } } #endif /* NO_FACTOR */ //////////////////////////////////////////////////////////////////////////// int out=0; mpz_t **pstack, **qstack, **gstack; long int cores=1, depth, cores_depth; double progress=0, percent; // binary splitting void sum(unsigned long i, unsigned long j, unsigned long gflag) { mpz_mul(pstack[i][0], pstack[i][0], pstack[j][0]); mpz_mul(qstack[i][0], qstack[i][0], pstack[j][0]); mpz_mul(qstack[j][0], qstack[j][0], gstack[i][0]); mpz_add(qstack[i][0], qstack[i][0], qstack[j][0]); if (gflag) { mpz_mul(gstack[i][0], gstack[i][0], gstack[j][0]); } } void bs(unsigned long a, unsigned long b, unsigned long gflag, unsigned long level, unsigned long index, unsigned long top) { #ifndef NO_FACTOR unsigned long i, mid; #else unsigned long mid; #endif int ccc; if (out&2) { fprintf(stderr,"bs: a = %ld b = %ld gflag = %ld index = %ld level = %ld top = %ld \n", a,b,gflag,index,level,top); fflush(stderr); } if ((b > a) && (b-a==1)) { /* g(b-1,b) = (6b-5)(2b-1)(6b-1) p(b-1,b) = b^3 * C^3 / 24 q(b-1,b) = (-1)^b*g(b-1,b)*(A+Bb). */ mpz_set_ui(pstack[index][top], b); mpz_mul_ui(pstack[index][top], pstack[index][top], b); mpz_mul_ui(pstack[index][top], pstack[index][top], b); mpz_mul_ui(pstack[index][top], pstack[index][top], (C/24)*(C/24)); mpz_mul_ui(pstack[index][top], pstack[index][top], C*24); mpz_set_ui(gstack[index][top], 2*b-1); mpz_mul_ui(gstack[index][top], gstack[index][top], 6*b-1); mpz_mul_ui(gstack[index][top], gstack[index][top], 6*b-5); mpz_set_ui(qstack[index][top], b); mpz_mul_ui(qstack[index][top], qstack[index][top], B); mpz_add_ui(qstack[index][top], qstack[index][top], A); mpz_mul (qstack[index][top], qstack[index][top], gstack[index][top]); if (b%2) mpz_neg(qstack[index][top], qstack[index][top]); #ifndef NO_FACTOR i=b; while ((i&1)==0) i>>=1; fac_set_bp(fpstack[index][top], i, 3); // b^3 fac_mul_bp(fpstack[index][top], 3*5*23*29, 3, index); fpstack[index][top][0].pow[0]--; fac_set_bp(fgstack[index][top], 2*b-1, 1); // 2b-1 fac_mul_bp(fgstack[index][top], 6*b-1, 1, index); // 6b-1 fac_mul_bp(fgstack[index][top], 6*b-5, 1, index); // 6b-5 #endif /* NO_FACTOR */ if (b>(int)(progress)) { fprintf(stderr,"."); fflush(stderr); progress += percent*2; } } else { /* p(a,b) = p(a,m) * p(m,b) g(a,b) = g(a,m) * g(m,b) q(a,b) = q(a,m) * p(m,b) + q(m,b) * g(a,m) */ mid = a+(b-a)*0.5224; // tuning parameter bs(a, mid, 1, level+1, index, top); bs(mid, b, gflag, level+1, index, top+1); ccc = level == 0; #ifndef NO_FACTOR if (ccc) CHECK_MEMUSAGE; if (level>=4) { // tuning parameter clock_t t = clock(); fac_remove_gcd(pstack[index][top+1], fpstack[index][top+1], gstack[index][top], fgstack[index][top], index); gcd_time += clock()-t; } #endif /* NO_FACTOR */ if (ccc) CHECK_MEMUSAGE; mpz_mul(pstack[index][top], pstack[index][top], pstack[index][top+1]); if (ccc) CHECK_MEMUSAGE; mpz_mul(qstack[index][top], qstack[index][top], pstack[index][top+1]); if (ccc) CHECK_MEMUSAGE; mpz_mul(qstack[index][top+1], qstack[index][top+1], gstack[index][top]); if (ccc) CHECK_MEMUSAGE; mpz_add(qstack[index][top], qstack[index][top], qstack[index][top+1]); #ifndef NO_FACTOR if (ccc) CHECK_MEMUSAGE; fac_mul(fpstack[index][top], fpstack[index][top+1], index); #endif /* NO_FACTOR */ if (gflag) { mpz_mul(gstack[index][top], gstack[index][top], gstack[index][top+1]); #ifndef NO_FACTOR fac_mul(fgstack[index][top], fgstack[index][top+1], index); #endif /* NO_FACTOR */ } } #ifndef NO_FACTOR if (out&2) { fprintf(stderr,"p(%ld,%ld)=",a,b); fac_show(fpstack[index][top]); if (gflag) fprintf(stderr,"g(%ld,%ld)=",a,b); fac_show(fgstack[index][top]); } #endif /* NO_FACTOR */ } int main(int argc, char *argv[]) { mpf_t pi, qi; long int d=100, terms, i, j, k, cores_size; unsigned long psize, qsize, mid; clock_t begin, mid0, mid1, mid2, mid3, mid4, end; double wbegin, wmid0, wmid1, wend; prog_name = argv[0]; if (argc==1) { fprintf(stderr,"\nSyntax: %s <digits> <option> <cores>\n",prog_name); fprintf(stderr," <digits> digits of pi to output\n"); fprintf(stderr," <option> 0 - just run (default)\n"); fprintf(stderr," 1 - output digits\n"); fprintf(stderr," 2 - debug\n"); fprintf(stderr," <cores> number of cores (default 1)\n"); exit(1); } if (argc>1) d = strtoul(argv[1], 0, 0); if (argc>2) out = atoi(argv[2]); if (argc>3) cores = atoi(argv[3]); terms = d/DIGITS_PER_ITER; depth = 0; while ((1L<<depth)<terms) depth++; depth++; if (cores < 1) { fprintf(stderr,"Number of cores reset from %ld to 1\n",cores); fflush(stderr); cores = 1; } if ((terms > 0) && (terms < cores)) { fprintf(stderr,"Number of cores reset from %ld to %ld\n",cores,terms); fflush(stderr); cores = terms; } cores_depth = 0; while ((1L<<cores_depth)<cores) cores_depth++; cores_size=pow(2,cores_depth); percent = terms/100.0; fprintf(stderr,"#terms=%ld, depth=%ld, cores=%ld\n", terms, depth, cores); begin = clock(); wbegin = wall_clock(); #ifndef NO_FACTOR sieve_size = max(3*5*23*29+1, terms*6); sieve = (sieve_t *)malloc(sizeof(sieve_t)*sieve_size/2); build_sieve(sieve_size, sieve); #endif /* NO_FACTOR */ mid0 = clock(); wmid0 = wall_clock(); #ifndef NO_FACTOR fprintf(stderr,"sieve cputime = %6.3f\n", (double)(mid0-begin)/CLOCKS_PER_SEC); #endif /* NO_FACTOR */ /* allocate stacks */ pstack = malloc(sizeof(mpz_t)*cores); qstack = malloc(sizeof(mpz_t)*cores); gstack = malloc(sizeof(mpz_t)*cores); for (j = 0; j < cores; j++) { pstack[j] = malloc(sizeof(mpz_t)*depth); qstack[j] = malloc(sizeof(mpz_t)*depth); gstack[j] = malloc(sizeof(mpz_t)*depth); for (i = 0; i < depth; i++) { mpz_init(pstack[j][i]); mpz_init(qstack[j][i]); mpz_init(gstack[j][i]); } } /* begin binary splitting process */ if (terms<=0) { mpz_set_ui(pstack[0][0],1); mpz_set_ui(qstack[0][0],0); mpz_set_ui(gstack[0][0],1); for (i = 1; i < cores; i++) { mpz_clear(pstack[i][0]); mpz_clear(qstack[i][0]); mpz_clear(gstack[i][0]); free(pstack[i]); free(qstack[i]); free(gstack[i]); } } else { #ifndef NO_FACTOR gcd = malloc(sizeof(mpz_t)*cores); ftmp = malloc(sizeof(fac_t)*cores); fmul = malloc(sizeof(fac_t)*cores); fpstack = malloc(sizeof(fac_t)*cores); fgstack = malloc(sizeof(fac_t)*cores); for (j = 0; j < cores; j++) { fpstack[j] = malloc(sizeof(fac_t)*depth); fgstack[j] = malloc(sizeof(fac_t)*depth); mpz_init(gcd[j]); fac_init(ftmp[j]); fac_init(fmul[j]); for (i = 0; i < depth; i++) { fac_init(fpstack[j][i]); fac_init(fgstack[j][i]); } } #endif /* NO_FACTOR */ mid0 = clock(); wmid0 = wall_clock(); mid = terms / cores; #ifdef _OPENMP #ifndef NO_FACTOR #pragma omp parallel for default(shared) private(i) reduction(+:gcd_time) #else #pragma omp parallel for default(shared) private(i) #endif #endif for (i = 0; i < cores; i++) { if (i < (cores-1)) bs(i*mid, (i+1)*mid, 1, cores_depth, i, 0); else bs(i*mid, terms, 1, cores_depth, i, 0); } for (j = 0; j < cores; j++) { for (i=1; i<depth; i++) { mpz_clear(pstack[j][i]); mpz_clear(qstack[j][i]); mpz_clear(gstack[j][i]); } } #ifndef NO_FACTOR for (j = 0; j < cores; j++) { mpz_clear(gcd[j]); fac_clear(ftmp[j]); fac_clear(fmul[j]); for (i=0; i<depth; i++) { fac_clear(fpstack[j][i]); fac_clear(fgstack[j][i]); } free(fpstack[j]); free(fgstack[j]); } free(gcd); free(ftmp); free(fmul); free(fpstack); free(fgstack); #endif /* NO_FACTOR */ for (k = 1; k < cores_size; k*=2) { #ifdef _OPENMP #pragma omp parallel for default(shared) private(i) #endif for (i = 0; i < cores; i=i+2*k) { if (i+k < cores) { sum( i, i+k, 1); mpz_clear(pstack[i+k][0]); mpz_clear(qstack[i+k][0]); mpz_clear(gstack[i+k][0]); free(pstack[i+k]); free(qstack[i+k]); free(gstack[i+k]); } } } } mpz_clear(gstack[0][0]); free(gstack[0]); free(gstack); mid1 = clock(); wmid1 = wall_clock(); fprintf(stderr,"\nbs cputime = %6.3f wallclock = %6.3f\n", (double)(mid1-mid0)/CLOCKS_PER_SEC, (wmid1-wmid0)); #ifndef NO_FACTOR fprintf(stderr,"gcd cputime = %6.3f\n", (double)(gcd_time)/CLOCKS_PER_SEC); //fprintf(stderr,"misc "); fflush(stderr); /* free some resources */ free(sieve); #endif /* NO_FACTOR */ /* prepare to convert integers to floats */ mpf_set_default_prec((long int)(d*BITS_PER_DIGIT+16)); /* p*(C/D)*sqrt(C) pi = ----------------- (q+A*p) */ psize = mpz_sizeinbase(pstack[0][0],10); qsize = mpz_sizeinbase(qstack[0][0],10); mpz_addmul_ui(qstack[0][0], pstack[0][0], A); mpz_mul_ui(pstack[0][0], pstack[0][0], C/D); mpf_init(pi); mpf_set_z(pi, pstack[0][0]); mpz_clear(pstack[0][0]); mpf_init(qi); mpf_set_z(qi, qstack[0][0]); mpz_clear(qstack[0][0]); free(pstack[0]); free(qstack[0]); free(pstack); free(qstack); mid2 = clock(); //fprintf(stderr,"cputime = %6.3f\n", (double)(mid2-mid1)/CLOCKS_PER_SEC); /* initialize temp float variables for sqrt & div */ mpf_init(t1); mpf_init(t2); //mpf_set_prec_raw(t1, mpf_get_prec(pi)); /* final step */ fprintf(stderr,"div "); fflush(stderr); my_div(qi, pi, qi); mid3 = clock(); fprintf(stderr,"cputime = %6.3f\n", (double)(mid3-mid2)/CLOCKS_PER_SEC); fprintf(stderr,"sqrt "); fflush(stderr); my_sqrt_ui(pi, C); mid4 = clock(); fprintf(stderr,"cputime = %6.3f\n", (double)(mid4-mid3)/CLOCKS_PER_SEC); fprintf(stderr,"mul "); fflush(stderr); mpf_mul(qi, qi, pi); end = clock(); wend = wall_clock(); fprintf(stderr,"cputime = %6.3f\n", (double)(end-mid4)/CLOCKS_PER_SEC); fprintf(stderr,"total cputime = %6.3f wallclock = %6.3f\n", (double)(end-begin)/CLOCKS_PER_SEC, (wend-wbegin)); fflush(stderr); fprintf(stderr," P size=%ld digits (%f)\n" " Q size=%ld digits (%f)\n", psize, (double)psize/d, qsize, (double)qsize/d); /* output Pi and timing statistics */ if (out&1) { fprintf(stdout,"pi(0,%ld)=\n", terms); mpf_out_str(stdout, 10, d+2, qi); fprintf(stdout,"\n"); } /* free float resources */ mpf_clear(pi); mpf_clear(qi); mpf_clear(t1); mpf_clear(t2); exit (0); }
convection_solver.h
#ifndef _CONVECTION_SOLVER_ #define _CONVECTION_SOLVER_ #include <complex> #include "toefl/toefl.h" enum target{ TEMPERATURE, VORTICITY, POTENTIAL }; struct Parameter { double R; double P; double nu; unsigned nx; unsigned nz; double lx; double lz; double h; double dt; enum toefl::bc bc_z; template< class Ostream> void display( Ostream& os) { os << "R is: "<< R <<"\n"; os << "P is: "<< P <<"\n"; os << "nu is: "<<nu <<"\n"; os << "nx is: "<< nx <<"\n"; os << "nz is: "<< nz <<"\n"; os << "lx is: "<< lx <<"\n"; os << "lz is: "<< lz <<"\n"; os << "h is: "<< h <<"\n"; os << "dt is: "<< dt <<"\n"; } }; typedef std::complex<double> Complex; void rayleigh_equations( toefl::QuadMat< Complex,2>& coeff, const Complex dx, const Complex dy, const Parameter& p) { double laplace = (dx*dx + dy*dy).real(); coeff( 0,0) = laplace - p.nu*laplace*laplace, coeff( 0,1) = -p.R*dx/laplace; coeff( 1,0) = -p.P*dx, coeff( 1,1) = p.P*laplace - p.nu*laplace*laplace; } inline void laplace_inverse( double& l_inv, const Complex dx, const Complex dy) { l_inv = 1.0/(dx*dx + dy*dy).real(); } namespace toefl{ /*! @brief Solver for periodic boundary conditions of the toefl equations. * @ingroup solvers */ class Convection_Solver { public: typedef Matrix<double, TL_DFT> Matrix_Type; /*! @brief Construct a solver for periodic boundary conditions * * The constructor allocates storage for the solver * and initializes all fourier coefficients as well as * all low level solvers needed. * @param blueprint Contains all the necessary parameters. * @throw Message If your parameters are inconsistent. */ Convection_Solver( const Parameter& param); /*! @brief Prepare Solver for execution * * This function takes the fields and computes the missing * one according to the target parameter passed. After that * it performs three initializing steps (one onestep-, * one twostep-method and the threestep-method used in the step function) * in order to initialize the karniadakis scheme. The actual time is * thus T_0 + 3*dt after initialisation. * @param v Container with three non void matrices * @param t which Matrix is missing? */ void init( std::array< Matrix<double,TL_DFT>, 2>& v, enum target t); /*! @brief Perform a step by the 3 step Karniadakis scheme*/ void step(){ step_<TL_ORDER3>();} /*! @brief Get the result You get the solution matrix of the current timestep. @param t The field you want @return A Read only reference to the field @attention The reference is only valid until the next call to the step() function! */ const Matrix<double, TL_DFT>& getField( enum target t) const; /*! @brief Get the result Use this function when you want to call step() without destroying the solution. @param m In exchange for the solution matrix you have to provide storage for further calculations. The field is swapped in. @param t The field you want. @attention The fields you get are not the ones of the current timestep. You get the fields that are not needed any more. This means the densities are 4 timesteps "old" whereas the potential is the one of the last timestep. */ void getField( Matrix<double, TL_DFT>& m, enum target t); /*! @brief Get the parameters of the solver. @return The parameters in use. @note You cannot change parameters once constructed. */ const Parameter& parameter() const { return param;} void setHeat( double x0, double y0, double sigma_x, double sigma_y, double amp){ if( x0 >= 0 && x0 < param.lx && y0 >= 0 && y0 < param.lz) x0_ = x0, y0_ = y0, sigma_x_ = sigma_x, sigma_y_ = sigma_y, amp_ = amp; else std::cerr << "x0 or y0 is not within the boundaries!\n"; } private: typedef std::complex<double> complex; //methods void init_coefficients( ); void compute_cphi();//multiply cphi void first_steps(); template< enum stepper S> void step_(); //members const size_t rows, cols; const size_t crows, ccols; double x0_, y0_, sigma_x_, sigma_y_, amp_; const Parameter param; /////////////////fields////////////////////////////////// //GhostMatrix<double, TL_DFT> ghostdens, ghostphi; std::array< Matrix_Type, 2> dens, nonlinear; GhostMatrix<double, TL_DFT> phi; /////////////////Complex (void) Matrices for fourier transforms/////////// std::array< Matrix< complex>, 2> cdens; Matrix< complex> cphi; ///////////////////Solvers//////////////////////// Arakawa arakawa; Karniadakis<2, complex, TL_DFT> karniadakis; DFT_DRT dft_drt; /////////////////////Coefficients////////////////////// Matrix< double > phi_coeff; }; Convection_Solver::Convection_Solver( const Parameter& p): rows( p.nz ), cols( p.nx ), crows( rows), ccols( cols/2+1), x0_(0), y0_(0), sigma_x_(0), sigma_y_(0), amp_(0), param( p), //fields dens( MatrixArray<double, TL_DFT, 2>::construct( rows, cols)), nonlinear( dens), phi( rows, cols, param.bc_z, TL_PERIODIC), cdens( MatrixArray<complex, TL_NONE, 2>::construct( crows, ccols)), cphi(crows, ccols), //Solvers arakawa( p.h), karniadakis(rows, cols, crows, ccols, p.dt), dft_drt( rows, cols, fftw_convert( p.bc_z), FFTW_MEASURE), //Coefficients phi_coeff( crows, ccols) { init_coefficients( ); } void Convection_Solver::init_coefficients( ) { Matrix< QuadMat< complex, 2> > coeff( crows, ccols); const complex kxmin( 0, 2.*M_PI/param.lx), kzmin( 0, M_PI/param.lz); // dft_drt is not transposing so i is the y index by default for( unsigned i = 0; i<crows; i++) for( unsigned j = 0; j<ccols; j++) { rayleigh_equations( coeff( i,j), (double)j*kxmin, (double)(i+1)*kzmin, param); laplace_inverse( phi_coeff( i,j), (double)j*kxmin, (double)(i+1)*kzmin); } double norm = param.nx * fftw_normalisation( param.bc_z, param.nz); karniadakis.init_coeff( coeff, norm); } void Convection_Solver::init( std::array< Matrix<double, TL_DFT>,2>& v, enum target t) { //fourier transform input into cdens for( unsigned k=0; k<2; k++) { #ifdef TL_DEBUG if( v[k].isVoid()) throw Message("You gave me a void Matrix!!", _ping_); #endif dft_drt.r2c( v[k], cdens[k]); } //don't forget to normalize coefficients!! double norm = param.nx * fftw_normalisation( param.bc_z, param.nz); for( unsigned k=0; k<2; k++) for( unsigned i=0; i<crows; i++) for( unsigned j=0; j<ccols;j++) cdens[k](i,j) /= norm; switch( t) //which field must be computed? { case( TEMPERATURE): throw Message( "Temperature independent", _ping_); break; case( VORTICITY): //bring cdens and cphi in the right order swap_fields( cphi, cdens[1]); //solve for cdens[1] for( unsigned i=0; i<crows; i++) for( unsigned j=0; j<ccols; j++) cdens[1](i,j) = cphi(i,j) /phi_coeff(i,j); break; case( POTENTIAL): //solve for cphi for( unsigned i=0; i<crows; i++) for( unsigned j=0; j<ccols; j++) { cphi(i,j) = cdens[1](i,j)*phi_coeff(i,j); } break; } //backtransform to x-space for( unsigned k=0; k<2; k++) { dft_drt.c2r( cdens[k], dens[k]); } dft_drt.c2r( cphi, phi); //now the density and the potential is given in x-space first_steps(); } void Convection_Solver::getField( Matrix<double, TL_DFT>& m, enum target t) { #ifdef TL_DEBUG if(m.isVoid()) throw Message( "You may not swap in a void Matrix!\n", _ping_); #endif switch( t) { case( TEMPERATURE): swap_fields( m, nonlinear[0]); break; case( VORTICITY): swap_fields( m, nonlinear[1]); break; case( POTENTIAL): swap_fields( m, cphi); break; } } const Matrix<double, TL_DFT>& Convection_Solver::getField( enum target t) const { Matrix<double, TL_DFT> const * m = 0; switch( t) { case( TEMPERATURE): m = &dens[0]; break; case( VORTICITY): m = &dens[1]; break; case( POTENTIAL): m = &phi; break; } return *m; } void Convection_Solver::first_steps() { karniadakis.invert_coeff<TL_EULER>( ); step_<TL_EULER>(); karniadakis.invert_coeff<TL_ORDER2>(); step_<TL_ORDER2>(); karniadakis.invert_coeff<TL_ORDER3>(); step_<TL_ORDER3>(); } void Convection_Solver::compute_cphi() { #pragma omp parallel for for( size_t i = 0; i < crows; i++) for( size_t j = 0; j < ccols; j++) cphi(i,j) = phi_coeff(i,j)*cdens[1](i,j); } template< enum stepper S> void Convection_Solver::step_() { phi.initGhostCells( ); //1. Compute nonlinearity #pragma omp parallel for for( unsigned k=0; k<2; k++) { GhostMatrix<double, TL_DFT> ghostdens{ rows, cols, param.bc_z, TL_PERIODIC, TL_VOID}; swap_fields( dens[k], ghostdens); //now dens[k] is void ghostdens.initGhostCells( ); arakawa( phi, ghostdens, nonlinear[k]); swap_fields( dens[k], ghostdens); //now ghostdens is void } if( amp_ != 0) { init_gaussian( dens[0], x0_, y0_, sigma_x_, sigma_y_, amp_); } //2. perform karniadakis step karniadakis.step_i<S>( dens, nonlinear); //3. solve linear equation //3.1. transform v_hut #pragma omp parallel for for( unsigned k=0; k<2; k++) dft_drt.r2c( dens[k], cdens[k]); //3.2. perform karniadaksi step and multiply coefficients for phi karniadakis.step_ii( cdens); compute_cphi(); //3.3. backtransform #pragma omp parallel for for( unsigned k=0; k<2; k++) dft_drt.c2r( cdens[k], dens[k]); dft_drt.c2r( cphi, phi); //field in phi again } }//namespace toefl #endif //_CONVECTION_SOLVER_
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-2,4),ceild(8*t2-Nz-3,16));t3<=min(floord(4*Nt+Ny-9,16),floord(4*t1+Ny-1,16));t3++) { for (t4=max(max(ceild(t1-62,64),ceild(8*t2-Nz-243,256)),ceild(16*t3-Ny-243,256));t4<=min(min(floord(4*Nt+Nx-9,256),floord(4*t1+Nx-1,256)),floord(16*t3+Nx+3,256));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(256*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),4*t3+2),64*t4+62);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(256*t4,4*t5+4); ubv=min(256*t4+255,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
analysisTools.h
#ifndef ANALYSISTOOLS_H #define ANALYSISTOOLS_H #include "block3D.h" #include "geometry.h" #include "io.h" #include "randomnumber.h" #include <cmath> #include <cfloat> #include <limits> #include <queue> #include <vector> #include <sstream> using std::vector; class Filter{ public: Filter(double a,double b,double c):pixel(3,3,3){ int sum; for(int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ for (int k = 0; k < 3; k++){ sum=0; if(i-1!=0) sum++; if(j-1!=0) sum++; if(k-1!=0) sum++; switch(sum){ case 0: pixel.get(i,j,k)=0; break; case 1: pixel.get(i,j,k)=a; break; case 2: pixel.get(i,j,k)=b; break; case 3: pixel.get(i,j,k)=c; break; default: break; } } } } } virtual ~Filter(){} double get(int x,int y,int z){ return pixel.get(x+1,y+1,z+1); } double const& get(int x,int y,int z) const{ return pixel.get(x+1,y+1,z+1); } public: ScalarField3D pixel; }; class Node:public Dot3D{ public: Node():Dot3D(0,0,0),step(0),parent(NULL){} Node(Dot3D const& dot, double step_, Node* parent_=NULL):Dot3D(dot),step(step_),parent(parent_){} void setNode(Dot3D const& dot, double step_, Node* parent_){ x=dot.x; y=dot.y; z=dot.z; step=step_; parent=parent_; } virtual ~Node(){} public: double step; Node* parent; }; enum mode{d6=6,d18=18,d26=26}; class addScale{ public: addScale(enum mode m):n(m){} std::vector<int> X={0,0,0,0,1,-1,0,0,1,-1,0,0,1,-1,1,1,-1,-1,-1,-1,-1,-1,1,1,1,1}; std::vector<int> Y={0,0,1,-1,0,0,1,-1,0,0,1,-1,0,0,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1}; std::vector<int> Z={1,-1,0,0,0,0,1,1,1,1,-1,-1,-1,-1,0,0,0,0,-1,1,-1,1,-1,1,-1,1}; int n; }; class analysisTools { public: analysisTools(ScalarField3D const& input, double init=0.0, int envelope_=1) :envelope(envelope_), analysisdomain(input.getBoundingBox().x0,input.getBoundingBox().x1+2*envelope, input.getBoundingBox().y0,input.getBoundingBox().y1+2*envelope, input.getBoundingBox().z0,input.getBoundingBox().z1+2*envelope), rawdata(analysisdomain.getNx(),analysisdomain.getNy(),analysisdomain.getNz(),init), resultdata(analysisdomain.getNx(),analysisdomain.getNy(),analysisdomain.getNz(),init){ Box3D datadomain=analysisdomain.enlarge(-envelope); for (int i = datadomain.x0; i <= datadomain.x1; i++){ for (int j = datadomain.y0; j <= datadomain.y1; j++){ for (int k = datadomain.z0; k <= datadomain.z1; k++){ rawdata.get(i,j,k)=input.get(i-envelope, j-envelope, k-envelope); } } } } ~analysisTools(){} void distanceTransform(Filter const& filter, addScale const& addscale, int rawdataType){ omp_set_num_threads(12); resultdata.reset(); Box3D datadomain=analysisdomain.enlarge(-envelope); ScalarField3D first(analysisdomain.getNx(),analysisdomain.getNy(),analysisdomain.getNz(),-1); // the change of rawdata input; // value 0 is the datadomain without wall // value 1 is the datadomain with all wall // value other is the datadomain with x-directcion and y-direction wall Box3D rawdatainput; if(rawdataType==0) rawdatainput=analysisdomain; else if(rawdataType==1) rawdatainput=datadomain; else rawdatainput=Box3D(datadomain.x0,datadomain.x1,datadomain.y0,datadomain.y1,analysisdomain.z0,analysisdomain.z1); //printf("%d,%d,%d,%d,%d,%d\n",rawdatainput.x0,rawdatainput.x1,rawdatainput.y0,rawdatainput.y1,rawdatainput.z0,rawdatainput.z1); #pragma omp parallel for for (int i = rawdatainput.x0; i <= rawdatainput.x1; i++){ for (int j = rawdatainput.y0; j <= rawdatainput.y1; j++){ for (int k = rawdatainput.z0; k <= rawdatainput.z1; k++){ first.get(i,j,k)=-rawdata.get(i,j,k); } } } resultdata=first; int sum,t=0; do{ sum=0; t++; #pragma omp parallel for reduction(+:sum) for (int i = datadomain.x0; i <= datadomain.x1; i++){ for (int j = datadomain.y0; j <= datadomain.y1; j++){ for (int k = datadomain.z0; k <= datadomain.z1; k++){ int nsum=0; double small=std::numeric_limits<double>::max(); if(std::abs(first.get(i,j,k)-0.0)<0.0001){ /*for (int ix = -1; ix <= 1; ix++){ for (int iy = -1; iy <= 1; iy++){ for (int iz = -1; iz <= 1; iz++){ if(std::abs(first.get(i+ix,j+iy,k+iz)-0.0)>0.0001) { nsum++; double temp=std::max(0.0,first.get(i+ix,j+iy,k+iz))+filter.get(ix,iy,iz); small=std::min(small,temp); } } } }*/ for(int as=0;as<addscale.n;as++){ int ix=addscale.X[as]; int iy=addscale.Y[as]; int iz=addscale.Z[as]; if(std::abs(first.get(i+ix,j+iy,k+iz)-0.0)>0.0001) { nsum++; double temp=std::max(0.0,first.get(i+ix,j+iy,k+iz))+filter.get(ix,iy,iz); small=std::min(small,temp); } } if(nsum>0) resultdata.get(i,j,k)=small; else resultdata.get(i,j,k)=0; sum++; } } } } first=resultdata; }while(sum!=0); #pragma omp parallel for for (int i = datadomain.x0; i <= datadomain.x1; i++){ for (int j = datadomain.y0; j <= datadomain.y1; j++){ for (int k = datadomain.z0; k <= datadomain.z1; k++){ if(resultdata.get(i,j,k)<0) resultdata.get(i,j,k)=0; } } } return ; } int porousCenter(int part, Filter const& filter, addScale const& addscale,int porousCenterType){ distanceTransform(filter,addscale,porousCenterType); Box3D datadomain=analysisdomain.enlarge(-envelope); //the compare domain size int compareLength=1; int Nx=datadomain.getNx(); int Ny=datadomain.getNy(); int Nz=datadomain.getNz(); int interpolation=Nx/part; ofstream fout; fout.open("pcdata.dat", ios::ate); int allcenter=0; for(int p=0;p<part-1;p++){ int npx0 = datadomain.x0+p*interpolation; int npx1 = datadomain.x0+(p+1)*interpolation-1; std::vector<Dot3D> buffer(interpolation*Ny*Nz,Dot3D(0,0,0)); std::vector<bool> bufferIndex(interpolation*Ny*Nz,false); int numpoint=0; #pragma omp parallel for reduction(+:numpoint) for(int i=0;i<interpolation;i++){ for(int j=0;j<Ny;j++){ for(int k=0;k<Nz;k++){ int index=i*Ny*Nz+j*Nz+k; if(maxpoint(Dot3D(npx0+i,datadomain.y0+j,datadomain.z0+k),datadomain,compareLength)){ buffer[index]=Dot3D(npx0+i,datadomain.y0+j,datadomain.z0+k); bufferIndex[index]=true; numpoint++; } } } } for(int i=0;i<interpolation*Ny*Nz;i++){ if(bufferIndex[i]){ fout<<(buffer[i].x-envelope)<<"\t"<<(buffer[i].y-envelope)<<"\t"<<(buffer[i].z-envelope)<<endl; resultdata.get(buffer[i].x,buffer[i].y,buffer[i].z)=std::max(Nx,std::max(Ny,Nz)); } } allcenter+=numpoint; } { int npx0 = datadomain.x0+(part-1)*interpolation; int npx1 = datadomain.x1; interpolation=npx1-npx0+1; std::vector<Dot3D> buffer(interpolation*Ny*Nz,Dot3D(0,0,0)); std::vector<bool> bufferIndex(interpolation*Ny*Nz,false); int numpoint=0; #pragma omp parallel for reduction(+:numpoint) for(int i=0;i<interpolation;i++){ for(int j=0;j<Ny;j++){ for(int k=0;k<Nz;k++){ int index=i*Ny*Nz+j*Nz+k; if(maxpoint(Dot3D(npx0+i,datadomain.y0+j,datadomain.z0+k),datadomain,compareLength)){ buffer[index]=Dot3D(npx0+i,datadomain.y0+j,datadomain.z0+k); bufferIndex[index]=true; numpoint++; } } } } for(int i=0;i<interpolation*Ny*Nz;i++){ if(bufferIndex[i]){ fout<<(buffer[i].x-envelope)<<"\t"<<(buffer[i].y-envelope)<<"\t"<<(buffer[i].z-envelope)<<endl; resultdata.get(buffer[i].x,buffer[i].y,buffer[i].z)=std::max(Nx,std::max(Ny,Nz)); } } allcenter+=numpoint; } fout.close(); return allcenter; } double shortestPath(int n, bool printall=false){ resultdata.reset(); Box3D datadomain=analysisdomain.enlarge(-envelope); RandomNumber rn; DotList3D begin; ofstream fout; fout.open("spdata.dat", ios::ate); double sum=0; while(begin.getN()<n){ int tempz=datadomain.z0; int tempx=rn.getRandomInt(datadomain.x0,datadomain.x1); int tempy=rn.getRandomInt(datadomain.y0,datadomain.y1); if(abs(rawdata.get(tempx,tempy,tempz)-0.0)<0.0001){ begin.addDot(Dot3D(tempx,tempy,tempz)); double oneans=findShortestPath(Dot3D(tempx,tempy,tempz),printall); fout<<oneans<<endl; sum+=oneans; } } fout.close(); return sum/static_cast<double>(n); } double porousDistribution(int n, int length){ Box3D datadomain=analysisdomain.enlarge(-envelope); RandomNumber rn; std::vector<double> buffer(n,0); DotList3D samples; while(samples.getN()<n){ int tempx=rn.getRandomInt(datadomain.x0,datadomain.x1); int tempy=rn.getRandomInt(datadomain.y0,datadomain.y1); int tempz=rn.getRandomInt(datadomain.z0,datadomain.z1); if(contained(tempx+length-1, tempy+length-1, tempz+length-1, datadomain)){ samples.addDot(Dot3D(tempx,tempy,tempz)); } } double sum=0; #pragma omp parallel for reduction(+:sum) for(int i=0; i<n; i++){ double oneans=calculateVoidage(samples.getDot(i), length); buffer[i]=oneans; sum+=oneans; } ofstream fout; string outputname=createFileName("av", length, 3); outputname+=".dat"; fout.open(outputname, ios::ate); for(int i=0; i<n; i++){ fout<<buffer[i]<<endl; } fout.close(); return sum/n; } double smallWeightPath(Filter const& filter, addScale const& addscale, int sampleN, int bolckNumber=5){ int samplenumber=sampleN; distanceTransform(filter, addscale ,2); Box3D datadomain=analysisdomain.enlarge(-envelope); //the transfer distance data become the rawdata rawdata=resultdata; resultdata.reset(1000000000); //find the max value of distance double maxvalue=0; for (int i = datadomain.x0; i <= datadomain.x1; i++){ for (int j = datadomain.y0; j <= datadomain.y1; j++){ for (int k = datadomain.z0; k <= datadomain.z1; k++){ maxvalue=std::max(maxvalue,rawdata.get(i,j,k)); } } } DotList3D headsample; Box3D headdomain=datadomain.enlarge(-std::min(datadomain.getNx(),datadomain.getNy())/4); RandomNumber rn; while(headsample.getN()<samplenumber){ int _x=rn.getRandomInt(headdomain.x0,headdomain.x1); int _y=rn.getRandomInt(headdomain.y0,headdomain.y1); int _z=datadomain.z0; if(rawdata.get(_x,_y,_z)>2){ headsample.addDot(Dot3D(_x,_y,_z)); } } int interval=datadomain.getNz()/bolckNumber; int zbegin=datadomain.z0,zend=datadomain.z1; double inputvalue=1; double pathweight=0; double threshold=1.5*interval*maxvalue*maxvalue; double ratio=3; vector<std::stringstream> outputstream(samplenumber); vector<DotList3D> pathans(samplenumber); vector<double> pathvalueans(samplenumber,0); for(int i=0;i<samplenumber;i++){ Dot3D head=headsample.getDot(i); pathans[i].addDot(Dot3D(head.x,head.y,head.z)); pathvalueans[i]+=inputvalue; outputstream[i]<<"The head dot:"<<head.x-envelope<<","<<head.y-envelope<<","<<head.z-envelope<<std::endl; outputstream[i]<<"The head dot weight:"<<rawdata.get(head.x,head.y,head.z)<<std::endl; outputstream[i]<<"The biggest pore radius:"<<maxvalue<<std::endl; } omp_set_num_threads(samplenumber); #pragma omp parallel for for(int i=0;i<samplenumber;i++){ //the begin part for(int t=0;t<=bolckNumber-2;t++){ zbegin=datadomain.z0+t*interval; zend=datadomain.z0+(t+1)*interval-1; Box3D part(datadomain.x0,datadomain.x1,datadomain.y0,datadomain.y1,zbegin,zend); ScalarField3D booldata=resultdata; double threadthreshold=threshold; double threadpathweight=pathweight; double threadinputvalue=pathvalueans[i]; int DotNumber=pathans[i].getN(); //printf("%d\n",DotNumber); Dot3D head=pathans[i].getDot(DotNumber-1); if(rawdata.get(head.x,head.y,head.z)<1) { Dot3D oldhead=head; for(int i=-1;i<=1;i++){ for(int j=-1;j<=1;j++){ if(rawdata.get(oldhead.x+i,oldhead.y+j,oldhead.z)>rawdata.get(oldhead.x,oldhead.y,oldhead.z)){ head=Dot3D(oldhead.x+i,oldhead.y+j,oldhead.z); } } } pathans[i].eraseDot(); pathans[i].addDot(head); Dot3D lastone=pathans[i].getDot(DotNumber-2); double oldheadvalue=std::sqrt(std::pow(oldhead.x-lastone.x,2)+std::pow(oldhead.y-lastone.y,2)+std::pow(oldhead.z-lastone.z,2)); double newheadvalue=std::sqrt(std::pow(head.x-lastone.x,2)+std::pow(head.y-lastone.y,2)+std::pow(head.z-lastone.z,2)); pathvalueans[i]=pathvalueans[i]-oldheadvalue+newheadvalue; } //printf("%d,%d,%d\n",head.x,head.y,head.z); DotList3D path=pathans[i]; smallWeightDFS(threadpathweight, threadthreshold, path, pathans[i], threadinputvalue, pathvalueans[i], Dot3D(head.x,head.y,head.z), maxvalue, addscale, filter, head, ratio*maxvalue, booldata, part); //std::cout<<"The path weight:"<<threadthreshold<<std::endl; printf("the thread %d block %d have finished\n",i,t); } //the end part { zbegin=datadomain.z0+(bolckNumber-1)*interval; zend=datadomain.z1; Box3D part(datadomain.x0,datadomain.x1,datadomain.y0,datadomain.y1,zbegin,zend); ScalarField3D booldata=resultdata; double threadthreshold=threshold; double threadpathweight=pathweight; double threadinputvalue=pathvalueans[i]; int DotNumber=pathans[i].getN(); //printf("%d\n",DotNumber); Dot3D head=pathans[i].getDot(DotNumber-1); if(rawdata.get(head.x,head.y,head.z)<1) { Dot3D oldhead=head; for(int i=-1;i<=1;i++){ for(int j=-1;j<=1;j++){ if(rawdata.get(oldhead.x+i,oldhead.y+j,oldhead.z)>rawdata.get(oldhead.x,oldhead.y,oldhead.z)){ head=Dot3D(oldhead.x+i,oldhead.y+j,oldhead.z); } } } pathans[i].eraseDot(); pathans[i].addDot(head); Dot3D lastone=pathans[i].getDot(DotNumber-2); double oldheadvalue=std::sqrt(std::pow(oldhead.x-lastone.x,2)+std::pow(oldhead.y-lastone.y,2)+std::pow(oldhead.z-lastone.z,2)); double newheadvalue=std::sqrt(std::pow(head.x-lastone.x,2)+std::pow(head.y-lastone.y,2)+std::pow(head.z-lastone.z,2)); pathvalueans[i]=pathvalueans[i]-oldheadvalue+newheadvalue; } DotList3D path=pathans[i]; smallWeightDFS(threadpathweight, threadthreshold, path, pathans[i], threadinputvalue, pathvalueans[i], Dot3D(head.x,head.y,head.z), maxvalue, addscale, filter, head, ratio*maxvalue, booldata, part); //std::cout<<"The path weight:"<<threadthreshold<<std::endl; } outputstream[i]<<"The number of path dot:"<<pathans[i].getN()<<std::endl; outputstream[i]<<"The length of path:"<<pathvalueans[i]<<std::endl; } double sum=0; resultdata=rawdata; ofstream pathoutput; for(int i=0;i<samplenumber;i++){ string name=createFileName("path",i,2); name+=".dat"; pathoutput.open(name, ios::ate); for(int j=0;j<pathans[i].getN();j++){ Dot3D temp=pathans[i].getDot(j); resultdata.get(temp.x,temp.y,temp.z)=maxvalue*5; pathoutput<<temp.x-envelope<<"\t"<<temp.y-envelope<<"\t"<<temp.z-envelope<<endl; } pathoutput.close(); sum+=pathvalueans[i]; std::cout<<outputstream[i].str()<<endl; } return sum/samplenumber; } void printdistancevalue(Filter const& filter, addScale const& addscale, DotList3D const& pointlist, string filename, bool printbool=true){ Box3D datadomain=analysisdomain.enlarge(-envelope); distanceTransform(filter,addscale,0); rawdata=resultdata; resultdata.reset(0); vector<double> pointvalue(pointlist.getN(),0); for(int i=0; i<pointlist.getN();i++){ int x=pointlist.getDot(i).x+envelope; int y=pointlist.getDot(i).y+envelope; int z=pointlist.getDot(i).z+envelope; pointvalue[i]=rawdata.get(x,y,z); if(printbool){ printf("print the center(%d,%d,%d)\n",x-envelope,y-envelope,z-envelope); int centeroffset=(int)pointvalue[i]+2; double length=pointvalue[i]; for(int ix=0;ix<centeroffset*2;ix++){ for(int jy=0;jy<centeroffset*2;jy++){ for(int kz=0;kz<centeroffset*2;kz++){ int truex=x+ix-centeroffset; int truey=y+jy-centeroffset; int truez=z+kz-centeroffset; if(contained(truex,truey,truez,datadomain)){ int truelength2=std::pow(ix-centeroffset,2)+std::pow(jy-centeroffset,2)+std::pow(kz-centeroffset,2); if(truelength2<=std::pow(length,2)) resultdata.get(truex,truey,truez)=1; } } } } } } ofstream fout; filename+="value.dat"; fout.open(filename, ios::ate); for(int i=0; i<pointlist.getN();i++){ fout<<pointlist.getDot(i).x<<"\t"<<pointlist.getDot(i).y<<"\t"<<pointlist.getDot(i).z<<"\t"<<pointvalue[i]<<endl; } fout.close(); } void exportAnalysisData(std::string headname, bool palabos=true, bool teceplot=false){ if(teceplot){ TeceplotWriter tw("teceplot"+headname); tw.writeData(resultdata,resultdata.getBoundingBox().enlarge(-envelope)); } if(palabos){ PalabosWriter pw("palabos"+headname); pw.writeData(resultdata,resultdata.getBoundingBox().enlarge(-envelope)); } } private: void getPath(Node* parentNode){ if(!parentNode) return; else{ resultdata.get(parentNode->x,parentNode->y,parentNode->z)=parentNode->step; getPath(parentNode->parent); } } double findShortestPath(Dot3D const& begin, bool printall){ Box3D datadomain=analysisdomain.enlarge(-envelope); Node*** parents=new Node**[analysisdomain.getNx()]; for (int i = 0; i < analysisdomain.getNx(); i++){ parents[i]=new Node*[analysisdomain.getNy()]; for (int j = 0; j < analysisdomain.getNy(); j++){ parents[i][j]=new Node[analysisdomain.getNz()]; } } //the change point addScale as(mode::d26); Filter fl(1,sqrt(2),sqrt(3)); ScalarField3D inq=rawdata; std::queue<Dot3D> q; q.push(begin); inq.get(begin.x,begin.y,begin.z)=1; double length=0; while(!q.empty()){ Dot3D top=q.front(); q.pop(); if(top.z!=analysisdomain.z1-1) { for(int i=0;i<as.n;i++){ int newX=top.x+as.X[i]; int newY=top.y+as.Y[i]; int newZ=top.z+as.Z[i]; if(contained(newX,newY,newZ,datadomain)&&((inq.get(newX,newY,newZ)-0.0)<0.0001)){ q.push(Dot3D(newX,newY,newZ)); parents[newX][newY][newZ].setNode(Dot3D(newX,newY,newZ),parents[top.x][top.y][top.z].step+fl.get(as.X[i],as.Y[i],as.Z[i]),&parents[top.x][top.y][top.z]); inq.get(newX,newY,newZ)=1; } } } else{ length=parents[top.x][top.y][top.z].step; resultdata.get(top.x,top.y,top.z)=length; getPath(parents[top.x][top.y][top.z].parent); if(!printall) break; } } for (int i = 0; i < analysisdomain.getNx(); i++){ for (int j = 0; j < analysisdomain.getNy(); j++){ delete [] parents[i][j]; } } for (int i = 0; i < analysisdomain.getNx(); i++){ delete [] parents[i]; } delete [] parents; return length; } double calculateVoidage(Dot3D const& sample, int length){ int sum=0; int total=pow(length,3); for(int i=sample.x; i<sample.x+length; i++){ for(int j=sample.y; j<sample.y+length; j++){ for(int k=sample.z; k<sample.z+length; k++){ int temp=rawdata.get(i,j,k); sum+=temp; } } } return 1-static_cast<double>(sum)/total; } bool maxpoint(Dot3D const& center,Box3D const& datadomain,int compareLength){ int centerx=center.x; int centery=center.y; int centerz=center.z; double centervalue=resultdata.get(centerx,centery,centerz); for(int i=-compareLength;i<=compareLength;i++){ for(int j=-compareLength;j<=compareLength;j++){ for(int k=-compareLength;k<=compareLength;k++){ if(!contained(centerx+i,centery+j,centerz+k,datadomain)) return false; if(i==0&&j==0&&k==0) continue; if(rawdata.get(centerx+i,centery+j,centerz+k)>0.001) return false; if(resultdata.get(centerx+i,centery+j,centerz+k)>=centervalue) return false; } } } return true; } void smallWeightDFS(double pathweight, double& threshold, DotList3D& path, DotList3D& pathans, double pathvalue, double& pathvalueans, Dot3D cur, double const& maxvalue, addScale const& addscale, Filter const& filter, Dot3D const& head, int domainlength, ScalarField3D & booldata, Box3D domain){ if(cur.z>domain.z1){ if(pathweight<threshold){ threshold=pathweight; pathans=path; pathvalueans=pathvalue; //printf("%f\n",threshold); } return; } /*int radiuslength=std::pow(cur.x-head.x,2)+std::pow(cur.y-head.y,2); if(radiuslength>std::pow(domainlength,2)) return;*/ double rawdistance=rawdata.get(cur.x,cur.y,cur.z); if(rawdistance<1) return; if(std::abs(cur.x-head.x)>domainlength||std::abs(cur.y-head.y)>domainlength) return; if(!contained(cur.x,cur.y,cur.z,domain)) return; if(pathweight>threshold) return; //if(path.getN()>domain.getNz()+20) return; double curvalue=std::pow((maxvalue-rawdistance),2); double newvalue=curvalue+pathweight; //printf("%d,%d,%d,%f\n",cur.x,cur.y,cur.z,newvalue); if(newvalue>=booldata.get(cur.x,cur.y,cur.z)) return; booldata.get(cur.x,cur.y,cur.z)=newvalue; for(int i=0;i<addscale.n;i++){ int addx=addscale.X[i],addy=addscale.Y[i],addz=addscale.Z[i]; int x=cur.x+addx,y=cur.y+addy,z=cur.z+addz; double norm=filter.get(addx,addy,addz); path.addDot(Dot3D(x,y,z)); double newpathvalue=pathvalue+norm; smallWeightDFS(newvalue,threshold, path, pathans, newpathvalue, pathvalueans, Dot3D(x,y,z),maxvalue,addscale,filter,head,domainlength,booldata,domain); path.eraseDot(); } } private: int envelope; Box3D analysisdomain; ScalarField3D rawdata; ScalarField3D resultdata; }; #endif //ANALYSISTOOLS_H
GB_binop__bget_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_08__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_02__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_04__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_int64) // C+=b function (dense accum): GB (_Cdense_accumb__bget_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int64) // C=scalar+B GB (_bind1st__bget_int64) // C=scalar+B' GB (_bind1st_tran__bget_int64) // C=A+scalar GB (_bind2nd__bget_int64) // C=A'+scalar GB (_bind2nd_tran__bget_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = GB_BITGET (aij, bij, int64_t, 64) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITGET (x, y, int64_t, 64) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_INT64 || GxB_NO_BGET_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bget_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bget_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bget_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bget_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITGET (x, bij, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITGET (aij, y, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, int64_t, 64) ; \ } GrB_Info GB (_bind1st_tran__bget_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (aij, y, int64_t, 64) ; \ } GrB_Info GB (_bind2nd_tran__bget_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_uint64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_uint64_fc64 // op(A') function: GB_unop_tran__identity_uint64_fc64 // C type: uint64_t // A type: GxB_FC64_t // cast: uint64_t cij = GB_cast_to_uint64_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint64_fc64 ( uint64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_uint64_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_pack4to16.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_pack4to16_avx512(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_packed, 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; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __m512 _sum = _mm512_setzero_ps(); if (bias_data_ptr) { _sum = _mm512_loadu_ps(bias_data_ptr + p * 16); } const float* kptr = weight_data_packed.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const float* sptr = m.row(i * stride_h) + j * stride_w * 4; for (int k = 0; k < maxk; k++) { const float* slptr = sptr + space_ofs[k] * 4; __m512 _val0 = _mm512_set1_ps(slptr[0]); __m512 _val1 = _mm512_set1_ps(slptr[1]); __m512 _val2 = _mm512_set1_ps(slptr[2]); __m512 _val3 = _mm512_set1_ps(slptr[3]); __m512 _w0 = _mm512_load_ps(kptr); __m512 _w1 = _mm512_load_ps(kptr + 16); __m512 _w2 = _mm512_load_ps(kptr + 32); __m512 _w3 = _mm512_load_ps(kptr + 48); _sum = _mm512_fmadd_ps(_val0, _w0, _sum); _sum = _mm512_fmadd_ps(_val1, _w1, _sum); _sum = _mm512_fmadd_ps(_val2, _w2, _sum); _sum = _mm512_fmadd_ps(_val3, _w3, _sum); kptr += 64; } } _sum = activation_avx512(_sum, activation_type, activation_params); _mm512_store_ps(outptr, _sum); outptr += 16; } } } }
common.c
/* MIT License Copyright (c) 2019 Novak Kaluđerović Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdarg.h> #include <assert.h> #include <math.h> #include <omp.h> #include "gmp.h" #include <time.h> #include <inttypes.h> #include <string.h> #include "common.h" void complain(char *fmt, ...) { va_list arglist; va_start(arglist, fmt); vfprintf(stderr, fmt, arglist); exit(1); } int compare8_seq(const void *a, const void *b) { unsigned char a1 = *((sequence_t *)a); unsigned char b1 = *((sequence_t *)b); if (a1 < b1) return -1; else if (a1 > b1) return 1; else return 0; } int compare16_seq(const void *a, const void *b) { uint16_t a1 = *((sequence_t *)a); uint16_t b1 = *((sequence_t *)b); if (a1 < b1) return -1; else if (a1 > b1) return 1; else return 0; } int compare32_seq(const void *a, const void *b) { uint32_t a1 = *((sequence_t *)a); uint32_t b1 = *((sequence_t *)b); if (a1 < b1) return -1; else if (a1 > b1) return 1; else return 0; } int compareJ_seq(const void *a, const void *b) { sequence_J a0 = *((sequence_J *)a); sequence_J b0 = *((sequence_J *)b); uint64_t a1 = a0.seq; uint64_t b1 = b0.seq; if (a1 < b1) return -1; else if (a1 > b1) return 1; else return 0; } uint64_t get_sequence_from_id(unsigned char *k_symbols, uint32_t i, uint32_t d, uint16_t seq_len, unsigned char negate_result) { assert(seq_len <= 64); uint64_t seq = 0; for (int j = 0; j < seq_len; j++) { uint32_t idx = i + j*d; uint32_t byte_idx = idx >> 3; uint32_t bit_idx = 7 - (idx & 0x7); unsigned char bit = (k_symbols[byte_idx] >> bit_idx) & 1; seq |= ((uint64_t)bit << j); } if (negate_result) seq ^= MASK(seq_len, 0); return seq; } void get_two_sequences_from_id(unsigned char *J_list, uint32_t i, uint32_t d, uint16_t seq_len, unsigned char negate_result, uint64_t *seq, uint64_t *seq_minus, unsigned char symbol_minus1) { assert(seq_len <= 64); for (int j = 0; j < seq_len; j++) { uint64_t idx = i + j*d; uint64_t byte_idx = idx >> 3; uint64_t bit_idx = 7 - (idx & 0x7); unsigned char bit = (J_list[byte_idx] >> bit_idx) & 1; *seq |= ((uint64_t)bit << j); *seq_minus |= ((uint64_t)bit << (seq_len - 1 - j)); } if (negate_result) *seq = ~(*seq); if (symbol_minus1^negate_result) *seq_minus = ~(*seq_minus); } void generate_long_list(unsigned char *out_seq, mpz_t start, mpz_t p, uint64_t seq_len) { //struct timespec end, time_start; //clock_gettime(CLOCK_MONOTONIC_RAW, &time_start); mpz_t tmp; mpz_init_set(tmp, start); for (uint64_t i = 0; i < (seq_len >> 3); i++) { unsigned char res = 0; for (int j = 7; j >= 0; j--) { int sym = (1 - mpz_legendre(tmp, p)) >> 1; res |= ((unsigned char)sym << j); mpz_add_ui(tmp, tmp, 1); } out_seq[i] = res; } mpz_clear(tmp); //clock_gettime(CLOCK_MONOTONIC_RAW, &end); //printf("Computed the J list in %lf seconds\n\n", delta(&end, &time_start)); } // AUXILIARY FUNCTIONS void maketests(unsigned char* k_symbols, uint64_t *tests) { for (uint32_t i = 0; i < NUM_TESTS; i++) tests[i] = get_sequence_from_id(k_symbols, i * TEST_BIT_CHUNKS, 1, TEST_BIT_CHUNKS, 0); } void symbolofmin1(mpz_t p, unsigned char* symb) { if (mpz_fdiv_ui(p, 4) == 1) *symb = 0; else *symb = 1; } void denominators(uint64_t N, uint32_t **list_of_ds, uint32_t *num_ds) { // Make a list of prime d's in the range [(M-1)/(L-1) + 1, (N-1)/(L-1)] uint64_t k_N = (uint64_t)floor((double)(N - 1)/((double)(CONST_L - 1))); int Lbound = CONST_k + 1; int Ubound = k_N; int sieverange = Ubound - Lbound; uint32_t *all_ds_to_be_sieved = malloc( sieverange * sizeof(uint32_t)); for (int j = 0; j < sieverange; j++) all_ds_to_be_sieved[j] = j + Lbound; for(int sieveprime = 2; sieveprime < sqrt(CONST_M); sieveprime++) { int start = ((((-Lbound) % sieveprime) + sieveprime) % sieveprime); while (start < sieverange) { all_ds_to_be_sieved[start] = 0; start += sieveprime; } } uint32_t num_ds_global = 0; for (int j = 0; j < sieverange; j++) if (all_ds_to_be_sieved[j]) num_ds_global++; int i = 0; *list_of_ds = malloc( num_ds_global * sizeof(uint32_t)); for (int j = 0; j < Ubound - Lbound; j++) if (all_ds_to_be_sieved[j]) (*list_of_ds)[i++] = all_ds_to_be_sieved[j]; *num_ds = num_ds_global; free(all_ds_to_be_sieved); } uint64_t get_position(uint64_t i, position_t position) { int64_t appx_pos = floor( (((double)CONST_A)/((double)(1ULL << 32))) * ((int64_t)i) ); int64_t pos = (int64_t)position; while (1) { if(labs(appx_pos - pos) < (1ULL << 31)) return ((uint64_t)pos); pos += (1ULL << 32); } } void get_bitmap_index(uint64_t seq, uint64_t *byte, unsigned char *bit) { uint64_t bmp_pos = seq & MASK(BITMAP_NUM_BITS,0); *byte = bmp_pos >> 3; *bit = bmp_pos & 0x7; } // READ DATA void readprime(char* primepath, mpz_t p) { char pp[200]; FILE *fp = fopen(primepath, "r"); assert((fp != NULL) && "Error opening the prime number file"); assert( fscanf(fp, "%s", pp) != 0) ; fclose(fp); mpz_init_set_str (p, pp, 16); } void readsymbols(char* stringspath, unsigned char* k_symbols) { FILE *fp = fopen(stringspath, "rb"); assert((fp != NULL) && "Error opening the symbols file"); assert( fread(k_symbols, CONST_M_NUM_BYTES, 1, fp) != 0 ); fclose(fp); // Flip the bits because they are computing Legendre as // (1+Leg(x,p))/2 instead of (1-Leg(x,p))/2 // NOTE: remember to remove this when using data generated correctly for (uint64_t i = 0; i < CONST_M_NUM_BYTES; i++) k_symbols[i] = ~k_symbols[i]; } void readpositions(char *positionspath, position_t *positions) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(positionspath, "rb"); assert((fp != NULL) && "Error opening the positions file"); assert( fread(positions, (OCC_LEN + 1) * sizeof(position_t), 1, fp) != 0); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to read positions is %lf seconds\n", delta(&end,&start)); } void readbitmap(char *bitmappath, unsigned char *bitmap) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(bitmappath, "rb"); assert((fp != NULL) && "Error opening the input file with bitmap"); assert(fread(bitmap, BITMAP_NUM_BYTES, 1, fp)); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to read bitmap is %lf seconds\n", delta(&end,&start)); } void readallseqs(char *allseqspath, sequence_t *precomp_seqs) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(allseqspath, "rb"); assert((fp != NULL) && "Error opening the input file with precomputed sequences"); assert(fread(precomp_seqs, CONST_A * sizeof(sequence_t), 1, fp)); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to read precomputed sequences is %lf seconds\n", delta(&end,&start)); } // MAKE DATA void makepositions(unsigned char *k_symbols, position_t *positions, mpz_t p_global) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); if (!positions) printf("positions malloc failed! Probably out of ram\n"); uint32_t curr_d = 1; #pragma omp parallel shared(curr_d) { mpz_t tmp, p; mpz_init(tmp); mpz_init_set(p,p_global); uint32_t d; unsigned char symbol_minus1; symbolofmin1(p, &symbol_minus1); while(1) { #pragma omp atomic capture d = curr_d++; if (d > CONST_k) break; mpz_set_ui(tmp, d); unsigned char d_symbol = (1 - mpz_legendre(tmp, p)) >> 1; for(uint32_t j = 0; j < d; j++) { uint64_t seq = 0; uint64_t seq_minus = 0; for (uint32_t i = j; i < CONST_M-(CONST_L-1)*d; i+=d) { if (i == j) get_two_sequences_from_id(k_symbols, i, d, CONST_L, d_symbol, &seq, &seq_minus, symbol_minus1); else { uint32_t idx = i + (CONST_L - 1)*d; uint32_t byte_idx = idx >> 3; uint32_t bit_idx = 7 - (idx & 0x7); unsigned char bit = (k_symbols[byte_idx] >> bit_idx) & 1; bit ^= d_symbol; seq = (seq >> 1) | ((uint64_t)bit << (CONST_L - 1)); seq = seq & MASK(CONST_L, 0); bit ^= symbol_minus1; seq_minus = (seq_minus << 1) | ((uint64_t)bit); seq_minus = seq_minus & MASK(CONST_L, 0); } uint64_t addr1 = seq & MASK(ADDRESS_NUM_BITS, 0); #pragma omp atomic positions[addr1]++; uint64_t addr2 = seq_minus & MASK(ADDRESS_NUM_BITS, 0); #pragma omp atomic positions[addr2]++; } } } mpz_clear(p); mpz_clear(tmp); } for (uint64_t i = OCC_LEN; i > 0 ; i--) positions[i] = positions[i-1]; positions[0] = 0; for (uint64_t i = 1; i <= OCC_LEN ; i++) positions[i] += positions[i-1]; clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to make list of positions is %lf seconds\n", delta(&end, &start)); } void make_allseqs_and_bitmap(sequence_t *precomp_seqs, unsigned char *k_symbols, unsigned char *bitmap, position_t *positions, mpz_t p_global) { struct timespec start, end; if (!precomp_seqs) printf("Precomp_seqs malloc failed! Probably out of ram\n"); clock_gettime(CLOCK_MONOTONIC_RAW, &start); uint32_t curr_d = 1; #pragma omp parallel shared(curr_d) { mpz_t tmp, p; mpz_init(tmp); mpz_init_set(p,p_global); uint32_t d; position_t pos0, pos1; uint64_t bmp_byte0, addr0, val0, index0; uint64_t bmp_byte1, addr1, val1, index1; unsigned char bmp_bit0; unsigned char bmp_bit1; unsigned char symbol_minus1; symbolofmin1(p, &symbol_minus1); while(1) { #pragma omp atomic capture d = curr_d++; if (d > CONST_k) break; mpz_set_ui(tmp, d); unsigned char d_symbol = (1 - mpz_legendre(tmp, p)) >> 1; for(uint32_t j = 0; j < d; j++) { uint64_t seq = 0; uint64_t seq_minus = 0; for (uint32_t i = j; i < CONST_M-(CONST_L-1)*d; i+=d) { if (i == j) get_two_sequences_from_id(k_symbols, i, d, CONST_L, d_symbol, &seq, &seq_minus, symbol_minus1); else { uint32_t idx = i + (CONST_L - 1)*d; uint32_t byte_idx = idx >> 3; uint32_t bit_idx = 7 - (idx & 0x7); unsigned char bit = (k_symbols[byte_idx] >> bit_idx) & 1; bit ^= d_symbol; seq = (seq >> 1) | ((uint64_t)bit << (CONST_L - 1)); seq = seq & MASK(CONST_L, 0); bit ^= symbol_minus1; seq_minus = (seq_minus << 1) | ((uint64_t)bit); seq_minus = seq_minus & MASK(CONST_L, 0); } //MAKE BITMAP get_bitmap_index(seq, &bmp_byte0, &bmp_bit0); #pragma omp atomic bitmap[bmp_byte0] |= (unsigned char)(1 << bmp_bit0); get_bitmap_index(seq_minus, &bmp_byte1, &bmp_bit1); #pragma omp atomic bitmap[bmp_byte1] |= (unsigned char)(1 << bmp_bit1); // MAKE ALLSEQ addr0 = seq & MASK(ADDRESS_NUM_BITS,0); val0 = seq >> ADDRESS_NUM_BITS; #pragma omp atomic capture pos0 = positions[addr0]++; index0 = get_position(addr0, pos0); #pragma omp atomic write precomp_seqs[index0] = ((sequence_t)val0); addr1 = seq_minus & MASK(ADDRESS_NUM_BITS,0); val1 = seq_minus >> ADDRESS_NUM_BITS; #pragma omp atomic capture pos1 = positions[addr1]++; index1 = get_position(addr1, pos1); #pragma omp atomic write precomp_seqs[index1] = ((sequence_t)val1); } } } mpz_clear(tmp); mpz_clear(p); } clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to make list of sequences and bitmaps is %lf seconds\n", delta(&end, &start)); for(uint64_t i = OCC_LEN; i>0; i--) positions[i] = positions[i-1]; positions[0] = 0; } void sortallseqs(sequence_t *precomp_seqs, position_t *positions, int num_threads) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); uint64_t number_of_threads = (uint64_t) num_threads; uint64_t my_id = omp_get_thread_num(); #pragma omp parallel shared(num_threads) for (uint64_t i = my_id; i < OCC_LEN; i += number_of_threads) { uint64_t pos_iplus1 = get_position(i+1, positions[i+1]); uint64_t pos_i = get_position(i, positions[i]); if ((CONST_L-ADDRESS_NUM_BITS)==32) qsort(&(precomp_seqs[pos_i]), pos_iplus1 - pos_i, sizeof(sequence_t), compare32_seq); else if ((CONST_L-ADDRESS_NUM_BITS)==24) qsort(&(precomp_seqs[pos_i]), pos_iplus1 - pos_i, sizeof(sequence_t), compare32_seq); else if ((CONST_L-ADDRESS_NUM_BITS)==16) qsort(&(precomp_seqs[pos_i]), pos_iplus1 - pos_i, sizeof(sequence_t), compare16_seq); else if ((CONST_L-ADDRESS_NUM_BITS)==8) qsort(&(precomp_seqs[pos_i]), pos_iplus1 - pos_i, sizeof(sequence_t), compare8_seq); } clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to sort list of sequences is %lf seconds\n\n", delta(&end, &start)); printf("If all is correct %" PRIu32" = %" PRIu32" \n\n", (uint32_t)CONST_A, positions[OCC_LEN]); } // WRITE DATA void writepositions(char *positionspath, position_t *positions) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(positionspath, "wb"); assert((fp != NULL) && "Error opening the positions output file"); fwrite((position_t *)positions, (OCC_LEN + 1) * sizeof(position_t), 1, fp); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to write list of positions is %lf seconds\n", delta(&end, &start)); } void writebitmap(char *bitmappath, unsigned char *bitmap) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(bitmappath, "wb"); assert((fp != NULL) && "Error opening the bitmap output file"); fwrite((unsigned char *)bitmap, BITMAP_NUM_BYTES, 1, fp); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to write bitmap is %lf seconds\n", delta(&end, &start)); } void writeallseqs(char* allseqspath, sequence_t *precomp_seqs) { struct timespec start, end; clock_gettime(CLOCK_MONOTONIC_RAW, &start); FILE *fp = fopen(allseqspath, "wb"); assert((fp != NULL) && "Error opening the allseqs output file"); fwrite((sequence_t *)precomp_seqs, CONST_A * sizeof(sequence_t), 1, fp); fclose(fp); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Time taken to write list of sequences is %lf seconds\n", delta(&end, &start)); } // TIMING double delta(struct timespec *end, struct timespec *start) { double delta_time = (double)(end->tv_sec - start->tv_sec) + (double)(end->tv_nsec - start->tv_nsec) / 1E9; return delta_time; } /* static inline uint64_t generate_sequence(mpz_t R, mpz_t p, uint16_t seq_len) { assert(seq_len <= 64); mpz_t tmp; mpz_init_set(tmp, R); uint64_t seq = 0; for (uint16_t j = 0; j < seq_len; j++) { unsigned char bit = (1 - mpz_legendre(tmp, p)) >> 1; seq |= ((uint64_t)bit << j); mpz_add_ui(tmp,tmp,1); } mpz_clear(tmp); return seq; } int is_the_key_correct(mpz_t key, mpz_t p, uint64_t *tests) { mpz_t tmp; mpz_init_set(tmp, key); for (int i = 0; i < NUM_TESTS; i++) { uint64_t seq = generate_sequence(tmp, p, TEST_BIT_CHUNKS); if (seq != tests[i]) return 0; mpz_add_ui(tmp, tmp, TEST_BIT_CHUNKS); } mpz_clear(tmp); return 1; } static inline int search_for_hit(sequence_t *precomp_seqs, uint32_t value, uint64_t bin_search_range, uint64_t *tests, mpz_t J, uint32_t i, uint32_t d, unsigned char is_minus, mpz_t p) { uint64_t addr_id = 0; uint64_t index = 0; if (binary_search(precomp_seqs, value, bin_search_range, &addr_id, &index) == 0) { int move = 0; uint32_t ik, dk; mpz_t k, J_id, d_inv; mpz_init(k); mpz_init_set(J_id, J); mpz_init_set_ui(d_inv, d); mpz_invert(d_inv, d_inv, p); mpz_add_ui(J_id, J, i); mpz_mul(J_id, J_id, d_inv); mpz_mod(J_id, J_id, p); if(is_minus) { mpz_sub_ui(J_id, J_id, CONST_L - 1); mpz_mul_si(J_id, J_id, -1); } get_id_from_address(addr_id, &ik, &dk); mpz_set(k, J_id); mpz_mul_ui(k, k, dk); mpz_sub_ui(k, k, ik); mpz_mod(k, k, p); if (is_the_key_correct(k, p, tests)){ gmp_printf("\nk = %Zd\n", k); return 2; } mpz_clear(J_id); mpz_clear(d_inv); mpz_clear(k); return 1; } return 0; } uint64_t get_address_from_id(uint32_t i, uint32_t d) { uint64_t address = i*CONST_k + (d-1); if (address >= CONST_A) address = 2*CONST_A - 1 - address; return address; } void get_id_from_address(uint64_t address, uint32_t *i, uint32_t *d) { uint32_t ii; uint32_t dd; ii = address / CONST_k; dd = address % CONST_k; if (ii > CONST_M-1-(CONST_L-1)*(dd+1)) { ii = 2*CONST_M - (CONST_L-1)*(CONST_k+1) - 1 - ii; dd = CONST_k - 1 - dd; } dd = dd + 1; *i = ii; *d = dd; } */
omp_workshare4.c
/****************************************************************************** * OpenMP Example - Combined Parallel Loop Work-sharing - C/C++ Version * FILE: omp_workshare4.c * DESCRIPTION: * This is a corrected version of the omp_workshare3.c example. Corrections * include removing all statements between the parallel for construct and * the actual for loop, and introducing logic to preserve the ability to * query a thread's id and print it from inside the for loop. * SOURCE: Blaise Barney 5/99 * LAST REVISED: 03/03/2002 ******************************************************************************/ #include <omp.h> #include <stdio.h> #define N 50 #define CHUNKSIZE 5 main () { int i, chunk, tid; float a[N], b[N], c[N]; char first_time; /* Some initializations */ for (i=0; i < N; i++) a[i] = b[i] = i * 1.0; chunk = CHUNKSIZE; first_time = 'y'; #pragma omp parallel for \ shared(a,b,c,chunk) \ private(i,tid) \ schedule(static,chunk) \ firstprivate(first_time) for (i=0; i < N; i++) { if (first_time == 'y') { tid = omp_get_thread_num(); first_time = 'n'; } c[i] = a[i] + b[i]; printf("tid= %d i= %d c[i]= %f\n", tid, i, c[i]); } return 0; }
krb5_asrep_fmt_plug.c
/* * This software is * Copyright (c) 2015 Michael Kramer <michael.kramer@uni-konstanz.de>, * Copyright (c) 2015 magnum, * Copyright (c) 2016 Fist0urs <eddy.maaalou@gmail.com>, * Copyright (c) 2017 @harmj0y * * 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. * * Changes, * * Slight modifications to krb5tgs format to support AS-REP responses by * @harmj0y * * Documentation, * * http://www.harmj0y.net/blog/activedirectory/roasting-as-reps/ says, * * If you can enumerate any accounts in a Windows domain that don't require * Kerberos preauthentication, you can now easily request a piece of encrypted * information for said accounts and efficiently crack the material offline * (using the format), revealing the user’s password. The reason for Kerberos * preauthentication is to prevent offline password guessing. While the AS-REP * ticket itself is encrypted with the service key (in this case the krbtgt * hash) the AS-REP "encrypted part" is signed with the client key, i.e. the * key of the user we send an AS-REQ for. If preauthentication isn't enabled, * an attacker can send an AS-REQ for any user that doesn't have preauth * required and receive a bit of encrypted material back that can be cracked * offline to reveal the target user’s password. * * While the AS-REP ticket uses type 2 like a TGS-REP ticket (i.e. * kerberoasting) this component of the response is encrypted with the service * key, which in this case is the krbtgt hash and therefore not crackable. * However, the AS-REP encrypted part, which is the section we can essentially * 'downgrade; to RC4-HMAC, is the same algorithm but of message type 8. This * difference caused this format to be born. * * Our krb5tgs format cracks "TGS-REP" messages and this format cracks "AS-REP" * messages. * * Use this format with https://github.com/HarmJ0y/ASREPRoast. * * See http://www.zytrax.com/tech/survival/kerberos.html for the basics on * Kerberos. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_krb5asrep; #elif FMT_REGISTERS_H john_register_one(&fmt_krb5asrep); #else #include <stdio.h> #include <string.h> #include <ctype.h> #ifdef _OPENMP #include <omp.h> #endif #include "misc.h" #include "formats.h" #include "common.h" #include "dyna_salt.h" #include "rc4.h" #include "md4.h" #include "hmacmd5.h" #include "unicode.h" #include "memdbg.h" #ifndef OMP_SCALE #define OMP_SCALE 256 #endif #define FORMAT_LABEL "krb5asrep" #define FORMAT_NAME "Kerberos 5 AS-REP etype 23" #define FORMAT_TAG "$krb5asrep$23$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "MD4 HMAC-MD5 RC4" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1000 #define MIN_PLAINTEXT_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 0 #define BINARY_ALIGN MEM_ALIGN_NONE #define SALT_SIZE sizeof(struct custom_salt *) #define SALT_ALIGN sizeof(struct custom_salt *) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 /* assuming checksum == edata1 formats are: checksum$edata2 $krb5asrep$23$checksum$edata2 */ static struct fmt_tests tests[] = { {"63B386C8C75ECD10F9DF354F42427FBF$BB46B57E89D878455743D1E4C2CD871B5A526A130595463CC021510BA476247B8F9431505155CBC3D7E6120E93623E083A6A508111937607B73F8F524C23E482B648A9C1BE74D7B72B230711BF405ACE9CAF01D5FAC0304509F0DE2A43E0A0834D5F4D5683CA1B8164359B28AC91B35025158A6C9AAD2585D54BAA0A7D886AC154A0B00BE77E86F25439B2298E9EDA7D4BCBE84F505C6C4E6477BB2C9FF860D80E69E99F83A8D1205743CCDD7EC3C3B8FEC481FCC688EC3BD4BA60D93EB30A3259B2E9542CC281B25061D298F672009DCCE9DCAF47BB296480F941AFCDA533F13EA99739F97B92C971A7B4FB970F", "Password123!"}, // http://www.exumbraops.com/layerone2016/party (sample.krb.pcap, packet number 1114, AS-REP) {"$krb5asrep$23$771adbc2397abddef676742924414f2b$2df6eb2d9c71820dc3fa2c098e071d920f0e412f5f12411632c5ee70e004da1be6f003b78661f8e4507e173552a52da751c45887c19bc1661ed334e0ccb4ef33975d4bd68b3d24746f281b4ca4fdf98fca0e50a8e845ad7d834e020c05b1495bc473b0295c6e9b94963cb912d3ff0f2f48c9075b0f52d9a31e5f4cc67c7af1d816b6ccfda0da5ccf35820a4d7d79073fa404726407ac840910357ef210fcf19ed81660106dfc3f4d9166a89d59d274f31619ddd9a1e2712c879a4e9c471965098842b44fae7ca6dd389d5d98b7fd7aca566ca399d072025e81cf0ef5075447687f80100307145fade7a8", "P@$$w0rd123"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static unsigned char (*saved_K1)[16]; static int any_cracked, *cracked; static size_t cracked_size; static int new_keys; static struct custom_salt { dyna_salt dsalt; unsigned char edata1[16]; uint32_t edata2len; unsigned char* edata2; } *cur_salt; static char *split(char *ciphertext, int index, struct fmt_main *self) { static char *ptr, *keeptr; int i; if (strstr(ciphertext, "$SOURCE_HASH$")) return ciphertext; ptr = mem_alloc_tiny(strlen(ciphertext) + FORMAT_TAG_LEN + 1, MEM_ALIGN_NONE); keeptr = ptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) { memcpy(ptr, FORMAT_TAG, FORMAT_TAG_LEN); ptr += FORMAT_TAG_LEN; } for (i = 0; i < strlen(ciphertext) + 1; i++) ptr[i] = tolower(ARCH_INDEX(ciphertext[i])); return keeptr; } static int valid(char *ciphertext, struct fmt_main *self) { char *p; char *ctcopy; char *keeptr; int extra; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) == 0) ctcopy += FORMAT_TAG_LEN; /* assume checksum */ if (((p = strtokm(ctcopy, "$")) == NULL) || strlen(p) != 32) goto err; /* assume edata2 following */ if (((p = strtokm(NULL, "$")) == NULL)) goto err; if (!ishex(p) || (hexlen(p, &extra) < (64 + 16) || extra)) goto err; if ((strtokm(NULL, "$") != NULL)) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_alloc_align(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); saved_K1 = mem_alloc_align(sizeof(*saved_K1) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); any_cracked = 0; cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt; cracked = mem_calloc(cracked_size, 1); } static void done(void) { MEM_FREE(saved_K1); MEM_FREE(cracked); MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { int i; static struct custom_salt cs; char *p; char *ctcopy; char *keeptr; static void *ptr; ctcopy = strdup(ciphertext); keeptr = ctcopy; memset(&cs, 0, sizeof(cs)); cs.edata2 = NULL; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) == 0) ctcopy += FORMAT_TAG_LEN; if (((p = strtokm(ctcopy, "$")) != NULL) && strlen(p) == 32) { /* assume checksum */ for (i = 0; i < 16; i++) { cs.edata1[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } /* skip '$' */ p += strlen(p) + 1; /* retrieve non-constant length of edata2 */ for (i = 0; p[i] != '\0'; i++) ; cs.edata2len = i/2; cs.edata2 = (unsigned char*) mem_calloc_tiny(cs.edata2len + 1, sizeof(char)); for (i = 0; i < cs.edata2len; i++) { /* assume edata2 */ cs.edata2[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } } MEM_FREE(keeptr); /* following is used to fool dyna_salt stuff */ cs.dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt, edata1); cs.dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt, edata1, edata2len, 0); cs.dsalt.salt_alloc_needs_free = 0; ptr = mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); memcpy(ptr, &cs, sizeof(struct custom_salt)); return (void *) &ptr; } static void set_salt(void *salt) { cur_salt = *(struct custom_salt**)salt; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, strlen(key) + 1); new_keys = 1; } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; // const unsigned char data[4] = {2, 0, 0, 0}; // valid for krb5tgs const unsigned char data[4] = {8, 0, 0, 0}; int index; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { unsigned char K3[16]; #ifdef _MSC_VER unsigned char ddata[65536]; #else unsigned char ddata[cur_salt->edata2len + 1]; #endif unsigned char checksum[16]; RC4_KEY rckey; if (new_keys) { MD4_CTX ctx; unsigned char key[16]; UTF16 wkey[PLAINTEXT_LENGTH + 1]; int len; len = enc_to_utf16(wkey, PLAINTEXT_LENGTH, (UTF8*)saved_key[index], strlen(saved_key[index])); if (len <= 0) { saved_key[index][-len] = 0; len = strlen16(wkey); } MD4_Init(&ctx); MD4_Update(&ctx, (char*)wkey, 2 * len); MD4_Final(key, &ctx); hmac_md5(key, data, 4, saved_K1[index]); } hmac_md5(saved_K1[index], cur_salt->edata1, 16, K3); RC4_set_key(&rckey, 16, K3); RC4(&rckey, 32, cur_salt->edata2, ddata); /* check the checksum */ RC4(&rckey, cur_salt->edata2len - 32, cur_salt->edata2 + 32, ddata + 32); hmac_md5(saved_K1[index], ddata, cur_salt->edata2len, checksum); if (!memcmp(checksum, cur_salt->edata1, 16)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } new_keys = 0; return *pcount; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return cracked[index]; } struct fmt_main fmt_krb5asrep = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, MIN_PLAINTEXT_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_UNICODE | FMT_UTF8 | FMT_OMP | FMT_DYNA_SALT, {NULL}, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, fmt_default_binary, get_salt, {NULL}, fmt_default_source, { fmt_default_binary_hash }, fmt_default_dyna_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif
find_kth_element.c
/* Algorithm to find kth smallest number in an array Input : array,k Output : kth smallest number in array array is genearated randomly To Run - ./a.out size k where, size = size of random input data k = kth smallest number Running time for array size = 100000 and k value declining priya@ubuntu:~$ cc -fopenmp indexsort.c priya@ubuntu:~$ time ./a.out 100000 60000 kth element is 47800 real 0m0.045s priya@ubuntu:~$ time ./a.out 100000 40000 kth element is 13385 real 0m0.041s priya@ubuntu:~$ time ./a.out 100000 10000 kth element is 8384 real 0m0.031s Running time declining array size priya@ubuntu:~$ time ./a.out 100000 6000 kth element is 59524 real 0m0.022s user 0m0.020s sys 0m0.000s priya@ubuntu:~$ time ./a.out 10000 6000 kth element is 4533 real 0m0.005s user 0m0.004s sys 0m0.000s priya@ubuntu:~$ time ./a.out 1000 600 kth element is 438 real 0m0.003s user 0m0.004s sys 0m0.000s Note - Repetition of values are taken care of. So, beyond a limit kth smallest value will not be found . In that case user is alerted */ #include<stdio.h> #include<stdlib.h> //#include<omp.h> int main(int argc,char *argv[]) { int *a; char x; int s; int i,k,iter[2]={0,0},ind; if(argc<=1) printf("enter k\n"); k=atoi(argv[2]); s=atoi(argv[1]); a=(int *)malloc(sizeof(int)*s); int ii=0; int tid; int flag=0; #pragma omp parallel num_threads(2) private(ind) shared(a,k,i,flag,ii) { #pragma omp for schedule(static,s/2) for(i=0;i<s;i++) { ind=rand()%s; a[ind]=1; } //tid=omp_get_thread_num(); #pragma omp for for(i=0;i<s;i++) { if(ii==k) { flag=1; printf(" kth element is %d",i); exit(1); } if(a[i]) #pragma omp critical { ii++; } } } if(flag==0) printf("%d th smallest element not available ",k); return 0; }
lastprivate.c
// OpenMP LastPrivate Example // Inclusions #include <omp.h> #include <stdio.h> #include <stdlib.h> // Main int main( int argc, char** argv ) { int thread = 0; // Thread Number int num = 3; // Number int i = 0; // Loop Iterator printf( "Master Thread\n Num Value = %d\n", num ); printf( "Parallel Region\n" ); #pragma omp parallel private( thread ) { #pragma omp master { printf( " Num Value = %d\n", num ); } #pragma omp for lastprivate( num ) for( i = 0; i < 4; i++ ) { thread = omp_get_thread_num( ); num = thread * thread + num; printf( " Thread %d - Value %d\n", thread, num ); } } printf( "Master Thread\n Num Value = %d\n", num ); return 0; } // End lastprivate.c - EWG SDG
bitshuffle.c
/* * Bitshuffle - Filter for improving compression of typed binary data. * * Author: Kiyoshi Masui <kiyo@physics.ubc.ca> * Website: http://www.github.com/kiyo-masui/bitshuffle * Created: 2014 * * See LICENSE file for details about copyright and rights to use. * */ #include "bitshuffle.h" #include "iochain.h" #include "lz4.h" #include <stdio.h> #include <string.h> #if defined(__AVX2__) && defined (__SSE2__) #define USEAVX2 #endif #if defined(__SSE2__) #define USESSE2 #endif // Conditional includes for SSE2 and AVX2. #ifdef USEAVX2 #include <immintrin.h> #elif defined USESSE2 #include <emmintrin.h> #endif // Constants. #define BSHUF_MIN_RECOMMEND_BLOCK 128 #define BSHUF_BLOCKED_MULT 8 // Block sizes must be multiple of this. #define BSHUF_TARGET_BLOCK_SIZE_B 8192 // Use fast decompression instead of safe decompression for LZ4. #define BSHUF_LZ4_DECOMPRESS_FAST // Macros. #define CHECK_MULT_EIGHT(n) if (n % 8) return -80; #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) #define CHECK_ERR(count) if (count < 0) { return count; } #define CHECK_ERR_FREE(count, buf) if (count < 0) { free(buf); return count; } #define CHECK_ERR_FREE_LZ(count, buf) if (count < 0) { \ free(buf); return count - 1000; } /* ---- Functions indicating compile time instruction set. ---- */ int bshuf_using_SSE2(void) { #ifdef USESSE2 return 1; #else return 0; #endif } int bshuf_using_AVX2(void) { #ifdef USEAVX2 return 1; #else return 0; #endif } /* ---- Worker code not requiring special instruction sets. ---- * * The following code does not use any x86 specific vectorized instructions * and should compile on any machine * */ /* Transpose 8x8 bit array packed into a single quadword *x*. * *t* is workspace. */ #define TRANS_BIT_8X8(x, t) { \ t = (x ^ (x >> 7)) & 0x00AA00AA00AA00AALL; \ x = x ^ t ^ (t << 7); \ t = (x ^ (x >> 14)) & 0x0000CCCC0000CCCCLL; \ x = x ^ t ^ (t << 14); \ t = (x ^ (x >> 28)) & 0x00000000F0F0F0F0LL; \ x = x ^ t ^ (t << 28); \ } /* Transpose of an array of arbitrarily typed elements. */ #define TRANS_ELEM_TYPE(in, out, lda, ldb, type_t) { \ type_t* in_type = (type_t*) in; \ type_t* out_type = (type_t*) out; \ for(size_t ii = 0; ii + 7 < lda; ii += 8) { \ for(size_t jj = 0; jj < ldb; jj++) { \ for(size_t kk = 0; kk < 8; kk++) { \ out_type[jj*lda + ii + kk] = \ in_type[ii*ldb + kk * ldb + jj]; \ } \ } \ } \ for(size_t ii = lda - lda % 8; ii < lda; ii ++) { \ for(size_t jj = 0; jj < ldb; jj++) { \ out_type[jj*lda + ii] = in_type[ii*ldb + jj]; \ } \ } \ } /* Memory copy with bshuf call signature. For testing and profiling. */ int64_t bshuf_copy(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; memcpy(out_b, in_b, size * elem_size); return size * elem_size; } /* Transpose bytes within elements, starting partway through input. */ int64_t bshuf_trans_byte_elem_remainder(void* in, void* out, const size_t size, const size_t elem_size, const size_t start) { char* in_b = (char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(start); if (size > start) { // ii loop separated into 2 loops so the compiler can unroll // the inner one. for (size_t ii = start; ii + 7 < size; ii += 8) { for (size_t jj = 0; jj < elem_size; jj++) { for (size_t kk = 0; kk < 8; kk++) { out_b[jj * size + ii + kk] = in_b[ii * elem_size + kk * elem_size + jj]; } } } for (size_t ii = size - size % 8; ii < size; ii ++) { for (size_t jj = 0; jj < elem_size; jj++) { out_b[jj * size + ii] = in_b[ii * elem_size + jj]; } } } return size * elem_size; } /* Transpose bytes within elements. */ int64_t bshuf_trans_byte_elem_scal(void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_byte_elem_remainder(in, out, size, elem_size, 0); } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_remainder(void* in, void* out, const size_t size, const size_t elem_size, const size_t start_byte) { uint64_t* in_b = in; uint8_t* out_b = out; uint64_t x, t; size_t nbyte = elem_size * size; size_t nbyte_bitrow = nbyte / 8; CHECK_MULT_EIGHT(nbyte); CHECK_MULT_EIGHT(start_byte); for (size_t ii = start_byte / 8; ii < nbyte_bitrow; ii ++) { x = in_b[ii]; TRANS_BIT_8X8(x, t); for (int kk = 0; kk < 8; kk ++) { out_b[kk * nbyte_bitrow + ii] = x; x = x >> 8; } } return size * elem_size; } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_scal(void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_bit_byte_remainder(in, out, size, elem_size, 0); } /* General transpose of an array, optimized for large element sizes. */ int64_t bshuf_trans_elem(void* in, void* out, const size_t lda, const size_t ldb, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; for(size_t ii = 0; ii < lda; ii++) { for(size_t jj = 0; jj < ldb; jj++) { memcpy(&out_b[(jj*lda + ii) * elem_size], &in_b[(ii*ldb + jj) * elem_size], elem_size); } } return lda * ldb * elem_size; } /* Transpose rows of shuffled bits (size / 8 bytes) within groups of 8. */ int64_t bshuf_trans_bitrow_eight(void* in, void* out, const size_t size, const size_t elem_size) { size_t nbyte_bitrow = size / 8; CHECK_MULT_EIGHT(size); return bshuf_trans_elem(in, out, 8, elem_size, nbyte_bitrow); } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_scal(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_scal(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_scal(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; size_t nbyte_row = size / 8; CHECK_MULT_EIGHT(size); for (size_t jj = 0; jj < elem_size; jj++) { for (size_t ii = 0; ii < nbyte_row; ii++) { for (size_t kk = 0; kk < 8; kk++) { out_b[ii * 8 * elem_size + jj * 8 + kk] = \ in_b[(jj * 8 + kk) * nbyte_row + ii]; } } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_scal(void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); char* in_b = (char*) in; char* out_b = (char*) out; size_t nbyte = elem_size * size; uint64_t x, t; for (size_t jj = 0; jj < 8 * elem_size; jj += 8) { for (size_t ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { x = *((uint64_t*) &in_b[ii + jj]); TRANS_BIT_8X8(x, t); for (size_t kk = 0; kk < 8; kk++) { *((uint8_t*) &out_b[ii + jj / 8 + kk * elem_size]) = x; x = x >> 8; } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_scal(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_scal(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_scal(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* ---- Worker code that uses SSE2 ---- * * The following code makes use of the SSE2 instruction set and specialized * 16 byte registers. The SSE2 instructions are present on modern x86 * processors. The first Intel processor microarchitecture supporting SSE2 was * Pentium 4 (2000). * */ #ifdef USESSE2 /* Transpose bytes within elements for 16 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_16(void* in, void* out, const size_t size) { char* in_b = (char*) in; char* out_b = (char*) out; __m128i a0, b0, a1, b1; for (size_t ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 1*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); } return bshuf_trans_byte_elem_remainder(in, out, size, 2, size - size % 16); } /* Transpose bytes within elements for 32 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_32(void* in, void* out, const size_t size) { char* in_b = (char*) in; char* out_b = (char*) out; __m128i a0, b0, c0, d0, a1, b1, c1, d1; for (size_t ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 3*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi64(a1, c1); b0 = _mm_unpackhi_epi64(a1, c1); c0 = _mm_unpacklo_epi64(b1, d1); d0 = _mm_unpackhi_epi64(b1, d1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); } return bshuf_trans_byte_elem_remainder(in, out, size, 4, size - size % 16); } /* Transpose bytes within elements for 64 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_64(void* in, void* out, const size_t size) { char* in_b = (char*) in; char* out_b = (char*) out; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; for (size_t ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 3*16]); e0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 4*16]); f0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 5*16]); g0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 6*16]); h0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 7*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); e1 = _mm_unpacklo_epi8(e0, f0); f1 = _mm_unpackhi_epi8(e0, f0); g1 = _mm_unpacklo_epi8(g0, h0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); e0 = _mm_unpacklo_epi8(e1, f1); f0 = _mm_unpackhi_epi8(e1, f1); g0 = _mm_unpacklo_epi8(g1, h1); h0 = _mm_unpackhi_epi8(g1, h1); a1 = _mm_unpacklo_epi32(a0, c0); b1 = _mm_unpackhi_epi32(a0, c0); c1 = _mm_unpacklo_epi32(b0, d0); d1 = _mm_unpackhi_epi32(b0, d0); e1 = _mm_unpacklo_epi32(e0, g0); f1 = _mm_unpackhi_epi32(e0, g0); g1 = _mm_unpacklo_epi32(f0, h0); h1 = _mm_unpackhi_epi32(f0, h0); a0 = _mm_unpacklo_epi64(a1, e1); b0 = _mm_unpackhi_epi64(a1, e1); c0 = _mm_unpacklo_epi64(b1, f1); d0 = _mm_unpackhi_epi64(b1, f1); e0 = _mm_unpacklo_epi64(c1, g1); f0 = _mm_unpackhi_epi64(c1, g1); g0 = _mm_unpacklo_epi64(d1, h1); h0 = _mm_unpackhi_epi64(d1, h1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); _mm_storeu_si128((__m128i *) &out_b[4*size + ii], e0); _mm_storeu_si128((__m128i *) &out_b[5*size + ii], f0); _mm_storeu_si128((__m128i *) &out_b[6*size + ii], g0); _mm_storeu_si128((__m128i *) &out_b[7*size + ii], h0); } return bshuf_trans_byte_elem_remainder(in, out, size, 8, size - size % 16); } /* Transpose bytes within elements using best SSE algorithm available. */ int64_t bshuf_trans_byte_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; // Trivial cases: power of 2 bytes. switch (elem_size) { case 1: count = bshuf_copy(in, out, size, elem_size); return count; case 2: count = bshuf_trans_byte_elem_SSE_16(in, out, size); return count; case 4: count = bshuf_trans_byte_elem_SSE_32(in, out, size); return count; case 8: count = bshuf_trans_byte_elem_SSE_64(in, out, size); return count; } // Worst case: odd number of bytes. Turns out that this is faster for // (odd * 2) byte elements as well (hence % 4). if (elem_size % 4) { count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); return count; } // Multiple of power of 2: transpose hierarchically. { size_t nchunk_elem; void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; if ((elem_size % 8) == 0) { nchunk_elem = elem_size / 8; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t); count = bshuf_trans_byte_elem_SSE_64(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size); } else if ((elem_size % 4) == 0) { nchunk_elem = elem_size / 4; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t); count = bshuf_trans_byte_elem_SSE_32(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size); } else { // Not used since scalar algorithm is faster. nchunk_elem = elem_size / 2; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t); count = bshuf_trans_byte_elem_SSE_16(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size); } free(tmp_buf); return count; } } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_SSE(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; uint16_t* out_ui16; int64_t count; size_t nbyte = elem_size * size; CHECK_MULT_EIGHT(nbyte); __m128i xmm; int32_t bt; for (size_t ii = 0; ii + 15 < nbyte; ii += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii]); for (size_t kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_ui16 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 16); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_SSE(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_SSE(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; __m128 *as, *bs, *cs, *ds, *es, *fs, *gs, *hs; for (size_t ii = 0; ii + 7 < nrows; ii += 8) { for (size_t jj = 0; jj + 15 < nbyte_row; jj += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 0)*nbyte_row + jj]); b0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 1)*nbyte_row + jj]); c0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 2)*nbyte_row + jj]); d0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 3)*nbyte_row + jj]); e0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 4)*nbyte_row + jj]); f0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 5)*nbyte_row + jj]); g0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 6)*nbyte_row + jj]); h0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 7)*nbyte_row + jj]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpacklo_epi8(c0, d0); c1 = _mm_unpacklo_epi8(e0, f0); d1 = _mm_unpacklo_epi8(g0, h0); e1 = _mm_unpackhi_epi8(a0, b0); f1 = _mm_unpackhi_epi8(c0, d0); g1 = _mm_unpackhi_epi8(e0, f0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi16(a1, b1); b0 = _mm_unpacklo_epi16(c1, d1); c0 = _mm_unpackhi_epi16(a1, b1); d0 = _mm_unpackhi_epi16(c1, d1); e0 = _mm_unpacklo_epi16(e1, f1); f0 = _mm_unpacklo_epi16(g1, h1); g0 = _mm_unpackhi_epi16(e1, f1); h0 = _mm_unpackhi_epi16(g1, h1); a1 = _mm_unpacklo_epi32(a0, b0); b1 = _mm_unpackhi_epi32(a0, b0); c1 = _mm_unpacklo_epi32(c0, d0); d1 = _mm_unpackhi_epi32(c0, d0); e1 = _mm_unpacklo_epi32(e0, f0); f1 = _mm_unpackhi_epi32(e0, f0); g1 = _mm_unpacklo_epi32(g0, h0); h1 = _mm_unpackhi_epi32(g0, h0); // We don't have a storeh instruction for integers, so interpret // as a float. Have a storel (_mm_storel_epi64). as = (__m128 *) &a1; bs = (__m128 *) &b1; cs = (__m128 *) &c1; ds = (__m128 *) &d1; es = (__m128 *) &e1; fs = (__m128 *) &f1; gs = (__m128 *) &g1; hs = (__m128 *) &h1; _mm_storel_pi((__m64 *) &out_b[(jj + 0) * nrows + ii], *as); _mm_storel_pi((__m64 *) &out_b[(jj + 2) * nrows + ii], *bs); _mm_storel_pi((__m64 *) &out_b[(jj + 4) * nrows + ii], *cs); _mm_storel_pi((__m64 *) &out_b[(jj + 6) * nrows + ii], *ds); _mm_storel_pi((__m64 *) &out_b[(jj + 8) * nrows + ii], *es); _mm_storel_pi((__m64 *) &out_b[(jj + 10) * nrows + ii], *fs); _mm_storel_pi((__m64 *) &out_b[(jj + 12) * nrows + ii], *gs); _mm_storel_pi((__m64 *) &out_b[(jj + 14) * nrows + ii], *hs); _mm_storeh_pi((__m64 *) &out_b[(jj + 1) * nrows + ii], *as); _mm_storeh_pi((__m64 *) &out_b[(jj + 3) * nrows + ii], *bs); _mm_storeh_pi((__m64 *) &out_b[(jj + 5) * nrows + ii], *cs); _mm_storeh_pi((__m64 *) &out_b[(jj + 7) * nrows + ii], *ds); _mm_storeh_pi((__m64 *) &out_b[(jj + 9) * nrows + ii], *es); _mm_storeh_pi((__m64 *) &out_b[(jj + 11) * nrows + ii], *fs); _mm_storeh_pi((__m64 *) &out_b[(jj + 13) * nrows + ii], *gs); _mm_storeh_pi((__m64 *) &out_b[(jj + 15) * nrows + ii], *hs); } for (size_t jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj]; out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj]; out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj]; out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj]; out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj]; out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj]; out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj]; out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. char* in_b = (char*) in; uint16_t* out_ui16 = (uint16_t*) out; size_t nbyte = elem_size * size; __m128i xmm; int32_t bt; if (elem_size % 2) { bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size); } else { for (size_t ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { for (size_t jj = 0; jj + 15 < 8 * elem_size; jj += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii + jj]); for (size_t kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); out_ui16[ind / 2] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_SSE(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_SSE(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USESSE2 int64_t bshuf_untrans_bit_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_bitrow_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_byte_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_64(void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_32(void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_16(void* in, void* out, const size_t size) { return -11; } int64_t bshuf_shuffle_bit_eightelem_SSE(void* in, void* out, const size_t size, const size_t elem_size) { return -11; } #endif // #ifdef USESSE2 /* ---- Code that requires AVX2. Intel Haswell (2013) and later. ---- */ /* ---- Worker code that uses AVX2 ---- * * The following code makes use of the AVX2 instruction set and specialized * 32 byte registers. The AVX2 instructions are present on newer x86 * processors. The first Intel processor microarchitecture supporting AVX2 was * Haswell (2013). * */ #ifdef USEAVX2 /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_AVX(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; int32_t* out_i32; size_t nbyte = elem_size * size; int64_t count; __m256i ymm; int32_t bt; for (size_t ii = 0; ii + 31 < nbyte; ii += 32) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii]); for (size_t kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); out_i32 = (int32_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_i32 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 32); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_AVX(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_AVX(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; if (elem_size % 4) return bshuf_trans_byte_bitrow_SSE(in, out, size, elem_size); __m256i ymm_0[8]; __m256i ymm_1[8]; __m256i ymm_storeage[8][4]; for (size_t jj = 0; jj + 31 < nbyte_row; jj += 32) { for (size_t ii = 0; ii + 3 < elem_size; ii += 4) { for (size_t hh = 0; hh < 4; hh ++) { for (size_t kk = 0; kk < 8; kk ++){ ymm_0[kk] = _mm256_loadu_si256((__m256i *) &in_b[ (ii * 8 + hh * 8 + kk) * nbyte_row + jj]); } for (size_t kk = 0; kk < 4; kk ++){ ymm_1[kk] = _mm256_unpacklo_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk + 4] = _mm256_unpackhi_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (size_t kk = 0; kk < 2; kk ++){ for (size_t mm = 0; mm < 2; mm ++){ ymm_0[kk * 4 + mm] = _mm256_unpacklo_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); ymm_0[kk * 4 + mm + 2] = _mm256_unpackhi_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); } } for (size_t kk = 0; kk < 4; kk ++){ ymm_1[kk * 2] = _mm256_unpacklo_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk * 2 + 1] = _mm256_unpackhi_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (size_t kk = 0; kk < 8; kk ++){ ymm_storeage[kk][hh] = ymm_1[kk]; } } for (size_t mm = 0; mm < 8; mm ++) { for (size_t kk = 0; kk < 4; kk ++){ ymm_0[kk] = ymm_storeage[mm][kk]; } ymm_1[0] = _mm256_unpacklo_epi64(ymm_0[0], ymm_0[1]); ymm_1[1] = _mm256_unpacklo_epi64(ymm_0[2], ymm_0[3]); ymm_1[2] = _mm256_unpackhi_epi64(ymm_0[0], ymm_0[1]); ymm_1[3] = _mm256_unpackhi_epi64(ymm_0[2], ymm_0[3]); ymm_0[0] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 32); ymm_0[1] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 32); ymm_0[2] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 49); ymm_0[3] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 49); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16) * nrows + ii * 8], ymm_0[0]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16 + 1) * nrows + ii * 8], ymm_0[1]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16) * nrows + ii * 8], ymm_0[2]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16 + 1) * nrows + ii * 8], ymm_0[3]); } } } for (size_t ii = 0; ii < nrows; ii ++ ) { for (size_t jj = nbyte_row - nbyte_row % 32; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii] = in_b[ii * nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. char* in_b = (char*) in; char* out_b = (char*) out; size_t nbyte = elem_size * size; __m256i ymm; int32_t bt; if (elem_size % 4) { return bshuf_shuffle_bit_eightelem_SSE(in, out, size, elem_size); } else { for (size_t jj = 0; jj + 31 < 8 * elem_size; jj += 32) { for (size_t ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii + jj]); for (size_t kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); * (int32_t *) &out_b[ind] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_AVX(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_AVX(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USEAVX2 int64_t bshuf_trans_bit_byte_AVX(void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_bit_elem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_byte_bitrow_AVX(void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_shuffle_bit_eightelem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_untrans_bit_elem_AVX(void* in, void* out, const size_t size, const size_t elem_size) { return -12; } #endif // #ifdef USEAVX2 /* ---- Drivers selecting best instruction set at compile time. ---- */ int64_t bshuf_trans_bit_elem(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_trans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_trans_bit_elem_SSE(in, out, size, elem_size); #else count = bshuf_trans_bit_elem_scal(in, out, size, elem_size); #endif return count; } int64_t bshuf_untrans_bit_elem(void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_untrans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_untrans_bit_elem_SSE(in, out, size, elem_size); #else count = bshuf_untrans_bit_elem_scal(in, out, size, elem_size); #endif return count; } /* ---- Wrappers for implementing blocking ---- */ /* Function definition for worker functions that process a single block. */ typedef int64_t (*bshufBlockFunDef)(ioc_chain* C_ptr, const size_t size, const size_t elem_size); /* Wrap a function for processing a single block to process an entire buffer in * parallel. */ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { ioc_chain C; ioc_init(&C, in, out); int64_t err = 0, count, cum_count = 0; size_t last_block_size; if (block_size == 0) { block_size = bshuf_default_block_size(elem_size); } if (block_size < 0 || block_size % BSHUF_BLOCKED_MULT) return -81; #pragma omp parallel for private(count) reduction(+ : cum_count) for (size_t ii = 0; ii < size / block_size; ii ++) { count = fun(&C, block_size, elem_size); if (count < 0) err = count; cum_count += count; } last_block_size = size % block_size; last_block_size = last_block_size - last_block_size % BSHUF_BLOCKED_MULT; if (last_block_size) { count = fun(&C, last_block_size, elem_size); if (count < 0) err = count; cum_count += count; } if (err < 0) return err; size_t leftover_bytes = size % BSHUF_BLOCKED_MULT * elem_size; size_t this_iter; char *last_in = (char *) ioc_get_in(&C, &this_iter); ioc_set_next_in(&C, &this_iter, (void *) (last_in + leftover_bytes)); char *last_out = (char *) ioc_get_out(&C, &this_iter); ioc_set_next_out(&C, &this_iter, (void *) (last_out + leftover_bytes)); memcpy(last_out, last_in, leftover_bytes); ioc_destroy(&C); return cum_count + leftover_bytes; } /* Bitshuffle a single block. */ int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, const size_t size, const size_t elem_size) { size_t this_iter; void *in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); void *out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); int64_t count = bshuf_trans_bit_elem(in, out, size, elem_size); return count; } /* Bitunshuffle a single block. */ int64_t bshuf_bitunshuffle_block(ioc_chain* C_ptr, const size_t size, const size_t elem_size) { size_t this_iter; void *in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); void *out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); int64_t count = bshuf_untrans_bit_elem(in, out, size, elem_size); return count; } /* Write a 64 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint64_BE(void* buf, uint64_t num) { uint8_t* b = buf; uint64_t pow28 = 1 << 8; for (int ii = 7; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 64 bit unsigned integer from a buffer big endian order. */ uint64_t bshuf_read_uint64_BE(void* buf) { uint8_t* b = buf; uint64_t num = 0, pow28 = 1 << 8, cp = 1; for (int ii = 7; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* Write a 32 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint32_BE(void* buf, uint32_t num) { uint8_t* b = buf; uint32_t pow28 = 1 << 8; for (int ii = 3; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 32 bit unsigned integer from a buffer big endian order. */ uint32_t bshuf_read_uint32_BE(void* buf) { uint8_t* b = buf; uint32_t num = 0, pow28 = 1 << 8, cp = 1; for (int ii = 3; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* Bitshuffle and compress a single block. */ int64_t bshuf_compress_lz4_block(ioc_chain *C_ptr, const size_t size, const size_t elem_size) { int64_t nbytes, count; void* tmp_buf_bshuf = malloc(size * elem_size); if (tmp_buf_bshuf == NULL) return -1; void* tmp_buf_lz4 = malloc(LZ4_compressBound(size * elem_size)); if (tmp_buf_lz4 == NULL){ free(tmp_buf_bshuf); return -1; } size_t this_iter; void *in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); count = bshuf_trans_bit_elem(in, tmp_buf_bshuf, size, elem_size); if (count < 0) { free(tmp_buf_lz4); free(tmp_buf_bshuf); return count; } nbytes = LZ4_compress(tmp_buf_bshuf, tmp_buf_lz4, size * elem_size); free(tmp_buf_bshuf); CHECK_ERR_FREE_LZ(nbytes, tmp_buf_lz4); void *out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + nbytes + 4)); bshuf_write_uint32_BE(out, nbytes); memcpy((char *) out + 4, tmp_buf_lz4, nbytes); free(tmp_buf_lz4); return nbytes + 4; } /* Decompress and bitunshuffle a single block. */ int64_t bshuf_decompress_lz4_block(ioc_chain *C_ptr, const size_t size, const size_t elem_size) { int64_t nbytes, count; size_t this_iter; void *in = ioc_get_in(C_ptr, &this_iter); int32_t nbytes_from_header = bshuf_read_uint32_BE(in); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + nbytes_from_header + 4)); void *out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; #ifdef BSHUF_LZ4_DECOMPRESS_FAST nbytes = LZ4_decompress_fast((char*) in + 4, tmp_buf, size * elem_size); CHECK_ERR_FREE_LZ(nbytes, tmp_buf); if (nbytes != nbytes_from_header) { free(tmp_buf); return -91; } #else nbytes = LZ4_decompress_safe((char*) in + 4, tmp_buf, nbytes_from_header, size * elem_size); CHECK_ERR_FREE_LZ(nbytes, tmp_buf); if (nbytes != size * elem_size) { free(tmp_buf); return -91; } nbytes = nbytes_from_header; #endif count = bshuf_untrans_bit_elem(tmp_buf, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); nbytes += 4; free(tmp_buf); return nbytes; } /* ---- Public functions ---- * * See header file for description and usage. * */ size_t bshuf_default_block_size(const size_t elem_size) { // This function needs to be absolutely stable between versions. // Otherwise encoded data will not be decodable. size_t block_size = BSHUF_TARGET_BLOCK_SIZE_B / elem_size; // Ensure it is a required multiple. block_size = (block_size / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT; return MAX(block_size, BSHUF_MIN_RECOMMEND_BLOCK); } size_t bshuf_compress_lz4_bound(const size_t size, const size_t elem_size, size_t block_size) { size_t bound, leftover; if (block_size == 0) { block_size = bshuf_default_block_size(elem_size); } if (block_size < 0 || block_size % BSHUF_BLOCKED_MULT) return -81; // Note that each block gets a 4 byte header. // Size of full blocks. bound = (LZ4_compressBound(block_size * elem_size) + 4) * (size / block_size); // Size of partial blocks, if any. leftover = ((size % block_size) / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT; if (leftover) bound += LZ4_compressBound(leftover * elem_size) + 4; // Size of uncompressed data not fitting into any blocks. bound += (size % BSHUF_BLOCKED_MULT) * elem_size; return bound; } int64_t bshuf_bitshuffle(void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitshuffle_block, in, out, size, elem_size, block_size); } int64_t bshuf_bitunshuffle(void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitunshuffle_block, in, out, size, elem_size, block_size); } int64_t bshuf_compress_lz4(void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_compress_lz4_block, in, out, size, elem_size, block_size); } int64_t bshuf_decompress_lz4(void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_decompress_lz4_block, in, out, size, elem_size, block_size); } #undef TRANS_BIT_8X8 #undef TRANS_ELEM_TYPE #undef MIN #undef MAX #undef CHECK_MULT_EIGHT #undef CHECK_ERR #undef CHECK_ERR_FREE #undef CHECK_ERR_FREE_LZ #undef USESSE2 #undef USEAVX2
DRB093-doall2-collapse-orig-no.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https:github.comLLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Two-dimensional array computation: collapse(2) is used to associate two loops with omp for. The corresponding loop iteration variables are private. */ int a[100][100]; int main() { int i, j; int _ret_val_0; #pragma cetus private(i, j) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i, j) for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#0#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<100; j ++ ) { a[i][j]=i; } } #pragma cetus private(i, j) #pragma loop name main#1 #pragma cetus parallel #pragma omp parallel for private(i, j) for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#1#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<100; j ++ ) { a[i][j]=(a[i][j]+1); } } #pragma cetus private(i, j) #pragma loop name main#2 for (i=0; i<100; i ++ ) { #pragma cetus private(j) #pragma loop name main#2#0 for (j=0; j<100; j ++ ) { printf("%d\n", a[i][j]); } } _ret_val_0=0; return _ret_val_0; }
data.c
#include "data.h" #include "utils.h" #include "image.h" #include "cuda.h" #include <stdio.h> #include <stdlib.h> #include <string.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; list *get_paths(char *filename) { char *path; FILE *file = faasmndp_fopen(filename, "r"); if(!file) file_error(filename); list *lines = make_list(); while((path=fgetl(file))){ list_insert(lines, path); } fclose(file); return lines; } /* char **get_random_paths_indexes(char **paths, int n, int m, int *indexes) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = rand()%m; indexes[i] = index; random_paths[i] = paths[index]; if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } */ char **get_random_paths(char **paths, int n, int m) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = rand()%m; random_paths[i] = paths[index]; //if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } char **find_replace_paths(char **paths, int n, char *find, char *replace) { char **replace_paths = calloc(n, sizeof(char*)); int i; for(i = 0; i < n; ++i){ char replaced[4096]; find_replace(paths[i], find, replace, replaced); replace_paths[i] = copy_string(replaced); } return replace_paths; } matrix load_image_paths_gray(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image(paths[i], w, h, 3); image gray = grayscale_image(im); free_image(im); im = gray; X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_paths(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], w, h); X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_augment_paths(char **paths, int n, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop; if(center){ crop = center_crop_image(im, size, size); } else { crop = random_augment_image(im, angle, aspect, min, max, size, size); } int flip = rand()%2; if (flip) flip_image(crop); random_distort_image(crop, hue, saturation, exposure); /* show_image(im, "orig"); show_image(crop, "crop"); cvWaitKey(0); */ //grayscale_image_3c(crop); free_image(im); X.vals[i] = crop.data; X.cols = crop.h*crop.w*crop.c; } return X; } box_label *read_boxes(char *filename, int *n) { FILE *file = faasmndp_fopen(filename, "r"); if(!file) file_error(filename); float x, y, h, w; int id; int count = 0; int size = 64; box_label *boxes = calloc(size, sizeof(box_label)); while(fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){ if(count == size) { size = size * 2; boxes = realloc(boxes, size*sizeof(box_label)); } boxes[count].id = id; boxes[count].x = x; boxes[count].y = y; boxes[count].h = h; boxes[count].w = w; boxes[count].left = x - w/2; boxes[count].right = x + w/2; boxes[count].top = y - h/2; boxes[count].bottom = y + h/2; ++count; } fclose(file); *n = count; return boxes; } void randomize_boxes(box_label *b, int n) { int i; for(i = 0; i < n; ++i){ box_label swap = b[i]; int index = rand()%n; b[i] = b[index]; b[index] = swap; } } void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx, float sy, int flip) { int i; for(i = 0; i < n; ++i){ if(boxes[i].x == 0 && boxes[i].y == 0) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } boxes[i].left = boxes[i].left * sx - dx; boxes[i].right = boxes[i].right * sx - dx; boxes[i].top = boxes[i].top * sy - dy; boxes[i].bottom = boxes[i].bottom* sy - dy; if(flip){ float swap = boxes[i].left; boxes[i].left = 1. - boxes[i].right; boxes[i].right = 1. - swap; } boxes[i].left = constrain(0, 1, boxes[i].left); boxes[i].right = constrain(0, 1, boxes[i].right); boxes[i].top = constrain(0, 1, boxes[i].top); boxes[i].bottom = constrain(0, 1, boxes[i].bottom); boxes[i].x = (boxes[i].left+boxes[i].right)/2; boxes[i].y = (boxes[i].top+boxes[i].bottom)/2; boxes[i].w = (boxes[i].right - boxes[i].left); boxes[i].h = (boxes[i].bottom - boxes[i].top); boxes[i].w = constrain(0, 1, boxes[i].w); boxes[i].h = constrain(0, 1, boxes[i].h); } } void fill_truth_swag(char *path, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count && i < 90; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .0 || h < .0) continue; int index = (4+classes) * i; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; if (id < classes) truth[index+id] = 1; } free(boxes); } void fill_truth_region(char *path, float *truth, int classes, int num_boxes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .005 || h < .005) continue; int col = (int)(x*num_boxes); int row = (int)(y*num_boxes); x = x*num_boxes - col; y = y*num_boxes - row; int index = (col+row*num_boxes)*(5+classes); if (truth[index]) continue; truth[index++] = 1; if (id < classes) truth[index+id] = 1; index += classes; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; } free(boxes); } void load_rle(image im, int *rle, int n) { int count = 0; int curr = 0; int i,j; for(i = 0; i < n; ++i){ for(j = 0; j < rle[i]; ++j){ im.data[count++] = curr; } curr = 1 - curr; } for(; count < im.h*im.w*im.c; ++count){ im.data[count] = curr; } } void or_image(image src, image dest, int c) { int i; for(i = 0; i < src.w*src.h; ++i){ if(src.data[i]) dest.data[dest.w*dest.h*c + i] = 1; } } void exclusive_image(image src) { int k, j, i; int s = src.w*src.h; for(k = 0; k < src.c-1; ++k){ for(i = 0; i < s; ++i){ if (src.data[k*s + i]){ for(j = k+1; j < src.c; ++j){ src.data[j*s + i] = 0; } } } } } box bound_image(image im) { int x,y; int minx = im.w; int miny = im.h; int maxx = 0; int maxy = 0; for(y = 0; y < im.h; ++y){ for(x = 0; x < im.w; ++x){ if(im.data[y*im.w + x]){ minx = (x < minx) ? x : minx; miny = (y < miny) ? y : miny; maxx = (x > maxx) ? x : maxx; maxy = (y > maxy) ? y : maxy; } } } box b = {minx, miny, maxx-minx + 1, maxy-miny + 1}; //printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); return b; } void fill_truth_iseg(char *path, int num_boxes, float *truth, int classes, int w, int h, augment_args aug, int flip, int mw, int mh) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); FILE *file = faasmndp_fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; int i = 0; int j; image part = make_image(w, h, 1); while((fscanf(file, "%d %s", &id, buff) == 2) && i < num_boxes){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); image sized = rotate_crop_image(part, aug.rad, aug.scale, aug.w, aug.h, aug.dx, aug.dy, aug.aspect); if(flip) flip_image(sized); image mask = resize_image(sized, mw, mh); truth[i*(mw*mh+1)] = id; for(j = 0; j < mw*mh; ++j){ truth[i*(mw*mh + 1) + 1 + j] = mask.data[j]; } ++i; free_image(mask); free_image(sized); free(rle); } if(i < num_boxes) truth[i*(mw*mh+1)] = -1; fclose(file); free_image(part); } void fill_truth_mask(char *path, int num_boxes, float *truth, int classes, int w, int h, augment_args aug, int flip, int mw, int mh) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); FILE *file = faasmndp_fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; int i = 0; image part = make_image(w, h, 1); while((fscanf(file, "%d %s", &id, buff) == 2) && i < num_boxes){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); image sized = rotate_crop_image(part, aug.rad, aug.scale, aug.w, aug.h, aug.dx, aug.dy, aug.aspect); if(flip) flip_image(sized); box b = bound_image(sized); if(b.w > 0){ image crop = crop_image(sized, b.x, b.y, b.w, b.h); image mask = resize_image(crop, mw, mh); truth[i*(4 + mw*mh + 1) + 0] = (b.x + b.w/2.)/sized.w; truth[i*(4 + mw*mh + 1) + 1] = (b.y + b.h/2.)/sized.h; truth[i*(4 + mw*mh + 1) + 2] = b.w/sized.w; truth[i*(4 + mw*mh + 1) + 3] = b.h/sized.h; int j; for(j = 0; j < mw*mh; ++j){ truth[i*(4 + mw*mh + 1) + 4 + j] = mask.data[j]; } truth[i*(4 + mw*mh + 1) + 4 + mw*mh] = id; free_image(crop); free_image(mask); ++i; } free_image(sized); free(rle); } fclose(file); free_image(part); } void fill_truth_detection(char *path, int num_boxes, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, "raw", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); if(count > num_boxes) count = num_boxes; float x,y,w,h; int id; int i; int sub = 0; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if ((w < .001 || h < .001)) { ++sub; continue; } truth[(i-sub)*5+0] = x; truth[(i-sub)*5+1] = y; truth[(i-sub)*5+2] = w; truth[(i-sub)*5+3] = h; truth[(i-sub)*5+4] = id; } free(boxes); } #define NUMCHARS 37 void print_letters(float *pred, int n) { int i; for(i = 0; i < n; ++i){ int index = max_index(pred+i*NUMCHARS, NUMCHARS); printf("%c", int_to_alphanum(index)); } printf("\n"); } void fill_truth_captcha(char *path, int n, float *truth) { char *begin = strrchr(path, '/'); ++begin; int i; for(i = 0; i < strlen(begin) && i < n && begin[i] != '.'; ++i){ int index = alphanum_to_int(begin[i]); if(index > 35) printf("Bad %c\n", begin[i]); truth[i*NUMCHARS+index] = 1; } for(;i < n; ++i){ truth[i*NUMCHARS + NUMCHARS-1] = 1; } } data load_data_captcha(char **paths, int n, int m, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = make_matrix(n, k*NUMCHARS); int i; for(i = 0; i < n; ++i){ fill_truth_captcha(paths[i], k, d.y.vals[i]); } if(m) free(paths); return d; } data load_data_captcha_encode(char **paths, int n, int m, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.X.cols = 17100; d.y = d.X; if(m) free(paths); return d; } void fill_truth(char *path, char **labels, int k, float *truth) { int i; memset(truth, 0, k*sizeof(float)); int count = 0; for(i = 0; i < k; ++i){ if(strstr(path, labels[i])){ truth[i] = 1; ++count; //printf("%s %s %d\n", path, labels[i], i); } } if(count != 1 && (k != 1 || count != 0)) printf("Too many or too few labels: %d, %s\n", count, path); } void fill_hierarchy(float *truth, int k, tree *hierarchy) { int j; for(j = 0; j < k; ++j){ if(truth[j]){ int parent = hierarchy->parent[j]; while(parent >= 0){ truth[parent] = 1; parent = hierarchy->parent[parent]; } } } int i; int count = 0; for(j = 0; j < hierarchy->groups; ++j){ //printf("%d\n", count); int mask = 1; for(i = 0; i < hierarchy->group_size[j]; ++i){ if(truth[count + i]){ mask = 0; break; } } if (mask) { for(i = 0; i < hierarchy->group_size[j]; ++i){ truth[count + i] = SECRET_NUM; } } count += hierarchy->group_size[j]; } } matrix load_regression_labels_paths(char **paths, int n, int k) { matrix y = make_matrix(n, k); int i,j; for(i = 0; i < n; ++i){ char labelpath[4096]; find_replace(paths[i], "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".BMP", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPeG", ".txt", labelpath); find_replace(labelpath, ".Jpeg", ".txt", labelpath); find_replace(labelpath, ".PNG", ".txt", labelpath); find_replace(labelpath, ".TIF", ".txt", labelpath); find_replace(labelpath, ".bmp", ".txt", labelpath); find_replace(labelpath, ".jpeg", ".txt", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); find_replace(labelpath, ".tif", ".txt", labelpath); FILE *file = faasmndp_fopen(labelpath, "r"); for(j = 0; j < k; ++j){ fscanf(file, "%f", &(y.vals[i][j])); } fclose(file); } return y; } matrix load_labels_paths(char **paths, int n, char **labels, int k, tree *hierarchy) { matrix y = make_matrix(n, k); int i; for(i = 0; i < n && labels; ++i){ fill_truth(paths[i], labels, k, y.vals[i]); if(hierarchy){ fill_hierarchy(y.vals[i], k, hierarchy); } } return y; } matrix load_tags_paths(char **paths, int n, int k) { matrix y = make_matrix(n, k); int i; //int count = 0; for(i = 0; i < n; ++i){ char label[4096]; find_replace(paths[i], "images", "labels", label); find_replace(label, ".jpg", ".txt", label); FILE *file = faasmndp_fopen(label, "r"); if (!file) continue; //++count; int tag; while(fscanf(file, "%d", &tag) == 1){ if(tag < k){ y.vals[i][tag] = 1; } } fclose(file); } //printf("%d/%d\n", count, n); return y; } char **get_labels(char *filename) { list *plist = get_paths(filename); char **labels = (char **)list_to_array(plist); free_list(plist); return labels; } void free_data(data d) { if(!d.shallow){ free_matrix(d.X); free_matrix(d.y); }else{ free(d.X.vals); free(d.y.vals); } } image get_segmentation_image(char *path, int w, int h, int classes) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); image mask = make_image(w, h, classes); FILE *file = faasmndp_fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; image part = make_image(w, h, 1); while(fscanf(file, "%d %s", &id, buff) == 2){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); or_image(part, mask, id); free(rle); } //exclusive_image(mask); fclose(file); free_image(part); return mask; } image get_segmentation_image2(char *path, int w, int h, int classes) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); image mask = make_image(w, h, classes+1); int i; for(i = 0; i < w*h; ++i){ mask.data[w*h*classes + i] = 1; } FILE *file = faasmndp_fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; image part = make_image(w, h, 1); while(fscanf(file, "%d %s", &id, buff) == 2){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); or_image(part, mask, id); for(i = 0; i < w*h; ++i){ if(part.data[i]) mask.data[w*h*classes + i] = 0; } free(rle); } //exclusive_image(mask); fclose(file); free_image(part); return mask; } data load_data_seg(int n, char **paths, int m, int w, int h, int classes, int min, int max, float angle, float aspect, float hue, float saturation, float exposure, int div) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y.rows = n; d.y.cols = h*w*classes/div/div; d.y.vals = calloc(d.X.rows, sizeof(float*)); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h); image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect); int flip = rand()%2; if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; image mask = get_segmentation_image(random_paths[i], orig.w, orig.h, classes); //image mask = make_image(orig.w, orig.h, classes+1); image sized_m = rotate_crop_image(mask, a.rad, a.scale/div, a.w/div, a.h/div, a.dx/div, a.dy/div, a.aspect); if(flip) flip_image(sized_m); d.y.vals[i] = sized_m.data; free_image(orig); free_image(mask); /* image rgb = mask_to_rgb(sized_m, classes); show_image(rgb, "part"); show_image(sized, "orig"); cvWaitKey(0); free_image(rgb); */ } free(random_paths); return d; } data load_data_iseg(int n, char **paths, int m, int w, int h, int classes, int boxes, int div, int min, int max, float angle, float aspect, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y = make_matrix(n, (((w/div)*(h/div))+1)*boxes); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h); image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect); int flip = rand()%2; if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; //show_image(sized, "image"); fill_truth_iseg(random_paths[i], boxes, d.y.vals[i], classes, orig.w, orig.h, a, flip, w/div, h/div); free_image(orig); /* image rgb = mask_to_rgb(sized_m, classes); show_image(rgb, "part"); show_image(sized, "orig"); cvWaitKey(0); free_image(rgb); */ } free(random_paths); return d; } data load_data_mask(int n, char **paths, int m, int w, int h, int classes, int boxes, int coords, int min, int max, float angle, float aspect, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y = make_matrix(n, (coords+1)*boxes); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h); image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect); int flip = rand()%2; if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; //show_image(sized, "image"); fill_truth_mask(random_paths[i], boxes, d.y.vals[i], classes, orig.w, orig.h, a, flip, 14, 14); free_image(orig); /* image rgb = mask_to_rgb(sized_m, classes); show_image(rgb, "part"); show_image(sized, "orig"); cvWaitKey(0); free_image(rgb); */ } free(random_paths); return d; } data load_data_region(int n, char **paths, int m, int w, int h, int size, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = size*size*(5+classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; int flip = rand()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/ow)/sx; float dy = ((float)ptop /oh)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; fill_truth_region(random_paths[i], d.y.vals[i], classes, size, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); } free(random_paths); return d; } data load_data_compare(int n, char **paths, int m, int classes, int w, int h) { if(m) paths = get_random_paths(paths, 2*n, m); int i,j; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*6; int k = 2*(classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image im1 = load_image_color(paths[i*2], w, h); image im2 = load_image_color(paths[i*2+1], w, h); d.X.vals[i] = calloc(d.X.cols, sizeof(float)); memcpy(d.X.vals[i], im1.data, h*w*3*sizeof(float)); memcpy(d.X.vals[i] + h*w*3, im2.data, h*w*3*sizeof(float)); int id; float iou; char imlabel1[4096]; char imlabel2[4096]; find_replace(paths[i*2], "imgs", "labels", imlabel1); find_replace(imlabel1, "jpg", "txt", imlabel1); FILE *fp1 = faasmndp_fopen(imlabel1, "r"); while(fscanf(fp1, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id] < iou) d.y.vals[i][2*id] = iou; } find_replace(paths[i*2+1], "imgs", "labels", imlabel2); find_replace(imlabel2, "jpg", "txt", imlabel2); FILE *fp2 = faasmndp_fopen(imlabel2, "r"); while(fscanf(fp2, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id + 1] < iou) d.y.vals[i][2*id + 1] = iou; } for (j = 0; j < classes; ++j){ if (d.y.vals[i][2*j] > .5 && d.y.vals[i][2*j+1] < .5){ d.y.vals[i][2*j] = 1; d.y.vals[i][2*j+1] = 0; } else if (d.y.vals[i][2*j] < .5 && d.y.vals[i][2*j+1] > .5){ d.y.vals[i][2*j] = 0; d.y.vals[i][2*j+1] = 1; } else { d.y.vals[i][2*j] = SECRET_NUM; d.y.vals[i][2*j+1] = SECRET_NUM; } } fclose(fp1); fclose(fp2); free_image(im1); free_image(im2); } if(m) free(paths); return d; } data load_data_swag(char **paths, int n, int classes, float jitter) { int index = rand()%n; char *random_path = paths[index]; image orig = load_image_color(random_path, 0, 0); int h = orig.h; int w = orig.w; data d = {0}; d.shallow = 0; d.w = w; d.h = h; d.X.rows = 1; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = (4+classes)*90; d.y = make_matrix(1, k); int dw = w*jitter; int dh = h*jitter; int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = w - pleft - pright; int sheight = h - ptop - pbot; float sx = (float)swidth / w; float sy = (float)sheight / h; int flip = rand()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/w)/sx; float dy = ((float)ptop /h)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); d.X.vals[0] = sized.data; fill_truth_swag(random_path, d.y.vals[0], classes, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); return d; } data load_data_detection(int n, char **paths, int m, int w, int h, int boxes, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y = make_matrix(n, 5*boxes); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); image sized = make_image(w, h, orig.c); fill_image(sized, .5); float dw = jitter * orig.w; float dh = jitter * orig.h; float new_ar = (orig.w + rand_uniform(-dw, dw)) / (orig.h + rand_uniform(-dh, dh)); //float scale = rand_uniform(.25, 2); float scale = 1; float nw, nh; if(new_ar < 1){ nh = scale * h; nw = nh * new_ar; } else { nw = scale * w; nh = nw / new_ar; } float dx = rand_uniform(0, w - nw); float dy = rand_uniform(0, h - nh); place_image(orig, nw, nh, dx, dy, sized); random_distort_image(sized, hue, saturation, exposure); int flip = rand()%2; if(flip) flip_image(sized); d.X.vals[i] = sized.data; fill_truth_detection(random_paths[i], boxes, d.y.vals[i], classes, flip, -dx/w, -dy/h, nw/w, nh/h); free_image(orig); } free(random_paths); return d; } void *load_thread(void *ptr) { //printf("Loading data: %d\n", rand()); load_args a = *(struct load_args*)ptr; if(a.exposure == 0) a.exposure = 1; if(a.saturation == 0) a.saturation = 1; if(a.aspect == 0) a.aspect = 1; if (a.type == OLD_CLASSIFICATION_DATA){ *a.d = load_data_old(a.paths, a.n, a.m, a.labels, a.classes, a.w, a.h); } else if (a.type == REGRESSION_DATA){ *a.d = load_data_regression(a.paths, a.n, a.m, a.classes, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } else if (a.type == CLASSIFICATION_DATA){ *a.d = load_data_augment(a.paths, a.n, a.m, a.labels, a.classes, a.hierarchy, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.center); } else if (a.type == SUPER_DATA){ *a.d = load_data_super(a.paths, a.n, a.m, a.w, a.h, a.scale); } else if (a.type == WRITING_DATA){ *a.d = load_data_writing(a.paths, a.n, a.m, a.w, a.h, a.out_w, a.out_h); } else if (a.type == ISEG_DATA){ *a.d = load_data_iseg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.num_boxes, a.scale, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } else if (a.type == INSTANCE_DATA){ *a.d = load_data_mask(a.n, a.paths, a.m, a.w, a.h, a.classes, a.num_boxes, a.coords, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } else if (a.type == SEGMENTATION_DATA){ *a.d = load_data_seg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.scale); } else if (a.type == REGION_DATA){ *a.d = load_data_region(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == DETECTION_DATA){ *a.d = load_data_detection(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == SWAG_DATA){ *a.d = load_data_swag(a.paths, a.n, a.classes, a.jitter); } else if (a.type == COMPARE_DATA){ *a.d = load_data_compare(a.n, a.paths, a.m, a.classes, a.w, a.h); } else if (a.type == IMAGE_DATA){ *(a.im) = load_image_color(a.path, 0, 0); *(a.resized) = resize_image(*(a.im), a.w, a.h); } else if (a.type == LETTERBOX_DATA){ *(a.im) = load_image_color(a.path, 0, 0); *(a.resized) = letterbox_image(*(a.im), a.w, a.h); } else if (a.type == TAG_DATA){ *a.d = load_data_tag(a.paths, a.n, a.m, a.classes, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } free(ptr); return 0; } pthread_t load_data_in_thread(load_args args) { pthread_t thread; struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_thread, ptr)) error("Thread creation failed"); return thread; } void *load_threads(void *ptr) { int i; load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; data *out = args.d; int total = args.n; free(ptr); data *buffers = calloc(args.threads, sizeof(data)); pthread_t *threads = calloc(args.threads, sizeof(pthread_t)); for(i = 0; i < args.threads; ++i){ args.d = buffers + i; args.n = (i+1) * total/args.threads - i * total/args.threads; threads[i] = load_data_in_thread(args); } for(i = 0; i < args.threads; ++i){ pthread_join(threads[i], 0); } *out = concat_datas(buffers, args.threads); out->shallow = 0; for(i = 0; i < args.threads; ++i){ buffers[i].shallow = 1; free_data(buffers[i]); } free(buffers); free(threads); return 0; } void load_data_blocking(load_args args) { struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; load_thread(ptr); } pthread_t load_data(load_args args) { pthread_t thread; struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_threads, ptr)) error("Thread creation failed"); return thread; } data load_data_writing(char **paths, int n, int m, int w, int h, int out_w, int out_h) { if(m) paths = get_random_paths(paths, n, m); char **replace_paths = find_replace_paths(paths, n, ".png", "-label.png"); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_image_paths_gray(replace_paths, n, out_w, out_h); if(m) free(paths); int i; for(i = 0; i < n; ++i) free(replace_paths[i]); free(replace_paths); return d; } data load_data_old(char **paths, int n, int m, char **labels, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_labels_paths(paths, n, labels, k, 0); if(m) free(paths); return d; } /* data load_data_study(char **paths, int n, int m, char **labels, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { data d = {0}; d.indexes = calloc(n, sizeof(int)); if(m) paths = get_random_paths_indexes(paths, n, m, d.indexes); d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure); d.y = load_labels_paths(paths, n, labels, k); if(m) free(paths); return d; } */ data load_data_super(char **paths, int n, int m, int w, int h, int scale) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; int i; d.X.rows = n; d.X.vals = calloc(n, sizeof(float*)); d.X.cols = w*h*3; d.y.rows = n; d.y.vals = calloc(n, sizeof(float*)); d.y.cols = w*scale * h*scale * 3; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop = random_crop_image(im, w*scale, h*scale); int flip = rand()%2; if (flip) flip_image(crop); image resize = resize_image(crop, w, h); d.X.vals[i] = resize.data; d.y.vals[i] = crop.data; free_image(im); } if(m) free(paths); return d; } data load_data_regression(char **paths, int n, int m, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0); d.y = load_regression_labels_paths(paths, n, k); if(m) free(paths); return d; } data select_data(data *orig, int *inds) { data d = {0}; d.shallow = 1; d.w = orig[0].w; d.h = orig[0].h; d.X.rows = orig[0].X.rows; d.y.rows = orig[0].X.rows; d.X.cols = orig[0].X.cols; d.y.cols = orig[0].y.cols; d.X.vals = calloc(orig[0].X.rows, sizeof(float *)); d.y.vals = calloc(orig[0].y.rows, sizeof(float *)); int i; for(i = 0; i < d.X.rows; ++i){ d.X.vals[i] = orig[inds[i]].X.vals[i]; d.y.vals[i] = orig[inds[i]].y.vals[i]; } return d; } data *tile_data(data orig, int divs, int size) { data *ds = calloc(divs*divs, sizeof(data)); int i, j; #pragma omp parallel for for(i = 0; i < divs*divs; ++i){ data d; d.shallow = 0; d.w = orig.w/divs * size; d.h = orig.h/divs * size; d.X.rows = orig.X.rows; d.X.cols = d.w*d.h*3; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.y = copy_matrix(orig.y); #pragma omp parallel for for(j = 0; j < orig.X.rows; ++j){ int x = (i%divs) * orig.w / divs - (d.w - orig.w/divs)/2; int y = (i/divs) * orig.h / divs - (d.h - orig.h/divs)/2; image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[j]); d.X.vals[j] = crop_image(im, x, y, d.w, d.h).data; } ds[i] = d; } return ds; } data resize_data(data orig, int w, int h) { data d = {0}; d.shallow = 0; d.w = w; d.h = h; int i; d.X.rows = orig.X.rows; d.X.cols = w*h*3; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.y = copy_matrix(orig.y); #pragma omp parallel for for(i = 0; i < orig.X.rows; ++i){ image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[i]); d.X.vals[i] = resize_image(im, w, h).data; } return d; } data load_data_augment(char **paths, int n, int m, char **labels, int k, tree *hierarchy, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.w=size; d.h=size; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, center); d.y = load_labels_paths(paths, n, labels, k, hierarchy); if(m) free(paths); return d; } data load_data_tag(char **paths, int n, int m, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.w = size; d.h = size; d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0); d.y = load_tags_paths(paths, n, k); if(m) free(paths); return d; } matrix concat_matrix(matrix m1, matrix m2) { int i, count = 0; matrix m; m.cols = m1.cols; m.rows = m1.rows+m2.rows; m.vals = calloc(m1.rows + m2.rows, sizeof(float*)); for(i = 0; i < m1.rows; ++i){ m.vals[count++] = m1.vals[i]; } for(i = 0; i < m2.rows; ++i){ m.vals[count++] = m2.vals[i]; } return m; } data concat_data(data d1, data d2) { data d = {0}; d.shallow = 1; d.X = concat_matrix(d1.X, d2.X); d.y = concat_matrix(d1.y, d2.y); d.w = d1.w; d.h = d1.h; return d; } data concat_datas(data *d, int n) { int i; data out = {0}; for(i = 0; i < n; ++i){ data new = concat_data(d[i], out); free_data(out); out = new; } return out; } data load_categorical_data_csv(char *filename, int target, int k) { data d = {0}; d.shallow = 0; matrix X = csv_to_matrix(filename); float *truth_1d = pop_column(&X, target); float **truth = one_hot_encode(truth_1d, X.rows, k); matrix y; y.rows = X.rows; y.cols = k; y.vals = truth; d.X = X; d.y = y; free(truth_1d); return d; } data load_cifar10_data(char *filename) { data d = {0}; d.shallow = 0; long i,j; matrix X = make_matrix(10000, 3072); matrix y = make_matrix(10000, 10); d.X = X; d.y = y; FILE *fp = faasmndp_fopen(filename, "rb"); if(!fp) file_error(filename); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class = bytes[0]; y.vals[i][class] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i][j] = (double)bytes[j+1]; } } scale_data_rows(d, 1./255); //normalize_data_rows(d); fclose(fp); return d; } void get_random_batch(data d, int n, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = rand()%d.X.rows; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void get_next_batch(data d, int n, int offset, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = offset + j; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); if(y) memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void smooth_data(data d) { int i, j; float scale = 1. / d.y.cols; float eps = .1; for(i = 0; i < d.y.rows; ++i){ for(j = 0; j < d.y.cols; ++j){ d.y.vals[i][j] = eps * scale + (1-eps) * d.y.vals[i][j]; } } } data load_all_cifar10() { data d = {0}; d.shallow = 0; int i,j,b; matrix X = make_matrix(50000, 3072); matrix y = make_matrix(50000, 10); d.X = X; d.y = y; for(b = 0; b < 5; ++b){ char buff[256]; sprintf(buff, "data/cifar/cifar-10-batches-bin/data_batch_%d.bin", b+1); FILE *fp = faasmndp_fopen(buff, "rb"); if(!fp) file_error(buff); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class = bytes[0]; y.vals[i+b*10000][class] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i+b*10000][j] = (double)bytes[j+1]; } } fclose(fp); } //normalize_data_rows(d); scale_data_rows(d, 1./255); smooth_data(d); return d; } data load_go(char *filename) { FILE *fp = faasmndp_fopen(filename, "rb"); matrix X = make_matrix(3363059, 361); matrix y = make_matrix(3363059, 361); int row, col; if(!fp) file_error(filename); char *label; int count = 0; while((label = fgetl(fp))){ int i; if(count == X.rows){ X = resize_matrix(X, count*2); y = resize_matrix(y, count*2); } sscanf(label, "%d %d", &row, &col); char *board = fgetl(fp); int index = row*19 + col; y.vals[count][index] = 1; for(i = 0; i < 19*19; ++i){ float val = 0; if(board[i] == '1') val = 1; else if(board[i] == '2') val = -1; X.vals[count][i] = val; } ++count; free(label); free(board); } X = resize_matrix(X, count); y = resize_matrix(y, count); data d = {0}; d.shallow = 0; d.X = X; d.y = y; fclose(fp); return d; } void randomize_data(data d) { int i; for(i = d.X.rows-1; i > 0; --i){ int index = rand()%i; float *swap = d.X.vals[index]; d.X.vals[index] = d.X.vals[i]; d.X.vals[i] = swap; swap = d.y.vals[index]; d.y.vals[index] = d.y.vals[i]; d.y.vals[i] = swap; } } void scale_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ scale_array(d.X.vals[i], d.X.cols, s); } } void translate_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ translate_array(d.X.vals[i], d.X.cols, s); } } data copy_data(data d) { data c = {0}; c.w = d.w; c.h = d.h; c.shallow = 0; c.num_boxes = d.num_boxes; c.boxes = d.boxes; c.X = copy_matrix(d.X); c.y = copy_matrix(d.y); return c; } void normalize_data_rows(data d) { int i; for(i = 0; i < d.X.rows; ++i){ normalize_array(d.X.vals[i], d.X.cols); } } data get_data_part(data d, int part, int total) { data p = {0}; p.shallow = 1; p.X.rows = d.X.rows * (part + 1) / total - d.X.rows * part / total; p.y.rows = d.y.rows * (part + 1) / total - d.y.rows * part / total; p.X.cols = d.X.cols; p.y.cols = d.y.cols; p.X.vals = d.X.vals + d.X.rows * part / total; p.y.vals = d.y.vals + d.y.rows * part / total; return p; } data get_random_data(data d, int num) { data r = {0}; r.shallow = 1; r.X.rows = num; r.y.rows = num; r.X.cols = d.X.cols; r.y.cols = d.y.cols; r.X.vals = calloc(num, sizeof(float *)); r.y.vals = calloc(num, sizeof(float *)); int i; for(i = 0; i < num; ++i){ int index = rand()%d.X.rows; r.X.vals[i] = d.X.vals[index]; r.y.vals[i] = d.y.vals[index]; } return r; } data *split_data(data d, int part, int total) { data *split = calloc(2, sizeof(data)); int i; int start = part*d.X.rows/total; int end = (part+1)*d.X.rows/total; data train; data test; train.shallow = test.shallow = 1; test.X.rows = test.y.rows = end-start; train.X.rows = train.y.rows = d.X.rows - (end-start); train.X.cols = test.X.cols = d.X.cols; train.y.cols = test.y.cols = d.y.cols; train.X.vals = calloc(train.X.rows, sizeof(float*)); test.X.vals = calloc(test.X.rows, sizeof(float*)); train.y.vals = calloc(train.y.rows, sizeof(float*)); test.y.vals = calloc(test.y.rows, sizeof(float*)); for(i = 0; i < start; ++i){ train.X.vals[i] = d.X.vals[i]; train.y.vals[i] = d.y.vals[i]; } for(i = start; i < end; ++i){ test.X.vals[i-start] = d.X.vals[i]; test.y.vals[i-start] = d.y.vals[i]; } for(i = end; i < d.X.rows; ++i){ train.X.vals[i-(end-start)] = d.X.vals[i]; train.y.vals[i-(end-start)] = d.y.vals[i]; } split[0] = train; split[1] = test; return split; }
SwathFileConsumer.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <boost/cast.hpp> // Datastructures #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> // Consumers #include <OpenMS/FORMAT/DATAACCESS/MSDataCachedConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h> // Helpers #include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> #ifdef _OPENMP #include <omp.h> #endif namespace OpenMS { /** * @brief Abstract base class which can consume spectra coming from SWATH experiment stored in a single file. * * The class consumes spectra which are coming from a complete SWATH * experiment. It will group MS2 spectra by their precursor m/z, assuming * that they correspond to the same SWATH window. For example, the spectra * could be arranged in the following fashion: * * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * - MS2 Spectrum (precursor = [1175,1200]) * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * * Base classes are expected to implement functions consuming a spectrum coming * from a specific SWATH or an MS1 spectrum and a final function * ensureMapsAreFilled_ after which the swath_maps_ vector needs to contain * valid pointers to MSExperiment. * * In addition it is possible to provide the swath boundaries and the read in * spectra will be matched by their precursor m/z to the "center" attribute * of the provided Swath maps. * * Usage: * * @code * FullSwathFileConsumer * dataConsumer; * // assign dataConsumer to an implementation of FullSwathFileConsumer * MzMLFile().transform(file, dataConsumer); * dataConsumer->retrieveSwathMaps(maps); * @endcode * */ class OPENMS_DLLAPI FullSwathFileConsumer : public Interfaces::IMSDataConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; FullSwathFileConsumer() : ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } /** * @brief Constructor * * @param swath_boundaries A vector of SwathMaps of which only the center, * lower and upper attributes will be used to infer the expected Swath maps. * */ FullSwathFileConsumer(std::vector<OpenSwath::SwathMap> swath_boundaries) : swath_map_boundaries_(swath_boundaries), ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } ~FullSwathFileConsumer() override {} void setExpectedSize(Size, Size) override {} void setExperimentalSettings(const ExperimentalSettings& exp) override {settings_ = exp; } /** * @brief Populate the vector of swath maps after consuming all spectra. * * Will populate the input vector with SwathMap objects which correspond to * the MS1 map (if present) and the MS2 maps (SWATH maps). This should be * called after all spectra are consumed. * * @note It is not possible to consume any more spectra after calling this * function (it contains finalization code and may close file streams). * */ void retrieveSwathMaps(std::vector<OpenSwath::SwathMap>& maps) { consuming_possible_ = false; // make consumption of further spectra / chromatograms impossible ensureMapsAreFilled_(); if (ms1_map_) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(ms1_map_); map.lower = -1; map.upper = -1; map.center = -1; map.ms1 = true; maps.push_back(map); } // Print warning if the lower/upper window could not be determined and we // required manual determination of the boundaries. if (!use_external_boundaries_ && correct_window_counter_ != swath_maps_.size()) { std::cout << "WARNING: Could not correctly read the upper/lower limits of the SWATH windows from your input file. Read " << correct_window_counter_ << " correct (non-zero) window limits (expected " << swath_maps_.size() << " windows)." << std::endl; } size_t nonempty_maps = 0; for (Size i = 0; i < swath_maps_.size(); i++) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_maps_[i]); map.lower = swath_map_boundaries_[i].lower; map.upper = swath_map_boundaries_[i].upper; map.center = swath_map_boundaries_[i].center; map.ms1 = false; maps.push_back(map); if (map.sptr->getNrSpectra() > 0) {nonempty_maps++;} } if (nonempty_maps != swath_map_boundaries_.size()) { std::cout << "WARNING: The number nonempty maps found in the input file (" << nonempty_maps << ") is not equal to the number of provided swath window boundaries (" << swath_map_boundaries_.size() << "). Please check your input." << std::endl; } } /// Consume a chromatogram -> should not happen when dealing with SWATH maps void consumeChromatogram(MapType::ChromatogramType&) override { std::cerr << "Read chromatogram while reading SWATH files, did not expect that!" << std::endl; } /** * @brief * Consume a spectrum which may belong either to an MS1 scan or * one of n MS2 (SWATH) scans * */ void consumeSpectrum(MapType::SpectrumType& s) override { if (!consuming_possible_) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "FullSwathFileConsumer cannot consume any more spectra after retrieveSwathMaps has been called already"); } if (s.getMSLevel() == 1) { consumeMS1Spectrum_(s); } else { if (s.getPrecursors().empty()) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide a precursor."); } const std::vector<Precursor> prec = s.getPrecursors(); double center = prec[0].getMZ(); double lower = prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset(); double upper = prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset(); bool found = false; // Check if enough information is present to infer the swath if (center <= 0.0) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide any precursor isolation information."); } // try to match the current scan to one of the already known windows for (Size i = 0; i < swath_map_boundaries_.size(); i++) { // We group by the precursor mz (center of the window) since this // should be present in all SWATH scans. if (std::fabs(center - swath_map_boundaries_[i].center) < 1e-6) { found = true; consumeSwathSpectrum_(s, i); break; } } if (!found) { if (use_external_boundaries_) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Encountered SWATH scan with boundary ") + center + " m/z which was not present in the provided windows."); } else { consumeSwathSpectrum_(s, swath_map_boundaries_.size()); // we found a new SWATH window if (lower > 0.0 && upper > 0.0) {correct_window_counter_++;} OpenSwath::SwathMap boundary; boundary.lower = lower; boundary.upper = upper; boundary.center = center; swath_map_boundaries_.push_back(boundary); OPENMS_LOG_DEBUG << "Adding Swath centered at " << center << " m/z with an isolation window of " << lower << " to " << upper << " m/z." << std::endl; } } } } protected: /** * @brief Consume an MS2 spectrum belonging to SWATH "swath_nr" * * This function should handle a spectrum belonging to a specific SWATH * (indicated by swath_nr). * */ virtual void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) = 0; /** * @brief Consume an MS1 spectrum * * This function should handle an MS1 spectrum. * */ virtual void consumeMS1Spectrum_(MapType::SpectrumType& s) = 0; /** * @brief Callback function after the reading is complete * * Has to ensure that swath_maps_ and ms1_map_ are correctly populated. */ virtual void ensureMapsAreFilled_() = 0; /// A list of Swath map identifiers (lower/upper boundary and center) std::vector<OpenSwath::SwathMap> swath_map_boundaries_; /// A list of SWATH maps and the MS1 map std::vector<boost::shared_ptr<PeakMap > > swath_maps_; boost::shared_ptr<PeakMap > ms1_map_; /// The Experimental settings // (MSExperiment has no constructor using ExperimentalSettings) PeakMap settings_; /// Whether further spectra can still be consumed bool consuming_possible_; /// Whether to use external input for SWATH boundaries bool use_external_boundaries_; /// How many windows were correctly annotated (non-zero window limits) size_t correct_window_counter_; }; /** * @brief In-memory implementation of FullSwathFileConsumer * * Keeps all the spectra in memory by just appending them to an MSExperiment. * */ class OPENMS_DLLAPI RegularSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; RegularSwathFileConsumer() {} RegularSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries) : FullSwathFileConsumer(known_window_boundaries) {} protected: void addNewSwathMap_() { boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_maps_[swath_nr]->addSpectrum(s); } void addMS1Map_() { boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (!ms1_map_) { addMS1Map_(); } ms1_map_->addSpectrum(s); } void ensureMapsAreFilled_() override {} }; /** * @brief On-disk cached implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk in a user-specified caching * location using the MSDataCachedConsumer. Internally, it handles * n+1 (n SWATH + 1 MS1 map) objects of MSDataCachedConsumer which can consume the * spectra and write them to disk immediately. * */ class OPENMS_DLLAPI CachedSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; CachedSwathFileConsumer(String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} CachedSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~CachedSwathFileConsumer() override { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } protected: void addNewSwathMap_() { String meta_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; String cached_file = meta_file + ".cached"; MSDataCachedConsumer* consumer = new MSDataCachedConsumer(cached_file, true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); // maps for meta data boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); // write data to cached file; clear data from spectrum s swath_maps_[swath_nr]->addSpectrum(s); // append for the metadata (actual data was deleted) } void addMS1Map_() { String meta_file = cachedir_ + basename_ + "_ms1.mzML"; String cached_file = meta_file + ".cached"; ms1_consumer_ = new MSDataCachedConsumer(cached_file, true); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); ms1_map_->addSpectrum(s); // append for the metadata (actual data is deleted) } void ensureMapsAreFilled_() override { size_t swath_consumers_size = swath_consumers_.size(); bool have_ms1 = (ms1_consumer_ != nullptr); // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream // The file streams to the cached data on disc can and should be closed // here safely. Since ensureMapsAreFilled_ is called after consuming all // the spectra, there will be no more spectra to append but the client // might already want to read after this call, so all data needs to be // present on disc and the file streams closed. // // TODO merge with destructor code into own function! while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } if (have_ms1) { boost::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_ms1.mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*ms1_map_, meta_file, true); MzMLFile().load(meta_file, *exp.get()); ms1_map_ = exp; } #ifdef _OPENMP #pragma omp parallel for #endif for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(swath_consumers_size); i++) { boost::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_" + String(i) + ".mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*swath_maps_[i], meta_file, true); MzMLFile().load(meta_file, *exp.get()); swath_maps_[i] = exp; } } MSDataCachedConsumer* ms1_consumer_; std::vector<MSDataCachedConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; /** * @brief On-disk mzML implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk to an mzML file location using the * PlainMSDataWritingConsumer. Internally, it handles n+1 (n SWATH + 1 MS1 * map) objects of MSDataCachedConsumer which can consume the spectra and * write them to disk immediately. * * Warning: no swathmaps (MS1 nor MS2) will be available when calling retrieveSwathMaps() * for downstream use. * */ class OPENMS_DLLAPI MzMLSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; MzMLSwathFileConsumer(const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} MzMLSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~MzMLSwathFileConsumer() override { deleteSetNull_(); } protected: void deleteSetNull_() { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } void addNewSwathMap_() { String mzml_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; PlainMSDataWritingConsumer* consumer = new PlainMSDataWritingConsumer(mzml_file); consumer->getOptions().setCompression(true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { // only use swath_consumers_ to count how many we have already added while (swath_consumers_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); s.clear(false); } void addMS1Map_() { String mzml_file = cachedir_ + basename_ + "_ms1.mzML"; ms1_consumer_ = new PlainMSDataWritingConsumer(mzml_file); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); ms1_consumer_->getOptions().setCompression(true); } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); } void ensureMapsAreFilled_() override { deleteSetNull_(); } PlainMSDataWritingConsumer* ms1_consumer_; std::vector<PlainMSDataWritingConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; }
idaFoodWeb_bnd_omp.c
/* * ----------------------------------------------------------------- * Programmer(s): Daniel R. Reynolds and Ting Yan @ SMU * Based on idaFoodWeb_bnd.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example program for IDA: Food web problem. * * This example program (OpenMP version) uses the SUNBAND linear * solver, and IDACalcIC for initial condition calculation. * * The mathematical problem solved in this example is a DAE system * that arises from a system of partial differential equations after * spatial discretization. The PDE system is a food web population * model, with predator-prey interaction and diffusion on the unit * square in two dimensions. The dependent variable vector is: * * 1 2 ns * c = (c , c , ..., c ) , ns = 2 * np * * and the PDE's are as follows: * * i i i * dc /dt = d(i)*(c + c ) + R (x,y,c) (i = 1,...,np) * xx yy i * * i i * 0 = d(i)*(c + c ) + R (x,y,c) (i = np+1,...,ns) * xx yy i * * where the reaction terms R are: * * i ns j * R (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * all other a(i,j) = 0 * b(i) = BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i <= np) * b(i) =-BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED (i > np) * * The various scalar parameters required are set using '#define' * statements or directly in routine InitUserData. In this program, * np = 1, ns = 2. The boundary conditions are homogeneous Neumann: * normal derivative = 0. * * A polynomial in x and y is used to set the initial values of the * first np variables (the prey variables) at each x,y location, * while initial values for the remaining (predator) variables are * set to a flat value, which is corrected by IDACalcIC. * * The PDEs are discretized by central differencing on a MX by MY * mesh. * * The DAE system is solved by IDA using the SUNBAND linear solver. * Output is printed at t = 0, .001, .01, .1, .4, .7, 1. * * Optionally, we can set the number of threads from environment * variable or command line. To check the current value for number * of threads from environment: * % echo $OMP_NUM_THREADS * * Execution: * * To use the default value for the number of threads from * the OMP_NUM_THREADS environment value: * % ./idaFoodWeb_bnd_omp * To specify the number of threads at the command line, use * % ./idaFoodWeb_bnd_omp num_threads * where num_threads is the desired number of threads. * * ----------------------------------------------------------------- * References: * [1] Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, Journal * of Applied Mathematics and Computation, Vol. 31 (May 1989), * pp. 40-91. * * [2] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold, * Using Krylov Methods in the Solution of Large-Scale * Differential-Algebraic Systems, SIAM J. Sci. Comput., 15 * (1994), pp. 1467-1488. * * [3] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold, * Consistent Initial Condition Calculation for Differential- * Algebraic Systems, SIAM J. Sci. Comput., 19 (1998), * pp. 1495-1512. * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ida/ida.h> #include <sunmatrix/sunmatrix_band.h> #include <sunlinsol/sunlinsol_band.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_direct.h> #include <sundials/sundials_types.h> #ifdef _OPENMP #include <omp.h> #endif /* Problem Constants. */ #define NPREY 1 /* No. of prey (= no. of predators). */ #define NUM_SPECIES 2*NPREY #define PI RCONST(3.1415926535898) #define FOURPI (RCONST(4.0)*PI) #define MX 20 /* MX = number of x mesh points */ #define MY 20 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NUM_SPECIES*MX*MY) #define AA RCONST(1.0) /* Coefficient in above eqns. for a */ #define EE RCONST(10000.) /* Coefficient in above eqns. for a */ #define GG RCONST(0.5e-6) /* Coefficient in above eqns. for a */ #define BB RCONST(1.0) /* Coefficient in above eqns. for b */ #define DPREY RCONST(1.0) /* Coefficient in above eqns. for d */ #define DPRED RCONST(0.05) /* Coefficient in above eqns. for d */ #define ALPHA RCONST(50.) /* Coefficient alpha in above eqns. */ #define BETA RCONST(1000.) /* Coefficient beta in above eqns. */ #define AX RCONST(1.0) /* Total range of x variable */ #define AY RCONST(1.0) /* Total range of y variable */ #define RTOL RCONST(1.e-5) /* Relative tolerance */ #define ATOL RCONST(1.e-5) /* Absolute tolerance */ #define NOUT 6 /* Number of output times */ #define TMULT RCONST(10.0) /* Multiplier for tout values */ #define TADD RCONST(0.3) /* Increment for tout values */ #define ZERO RCONST(0.) #define ONE RCONST(1.0) /* * User-defined vector and accessor macro: IJ_Vptr. * IJ_Vptr is defined in order to express the underlying 3-D structure of * the dependent variable vector from its underlying 1-D storage (an N_Vector). * IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to * species index is = 0, x-index ix = i, and y-index jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, (i)*NUM_SPECIES + (j)*NSMX)) /* Type: UserData. Contains problem constants, etc. */ typedef struct { sunindextype Neq, ns, np, mx, my; realtype dx, dy, **acoef; realtype cox[NUM_SPECIES], coy[NUM_SPECIES], bcoef[NUM_SPECIES]; N_Vector rates; int nthreads; } *UserData; /* Prototypes for functions called by the IDA Solver. */ static int resweb(realtype time, N_Vector cc, N_Vector cp, N_Vector resval, void *user_data); /* Prototypes for private Helper Functions. */ static void InitUserData(UserData webdata); static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id, UserData webdata); static void PrintHeader(sunindextype mu, sunindextype ml, realtype rtol, realtype atol); static void PrintOutput(void *ida_mem, N_Vector c, realtype t); static void PrintFinalStats(void *ida_mem); static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata); static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, UserData webdata); static realtype dotprod(sunindextype size, realtype *x1, realtype *x2); static int check_retval(void *returnvalue, char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { void *ida_mem; SUNMatrix A; SUNLinearSolver LS; UserData webdata; N_Vector cc, cp, id; int iout, retval; sunindextype mu, ml; realtype rtol, atol, t0, tout, tret; int num_threads; ida_mem = NULL; A = NULL; LS = NULL; webdata = NULL; cc = cp = id = NULL; /* Set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* overwrite with OMP_NUM_THREADS enviroment variable */ #endif if (argc > 1) /* overwrite with command line value, if supplied */ num_threads = strtol(argv[1], NULL, 0); /* Allocate and initialize user data block webdata. */ webdata = (UserData) malloc(sizeof *webdata); webdata->rates = N_VNew_OpenMP(NEQ, num_threads); webdata->acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); webdata->nthreads = num_threads; InitUserData(webdata); /* Allocate N-vectors and initialize cc, cp, and id. */ cc = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)cc, "N_VNew_OpenMP", 0)) return(1); cp = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)cp, "N_VNew_OpenMP", 0)) return(1); id = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)id, "N_VNew_OpenMP", 0)) return(1); SetInitialProfiles(cc, cp, id, webdata); /* Set remaining inputs to IDAMalloc. */ t0 = ZERO; rtol = RTOL; atol = ATOL; /* Call IDACreate and IDAMalloc to initialize IDA. */ ida_mem = IDACreate(); if(check_retval((void *) ida_mem, "IDACreate", 0)) return(1); retval = IDASetUserData(ida_mem, webdata); if(check_retval(&retval, "IDASetUserData", 1)) return(1); retval = IDASetId(ida_mem, id); if(check_retval(&retval, "IDASetId", 1)) return(1); retval = IDAInit(ida_mem, resweb, t0, cc, cp); if(check_retval(&retval, "IDAInit", 1)) return(1); retval = IDASStolerances(ida_mem, rtol, atol); if(check_retval(&retval, "IDASStolerances", 1)) return(1); /* Setup band matrix and linear solver, and attach to IDA. */ mu = ml = NSMX; A = SUNBandMatrix(NEQ, mu, ml); if(check_retval((void *)A, "SUNBandMatrix", 0)) return(1); LS = SUNLinSol_Band(cc, A); if(check_retval((void *)LS, "SUNLinSol_Band", 0)) return(1); retval = IDASetLinearSolver(ida_mem, LS, A); if(check_retval(&retval, "IDASetLinearSolver", 1)) return(1); /* Call IDACalcIC (with default options) to correct the initial values. */ tout = RCONST(0.001); retval = IDACalcIC(ida_mem, IDA_YA_YDP_INIT, tout); if(check_retval(&retval, "IDACalcIC", 1)) return(1); /* Print heading, basic parameters, and initial values. */ PrintHeader(mu, ml, rtol, atol); PrintOutput(ida_mem, cc, ZERO); /* Loop over iout, call IDASolve (normal mode), print selected output. */ for (iout = 1; iout <= NOUT; iout++) { retval = IDASolve(ida_mem, tout, &tret, cc, cp, IDA_NORMAL); if(check_retval(&retval, "IDASolve", 1)) return(retval); PrintOutput(ida_mem, cc, tret); if (iout < 3) tout *= TMULT; else tout += TADD; } /* Print final statistics and free memory. */ PrintFinalStats(ida_mem); printf("num_threads = %i\n\n", num_threads); /* Free memory */ IDAFree(&ida_mem); SUNLinSolFree(LS); SUNMatDestroy(A); N_VDestroy_OpenMP(cc); N_VDestroy_OpenMP(cp); N_VDestroy_OpenMP(id); destroyMat(webdata->acoef); N_VDestroy_OpenMP(webdata->rates); free(webdata); return(0); } /* Define lines for readability in later routines */ #define acoef (webdata->acoef) #define bcoef (webdata->bcoef) #define cox (webdata->cox) #define coy (webdata->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY IDA *-------------------------------------------------------------------- */ /* * resweb: System residual function for predator-prey system. * This routine calls Fweb to get all the right-hand sides of the * equations, then loads the residual vector accordingly, * using cp in the case of prey species. */ static int resweb(realtype tt, N_Vector cc, N_Vector cp, N_Vector res, void *user_data) { sunindextype jx, jy, is, yloc, loc, np; realtype *resv, *cpv; UserData webdata; webdata = (UserData)user_data; cpv = NV_DATA_OMP(cp); resv = NV_DATA_OMP(res); np = webdata->np; /* Call Fweb to set res to vector of right-hand sides. */ Fweb(tt, cc, res, webdata); /* Loop over all grid points, setting residual values appropriately for differential or algebraic components. */ #pragma omp parallel for default(shared) private(jy, yloc, jx, loc, is) schedule(static) num_threads(webdata->nthreads) for (jy = 0; jy < MY; jy++) { yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { loc = yloc + NUM_SPECIES * jx; for (is = 0; is < NUM_SPECIES; is++) { if (is < np) resv[loc+is] = cpv[loc+is] - resv[loc+is]; else resv[loc+is] = -resv[loc+is]; } } } return(0); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * InitUserData: Load problem constants in webdata (of type UserData). */ static void InitUserData(UserData webdata) { int i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; webdata->mx = MX; webdata->my = MY; webdata->ns = NUM_SPECIES; webdata->np = NPREY; webdata->dx = AX/(MX-1); webdata->dy = AY/(MY-1); webdata->Neq= NEQ; /* Set up the coefficients a and b, and others found in the equations. */ np = webdata->np; dx2 = (webdata->dx)*(webdata->dx); dy2 = (webdata->dy)*(webdata->dy); for (i = 0; i < np; i++) { a1 = &(acoef[i][np]); a2 = &(acoef[i+np][0]); a3 = &(acoef[i][0]); a4 = &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row. */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* Reset the diagonal elements of acoef to -AA. */ acoef[i][i] = -AA; acoef[i+np][i+np] = -AA; /* Set coefficients for b and diffusion terms. */ bcoef[i] = BB; bcoef[i+np] = -BB; cox[i] = DPREY/dx2; cox[i+np] = DPRED/dx2; coy[i] = DPREY/dy2; coy[i+np] = DPRED/dy2; } } /* * SetInitialProfiles: Set initial conditions in cc, cp, and id. * A polynomial profile is used for the prey cc values, and a constant * (1.0e5) is loaded as the initial guess for the predator cc values. * The id values are set to 1 for the prey and 0 for the predators. * The prey cp values are set according to the given system, and * the predator cp values are set to zero. */ static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id, UserData webdata) { sunindextype loc, yloc, is, jx, jy, np; realtype xx, yy, xyfactor; realtype *ccv, *cpv, *idv; ccv = NV_DATA_OMP(cc); cpv = NV_DATA_OMP(cp); idv = NV_DATA_OMP(id); np = webdata->np; /* Loop over grid, load cc values and id values. */ for (jy = 0; jy < MY; jy++) { yy = jy * webdata->dy; yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { xx = jx * webdata->dx; xyfactor = RCONST(16.0)*xx*(ONE-xx)*yy*(ONE-yy); xyfactor *= xyfactor; loc = yloc + NUM_SPECIES*jx; for (is = 0; is < NUM_SPECIES; is++) { if (is < np) { ccv[loc+is] = RCONST(10.0) + (realtype)(is+1) * xyfactor; idv[loc+is] = ONE; } else { ccv[loc+is] = RCONST(1.0e5); idv[loc+is] = ZERO; } } } } /* Set c' for the prey by calling the function Fweb. */ Fweb(ZERO, cc, cp, webdata); /* Set c' for predators to 0. */ for (jy = 0; jy < MY; jy++) { yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { loc = yloc + NUM_SPECIES * jx; for (is = np; is < NUM_SPECIES; is++) { cpv[loc+is] = ZERO; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(sunindextype mu, sunindextype ml, realtype rtol, realtype atol) { printf("\nidaFoodWeb_bnd_omp: Predator-prey DAE OpenMP example problem for IDA \n\n"); printf("Number of species ns: %d", NUM_SPECIES); printf(" Mesh dimensions: %d x %d", MX, MY); printf(" System size: %d\n", NEQ); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: rtol = %Lg atol = %Lg\n", rtol, atol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol); #else printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol); #endif printf("Linear solver: SUNBAND, Band parameters mu = %ld, ml = %ld\n", (long int) mu, (long int) ml); printf("CalcIC called to correct initial predator concentrations.\n\n"); printf("-----------------------------------------------------------\n"); printf(" t bottom-left top-right"); printf(" | nst k h\n"); printf("-----------------------------------------------------------\n\n"); } /* * PrintOutput: Print output values at output time t = tt. * Selected run statistics are printed. Then values of the concentrations * are printed for the bottom left and top right grid points only. */ static void PrintOutput(void *ida_mem, N_Vector c, realtype t) { int i, kused, retval; long int nst; realtype *c_bl, *c_tr, hused; retval = IDAGetLastOrder(ida_mem, &kused); check_retval(&retval, "IDAGetLastOrder", 1); retval = IDAGetNumSteps(ida_mem, &nst); check_retval(&retval, "IDAGetNumSteps", 1); retval = IDAGetLastStep(ida_mem, &hused); check_retval(&retval, "IDAGetLastStep", 1); c_bl = IJ_Vptr(c,0,0); c_tr = IJ_Vptr(c,MX-1,MY-1); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%8.2Le %12.4Le %12.4Le | %3ld %1d %12.4Le\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4Le %12.4Le |\n",c_bl[i],c_tr[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]); #else printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]); #endif printf("\n"); } /* * PrintFinalStats: Print final run data contained in iopt. */ static void PrintFinalStats(void *ida_mem) { long int nst, nre, nreLS, nni, nje, netf, ncfn; int retval; retval = IDAGetNumSteps(ida_mem, &nst); check_retval(&retval, "IDAGetNumSteps", 1); retval = IDAGetNumNonlinSolvIters(ida_mem, &nni); check_retval(&retval, "IDAGetNumNonlinSolvIters", 1); retval = IDAGetNumResEvals(ida_mem, &nre); check_retval(&retval, "IDAGetNumResEvals", 1); retval = IDAGetNumErrTestFails(ida_mem, &netf); check_retval(&retval, "IDAGetNumErrTestFails", 1); retval = IDAGetNumNonlinSolvConvFails(ida_mem, &ncfn); check_retval(&retval, "IDAGetNumNonlinSolvConvFails", 1); retval = IDAGetNumJacEvals(ida_mem, &nje); check_retval(&retval, "IDAGetNumJacEvals", 1); retval = IDAGetNumLinResEvals(ida_mem, &nreLS); check_retval(&retval, "IDAGetNumLinResEvals", 1); printf("-----------------------------------------------------------\n"); printf("Final run statistics: \n\n"); printf("Number of steps = %ld\n", nst); printf("Number of residual evaluations = %ld\n", nre+nreLS); printf("Number of Jacobian evaluations = %ld\n", nje); printf("Number of nonlinear iterations = %ld\n", nni); printf("Number of error test failures = %ld\n", netf); printf("Number of nonlinear conv. failures = %ld\n", ncfn); } /* * Fweb: Rate function for the food-web problem. * This routine computes the right-hand sides of the system equations, * consisting of the diffusion term and interaction term. * The interaction term is computed by the function WebRates. */ static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata) { sunindextype jx, jy, is, idyu, idyl, idxu, idxl; realtype xx, yy, *cxy, *ratesxy, *cratexy, dcyli, dcyui, dcxli, dcxui; /* Loop over grid points, evaluate interaction vector (length ns), form diffusion difference terms, and load crate. */ for (jy = 0; jy < MY; jy++) { yy = (webdata->dy) * jy ; idyu = (jy!=MY-1) ? NSMX : -NSMX; idyl = (jy!= 0 ) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = (webdata->dx) * jx; idxu = (jx!= MX-1) ? NUM_SPECIES : -NUM_SPECIES; idxl = (jx!= 0 ) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); ratesxy = IJ_Vptr(webdata->rates,jx,jy); cratexy = IJ_Vptr(crate,jx,jy); /* Get interaction vector at this grid point. */ WebRates(xx, yy, cxy, ratesxy, webdata); /* Loop over species, do differencing, load crate segment. */ #pragma omp parallel for default(shared) private(is, dcyli, dcyui, dcxli, dcxui) schedule(static) num_threads(webdata->nthreads) for (is = 0; is < NUM_SPECIES; is++) { /* Differencing in y. */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in x. */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxui = *(cxy + idxu +is) - *(cxy+is); /* Compute the crate values at (xx,yy). */ cratexy[is] = coy[is] * (dcyui - dcyli) + cox[is] * (dcxui - dcxli) + ratesxy[is]; } /* End is loop */ } /* End of jx loop */ } /* End of jy loop */ } /* * WebRates: Evaluate reaction rates at a given spatial point. * At a given (x,y), evaluate the array of ns reaction terms R. */ static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, UserData webdata) { int is; realtype fac; for (is = 0; is < NUM_SPECIES; is++) ratesxy[is] = dotprod(NUM_SPECIES, cxy, acoef[is]); fac = ONE + ALPHA*xx*yy + BETA*sin(FOURPI*xx)*sin(FOURPI*yy); for (is = 0; is < NUM_SPECIES; is++) ratesxy[is] = cxy[is]*( bcoef[is]*fac + ratesxy[is] ); } /* * dotprod: dot product routine for realtype arrays, for use by WebRates. */ static realtype dotprod(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns an integer value so check if * retval < 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_retval(void *returnvalue, char *funcname, int opt) { int *retval; if (opt == 0 && returnvalue == NULL) { /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } else if (opt == 1) { /* Check if retval < 0 */ retval = (int *) returnvalue; if (*retval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n", funcname, *retval); return(1); } } else if (opt == 2 && returnvalue == NULL) { /* Check if function returned NULL pointer - no memory allocated */ fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
GB_unop__atan_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__atan_fc64_fc64) // op(A') function: GB (_unop_tran__atan_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = catan (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = catan (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = catan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ATAN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__atan_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catan (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catan (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__atan_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *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
Parallel_update_simplicial.h
// // Created by kazem on 4/13/19. // #ifndef PROJECT_PARALLEL_UPDATE_SIMPLICIAL_H #define PROJECT_PARALLEL_UPDATE_SIMPLICIAL_H namespace nasoq { #include "omp.h" int update_ldl_parallel_left_simplicial_01(int n, int *c, int *r, double *values, int *cT, int *rT, int *lC, int *lR, double *&lValues, double *d, #if 0 int *prunePtr, int *pruneSet, #endif int *eTree, bool *marked, int nLevels, int *levelPtr, int nPar, int *parPtr, int *partition) { //ws n, ws_int size of 3*n /* * Performs a Cholesky decomposition on a given matrix (c, r, values), i.e. * stored in compressed column format, and produces L, which are * stored in column compressed format. * (n, c, r, values) : IN : input matrix * (lC, lR) : IN : The column and rwo sparsity patterns of L * (lValues) : OUT : the nonzero values of the L factor * (pruneSet, prunePtr) : IN : the row sparsity pattern of the factor L */ double *f; int *xi; omp_set_nested(1); for (int i1 = 0; i1 < nLevels; ++i1) { #pragma omp parallel private(f, xi) { #pragma omp for schedule(static) private(f, xi) for (int j1 = levelPtr[i1]; j1 < levelPtr[i1 + 1]; ++j1) { f = new double[n](); xi = new int[2 * n](); //int pls = levelSet[j1]; for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) { int colNo = partition[k1]; if (!marked[colNo]) continue; int spCol = 0; int top = 0; //emptying col colNo in L for (int k = lC[colNo]; k < lC[colNo + 1]; ++k) { lValues[k] = 0; } d[colNo] = 0; //Uncompress a col into a 1D array for (int nzNo = c[colNo]; nzNo < c[colNo + 1]; ++nzNo) { f[r[nzNo]] = values[nzNo];//Copying nonzero of the col } /*#if 0 for (int i = prunePtr[colNo]; i < prunePtr[colNo + 1]-1; ++i) { spCol = pruneSet[i]; #endif*/ top = ereach(n, cT, rT, colNo, eTree, xi, xi + n); //std::cout<<n-top<<";\n"; for (int i = top; i < n; ++i) { spCol = xi[i]; bool sw = false; double facing_val = 0, tmp = 0; int facing_idx = -1; for (int l = lC[spCol]; l < lC[spCol + 1]; ++l) { if (lR[l] == colNo) { facing_val = lValues[l]; tmp = facing_val * d[spCol]; facing_idx = l; break; } } assert(facing_idx >= 0); for (int l = facing_idx + 1; l < lC[spCol + 1]; ++l) { f[lR[l]] -= lValues[l] * tmp; } d[colNo] += facing_val * tmp; } d[colNo] = f[colNo] - d[colNo]; double diag = d[colNo]; //double tmpSqrt = sqrt(f[colNo]); f[colNo] = 0; lValues[lC[colNo]] = 1; for (int j = lC[colNo] + 1; j < lC[colNo + 1]; ++j) { lValues[j] = f[lR[j]] / diag; f[lR[j]] = 0; } /* std::cout<<" -> "<<colNo<<"\n"; for (int j = lC[colNo] + 1; j < lC[colNo+1]; ++j) { std::cout<<lValues[j]<<";"; } std::cout<<"\n";*/ } delete[]f; delete[]xi; } } } return 1; } } #endif //PROJECT_PARALLEL_UPDATE_SIMPLICIAL_H
QuadNodeCartesianEuclid.h
/* * QuadNodePolarEuclid.h * * Created on: 21.05.2014 * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu) * * Note: This is similar enough to QuadNode.h that one could merge these two classes. */ #ifndef QUADNODECARTESIANEUCLID_H_ #define QUADNODECARTESIANEUCLID_H_ #include <vector> #include <algorithm> #include <functional> #include <assert.h> #include "../../auxiliary/Log.h" #include "../../geometric/HyperbolicSpace.h" using std::vector; using std::min; using std::max; using std::cos; namespace NetworKit { template <class T> class QuadNodeCartesianEuclid { friend class QuadTreeGTest; private: Point<double> minPoint; Point<double> maxPoint; count dimension; unsigned capacity; static const unsigned coarsenLimit = 4; static const long unsigned sanityNodeLimit = 10E15; //just assuming, for debug purposes, that this algorithm never runs on machines with more than 4 Petabyte RAM count subTreeSize; std::vector<T> content; std::vector<Point<double> > positions; bool isLeaf; bool splitTheoretical; index ID; double lowerBoundR; public: std::vector<QuadNodeCartesianEuclid> children; /** * Construct a QuadNode for polar coordinates. * * * @param lower Minimal coordinates of region * @param upper Maximal coordinates of region (excluded) * @param capacity Number of points a leaf cell can store before splitting * @param splitTheoretical Whether to split in a theoretically optimal way or in a way to decrease measured running times * */ QuadNodeCartesianEuclid(Point<double> lower = Point<double>({0.0, 0.0}), Point<double> upper = Point<double>({1.0, 1.0}), unsigned capacity = 1000, bool splitTheoretical = false) { this->minPoint = lower; this->maxPoint = upper; this->dimension = minPoint.getDimensions(); assert(maxPoint.getDimensions() == dimension); this->capacity = capacity; this->splitTheoretical = splitTheoretical; this->ID = 0; isLeaf = true; subTreeSize = 0; } void split() { assert(isLeaf); assert(children.size() == 0); vector<double> middle(dimension); if (splitTheoretical) { //Euclidean space is distributed equally for (index d = 0; d < dimension; d++) { middle[d] = (minPoint[d] + maxPoint[d]) / 2; } } else { //median of points const count numPoints = positions.size(); assert(numPoints > 0);//otherwise, why split? vector<vector<double> > sorted(dimension); for (index d = 0; d < dimension; d++) { sorted[d].resize(numPoints); for (index i = 0; i < numPoints; i++) { sorted[d][i] = positions[i][d]; } std::sort(sorted[d].begin(), sorted[d].end()); middle[d] = sorted[d][numPoints/2];//this will crash if no points are there! assert(middle[d] <= maxPoint[d]); assert(middle[d] >= minPoint[d]); } } count childCount = pow(2,dimension); for (index i = 0; i < childCount; i++) { vector<double> lowerValues(dimension); vector<double> upperValues(dimension); index bitCopy = i; for (index d = 0; d < dimension; d++) { if (bitCopy & 1) { lowerValues[d] = middle[d]; upperValues[d] = maxPoint[d]; } else { lowerValues[d] = minPoint[d]; upperValues[d] = middle[d]; } bitCopy = bitCopy >> 1; } QuadNodeCartesianEuclid child(Point<double>(lowerValues), Point<double>(upperValues), capacity, splitTheoretical); assert(child.isLeaf); children.push_back(child); } isLeaf = false; } /** * Add a point at polar coordinates (angle, R) with content input. May split node if capacity is full * * @param input arbitrary content, in our case an index * @param angle angular coordinate of point, between 0 and 2 pi. * @param R radial coordinate of point, between 0 and 1. */ void addContent(T input, Point<double> pos) { assert(input < sanityNodeLimit); assert(content.size() == positions.size()); assert(this->responsible(pos)); if (isLeaf) { if (content.size() + 1 < capacity) { content.push_back(input); positions.push_back(pos); } else { split(); for (index i = 0; i < content.size(); i++) { this->addContent(content[i], positions[i]); } assert(subTreeSize == content.size());//we have added everything twice subTreeSize = content.size(); content.clear(); positions.clear(); this->addContent(input, pos); } } else { assert(children.size() > 0); bool foundResponsibleChild = false; for (index i = 0; i < children.size(); i++) { if (children[i].responsible(pos)) { foundResponsibleChild = true; children[i].addContent(input, pos); break; } } assert(foundResponsibleChild); subTreeSize++; } } /** * Remove content at coordinate pos. May cause coarsening of the quadtree * * @param input Content to be removed * @param pos Coordinate of content * * @return True if content was found and removed, false otherwise */ bool removeContent(T input, Point<double> pos) { if (!responsible(pos)) return false; if (isLeaf) { index i = 0; for (; i < content.size(); i++) { if (content[i] == input) break; } if (i < content.size()) { assert(positions[i].distance(pos) == 0); //remove element content.erase(content.begin()+i); positions.erase(positions.begin()+i); return true; } else { return false; } } else { bool removed = false; bool allLeaves = true; assert(children.size() > 0); for (index i = 0; i < children.size(); i++) { if (!children[i].isLeaf) allLeaves = false; if (children[i].removeContent(input, pos)) { assert(!removed); removed = true; } } if (removed) subTreeSize--; //coarsen? if (removed && allLeaves && size() < coarsenLimit) { //coarsen!! //why not assert empty containers and then insert directly? vector<T> allContent; vector<Point<double> > allPositions; for (index i = 0; i < children.size(); i++) { allContent.insert(allContent.end(), children[i].content.begin(), children[i].content.end()); allPositions.insert(allPositions.end(), children[i].positions.begin(), children[i].positions.end()); } assert(allContent.size() == allPositions.size()); children.clear(); content.swap(allContent); positions.swap(allPositions); isLeaf = true; } return removed; } } /** * Check whether the region managed by this node lies outside of an Euclidean circle. * * @param query Center of the Euclidean query circle, given in Cartesian coordinates * @param radius Radius of the Euclidean query circle * * @return True if the region managed by this node lies completely outside of the circle */ bool outOfReach(Point<double> query, double radius) const { return EuclideanDistances(query).first > radius; } /** * @param query Position of the query point */ std::pair<double, double> EuclideanDistances(Point<double> query) const { /** * If the query point is not within the quadnode, the distance minimum is on the border. * Need to check whether extremum is between corners. */ double maxDistance = 0; double minDistance = std::numeric_limits<double>::max(); //Point<double> minCopy(minPoint); //Point<double> maxCopy(minPoint); if (responsible(query)) minDistance = 0; auto updateMinMax = [&minDistance, &maxDistance, query](Point<double> pos){ double extremalValue = pos.distance(query); maxDistance = std::max(extremalValue, maxDistance); minDistance = std::min(minDistance, extremalValue); }; vector<double> closestValues(dimension); vector<double> farthestValues(dimension); for (index d = 0; d < dimension; d++) { if (std::abs(query[d] - minPoint.at(d)) < std::abs(query[d] - maxPoint.at(d))) { closestValues[d] = minPoint.at(d); farthestValues[d] = maxPoint.at(d); } else { farthestValues[d] = minPoint.at(d); closestValues[d] = maxPoint.at(d); } if (query[d] >= minPoint.at(d) && query[d] <= maxPoint.at(d)) { closestValues[d] = query[d]; } } updateMinMax(Point<double>(closestValues)); updateMinMax(Point<double>(farthestValues)); assert(minDistance < query.length() + maxPoint.length()); assert(minDistance < maxDistance); return std::pair<double, double>(minDistance, maxDistance); } /** * Does the point at (angle, r) fall inside the region managed by this QuadNode? * * @param angle Angular coordinate of input point * @param r Radial coordinate of input points * * @return True if input point lies within the region of this QuadNode */ bool responsible(Point<double> pos) const { for (index d = 0; d < dimension; d++) { if (pos[d] < minPoint.at(d) || pos[d] >= maxPoint.at(d)) return false; } return true; } /** * Get all Elements in this QuadNode or a descendant of it * * @return vector of content type T */ std::vector<T> getElements() const { if (isLeaf) { return content; } else { assert(content.size() == 0); assert(positions.size() == 0); vector<T> result; for (index i = 0; i < children.size(); i++) { std::vector<T> subresult = children[i].getElements(); result.insert(result.end(), subresult.begin(), subresult.end()); } return result; } } void getCoordinates(vector<Point<double> > &pointContainer) const { if (isLeaf) { pointContainer.insert(pointContainer.end(), positions.begin(), positions.end()); } else { assert(content.size() == 0); assert(positions.size() == 0); for (index i = 0; i < children.size(); i++) { children[i].getCoordinates(pointContainer); } } } /** * Main query method, get points lying in a Euclidean circle around the center point. * Optional limits can be given to get a different result or to reduce unnecessary comparisons * * Elements are pushed onto a vector which is a required argument. This is done to reduce copying. * (Maybe not necessary due to copy elisison) * * Safe to call in parallel. * * @param center Center of the query circle * @param radius Radius of the query circle * @param result Reference to the vector where the results will be stored * @param minAngle Optional value for the minimum angular coordinate of the query region * @param maxAngle Optional value for the maximum angular coordinate of the query region * @param lowR Optional value for the minimum radial coordinate of the query region * @param highR Optional value for the maximum radial coordinate of the query region */ void getElementsInEuclideanCircle(Point<double> center, double radius, vector<T> &result) const { if (outOfReach(center, radius)) { return; } if (isLeaf) { const double rsq = radius*radius; const count cSize = content.size(); for (int i=0; i < cSize; i++) { if (positions[i].squaredDistance(center) < rsq) { result.push_back(content[i]); if (content[i] >= sanityNodeLimit) DEBUG("Quadnode content ", content[i], " found, suspiciously high!"); assert(content[i] < sanityNodeLimit); } } } else { for (index i = 0; i < children.size(); i++) { children[i].getElementsInEuclideanCircle(center, radius, result); } } } count getElementsProbabilistically(Point<double> euQuery, std::function<double(double)> prob, vector<T> &result) const { TRACE("Getting Euclidean distances"); auto distancePair = EuclideanDistances(euQuery); double probUB = prob(distancePair.first); double probLB = prob(distancePair.second); assert(probLB <= probUB); if (probUB > 0.5) probUB = 1; if (probUB == 0) return 0; //TODO: return whole if probLB == 1 double probdenom = std::log(1-probUB); if (probdenom == 0) return 0;//there is a very small probability, but we cannot process it. TRACE("probUB: ", probUB, ", probdenom: ", probdenom); count expectedNeighbours = probUB*size(); count candidatesTested = 0; count incomingNeighbours = result.size(); count ownsize = size(); if (isLeaf) { const count lsize = content.size(); TRACE("Leaf of size ", lsize); for (int i = 0; i < lsize; i++) { //jump! if (probUB < 1) { double random = Aux::Random::real(); double delta = std::log(random) / probdenom; assert(delta >= 0); i += delta; if (i >= lsize) break; TRACE("Jumped with delta ", delta, " arrived at ", i); } assert(i >= 0); //see where we've arrived candidatesTested++; double distance = positions[i].distance(euQuery); assert(distance >= distancePair.first);//TODO: These should not fail! assert(distance <= distancePair.second); double q = prob(distance); q = q / probUB; //since the candidate was selected by the jumping process, we have to adjust the probabilities assert(q <= 1); //accept? double acc = Aux::Random::real(); if (acc < q) { TRACE("Accepted node ", i, " with probability ", q, "."); result.push_back(content[i]); } } } else { if (expectedNeighbours < 4 || probUB < 1/1000) {//select candidates directly instead of calling recursively TRACE("probUB = ", probUB, ", switching to direct candidate selection."); assert(probUB < 1); const count stsize = size(); for (index i = 0; i < stsize; i++) { double delta = std::log(Aux::Random::real()) / probdenom; assert(delta >= 0); i += delta; TRACE("Jumped with delta ", delta, " arrived at ", i, ". Calling maybeGetKthElement."); if (i < size()) maybeGetKthElement(probUB, euQuery, prob, i, result);//this could be optimized. As of now, the offset is subtracted separately for each point else break; candidatesTested++; } } else {//carry on as normal for (index i = 0; i < children.size(); i++) { TRACE("Recursively calling child ", i); candidatesTested += children[i].getElementsProbabilistically(euQuery, prob, result); } } } count finalNeighbours = result.size(); if (probLB == 1) assert(finalNeighbours == incomingNeighbours + ownsize); return candidatesTested; } void maybeGetKthElement(double upperBound, Point<double> euQuery, std::function<double(double)> prob, index k, vector<T> &circleDenizens) const { TRACE("Maybe get element ", k, " with upper Bound ", upperBound); assert(k < size()); if (isLeaf) { double acceptance = prob(euQuery.distance(positions[k]))/upperBound; TRACE("Is leaf, accept with ", acceptance); if (Aux::Random::real() < acceptance) circleDenizens.push_back(content[k]); } else { TRACE("Call recursively."); index offset = 0; for (index i = 0; i < children.size(); i++) { count childsize = children[i].size(); if (k - offset < childsize) { children[i].maybeGetKthElement(upperBound, euQuery, prob, k - offset, circleDenizens); break; } offset += childsize; } } } /** * Shrink all vectors in this subtree to fit the content. * Call after quadtree construction is complete, causes better memory usage and cache efficiency */ void trim() { content.shrink_to_fit(); positions.shrink_to_fit(); if (!isLeaf) { for (index i = 0; i < children.size(); i++) { children[i].trim(); } } } /** * Number of points lying in the region managed by this QuadNode */ count size() const { return isLeaf ? content.size() : subTreeSize; } void recount() { subTreeSize = 0; for (index i = 0; i < children.size(); i++) { children[i].recount(); subTreeSize += children[i].size(); } } /** * Height of subtree hanging from this QuadNode */ count height() const { count result = 1;//if leaf node, the children loop will not execute for (auto child : children) result = std::max(result, child.height()+1); return result; } /** * Leaf cells in the subtree hanging from this QuadNode */ count countLeaves() const { if (isLeaf) return 1; count result = 0; for (index i = 0; i < children.size(); i++) { result += children[i].countLeaves(); } return result; } index getID() const { return ID; } index indexSubtree(index nextID) { index result = nextID; assert(children.size() == pow(2,dimension) || children.size() == 0); for (int i = 0; i < children.size(); i++) { result = children[i].indexSubtree(result); } this->ID = result; return result+1; } index getCellID(Point<double> pos) const { if (!responsible(pos)) return -1; if (isLeaf) return getID(); else { for (int i = 0; i < children.size(); i++) { index childresult = children[i].getCellID(pos); if (childresult >= 0) return childresult; } assert(false); //if responsible return -1; } } index getMaxIDInSubtree() const { if (isLeaf) return getID(); else { index result = -1; for (int i = 0; i < children.size(); i++) { result = std::max(children[i].getMaxIDInSubtree(), result); } return std::max(result, getID()); } } count reindex(count offset) { if (isLeaf) { #pragma omp task { index p = offset; std::generate(content.begin(), content.end(), [&p](){return p++;}); } offset += size(); } else { for (int i = 0; i < children.size(); i++) { offset = children[i].reindex(offset); } } return offset; } }; } #endif /* QUADNODE_H_ */
GB_unaryop__minv_int8_bool.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_int8_bool // op(A') function: GB_tran__minv_int8_bool // C type: int8_t // A type: bool // cast: int8_t cij = (int8_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ bool #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 8) ; // casting #define GB_CASTING(z, x) \ int8_t z = (int8_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_MINV || GxB_NO_INT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int8_bool ( int8_t *restrict Cx, const bool *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_int8_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
traversal.h
#ifndef TRAVERSAL_H_ #define TRAVERSAL_H_ #include "types.h" #include "adListShared.h" #include "stinger.h" #include "darhh.h" #include "adListChunked.h" #include "GraphTango.h" #include "Vertex.h" #include "topDataStruc.h" template<typename T> class neighborhood; template<typename T> class neighborhood_iter { public: neighborhood_iter(T *ds, NodeID n, bool in_neigh); bool operator!=(neighborhood_iter &it); neighborhood_iter& operator++(); neighborhood_iter& operator++(int); NodeID operator*(); Weight extractWeight(); }; template<typename U> class neighborhood_iter<GraphTango<U>> { friend class neighborhood<GraphTango<U>> ; private: U* cursor; public: neighborhood_iter(U* _cursor) { cursor = _cursor; } bool operator!=(const neighborhood_iter<GraphTango<U>> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { #ifdef CALC_EDGE_TOUCHED #pragma omp atomic g_edge_touched++; #endif cursor++; return *this; } neighborhood_iter& operator++(int) { #ifdef CALC_EDGE_TOUCHED #pragma omp atomic g_edge_touched++; #endif cursor++; return *this; } NodeID operator*() { return cursor->getNodeID(); } Weight extractWeight() { return cursor->getWeight(); } }; template<typename U> class neighborhood_iter<adList<U>> { friend class neighborhood<adList<U>> ; private: adList<U> *ds; NodeID node; bool in_neigh; U *cursor; public: neighborhood_iter(adList<U> *_ds, NodeID _n, bool _in_neigh) : ds(_ds), node(_n), in_neigh(_in_neigh) { if (in_neigh) { bool empty = ds->in_neighbors[node].empty(); cursor = empty ? 0 : &(ds->in_neighbors[node][0]); } else { bool empty = ds->out_neighbors[node].empty(); cursor = empty ? 0 : &(ds->out_neighbors[node][0]); } } bool operator!=(const neighborhood_iter<adList<U>> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { if (in_neigh) { int size_in_neigh = ds->in_neighbors[node].size(); if (cursor == &(ds->in_neighbors[node][size_in_neigh - 1])) { cursor = nullptr; } else cursor = cursor + 1; } else { int size_out_neigh = ds->out_neighbors[node].size(); if (cursor == &(ds->out_neighbors[node][size_out_neigh - 1])) { cursor = nullptr; } else cursor = cursor + 1; } return *this; } neighborhood_iter& operator++(int) { if (in_neigh) { int size_in_neigh = ds->in_neighbors[node].size(); if (cursor == &(ds->in_neighbors[node][size_in_neigh - 1])) { cursor = nullptr; } else cursor = cursor + 1; } else { int size_out_neigh = ds->out_neighbors[node].size(); if (cursor == &(ds->out_neighbors[node][size_out_neigh - 1])) { cursor = nullptr; } else cursor = cursor + 1; } return *this; } NodeID operator*() { return cursor->getNodeID(); } Weight extractWeight() { return cursor->getWeight(); } }; template<typename U> class neighborhood_iter<adListShared<U>> { friend class neighborhood<adListShared<U>> ; private: U *cursor; U *endPtr; public: neighborhood_iter(adListShared<U> *ds, NodeID node, bool in_neigh) { cursor = nullptr; endPtr = nullptr; if(in_neigh){ const int sz = ds->in_neighbors[node].size(); if(sz){ cursor = &(ds->in_neighbors[node][0]); endPtr = cursor + sz; } } else{ const int sz = ds->out_neighbors[node].size(); if(sz){ cursor = &(ds->out_neighbors[node][0]); endPtr = cursor + sz; } } while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return; } cursor++; } cursor = nullptr; endPtr = nullptr; } bool operator!=(const neighborhood_iter<adListShared<U>> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { cursor++; while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return *this; } cursor++; } cursor = nullptr; return *this; } neighborhood_iter& operator++(int) { cursor++; while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return *this; } cursor++; } cursor = nullptr; return *this; } NodeID operator*() { return cursor->getNodeID(); } Weight extractWeight() { return cursor->getWeight(); } }; /* //specialization for stinger ---- OLD template<> class neighborhood_iter<stinger> { friend class neighborhood<stinger> ; private: stinger *ds; NodeID node; bool in_neigh; stinger_edge *cursor; stinger_eb *curr_eb; stinger_vertex *sv; int cursor_index; public: neighborhood_iter(stinger *_ds, NodeID _n, bool _in_neigh) : ds(_ds), node(_n), in_neigh(_in_neigh) { sv = &(ds->vertices[node]); if (in_neigh) { bool empty = (sv->in_neighbors->numEdges == 0); cursor = empty ? 0 : &(sv->in_neighbors->edges[0]); curr_eb = sv->in_neighbors; if (!empty) cursor_index = 0; } else { bool empty = (sv->out_neighbors->numEdges == 0); cursor = empty ? 0 : &(sv->out_neighbors->edges[0]); curr_eb = sv->out_neighbors; if (!empty) cursor_index = 0; } } bool operator!=(const neighborhood_iter<stinger> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { // just increment by 1 if we are in an edgeblock and more edges left if (cursor_index < (curr_eb->numEdges - 1)) { cursor = cursor + 1; cursor_index++; } else if (cursor_index == (curr_eb->numEdges - 1)) { // We are done with current edgeblock if (curr_eb->next != nullptr) { // move to next one, if there is one curr_eb = curr_eb->next; cursor = &(curr_eb->edges[0]); cursor_index = 0; } else { // there is no further, end of traversal cursor = nullptr; } } return *this; } neighborhood_iter& operator++(int) { // just increment by 1 if we are in an edgeblock and more edges left if (cursor_index < (curr_eb->numEdges - 1)) { cursor = cursor + 1; cursor_index++; } else if (cursor_index == (curr_eb->numEdges - 1)) { // We are done with current edgeblock if (curr_eb->next != nullptr) { // move to next one, if there is one curr_eb = curr_eb->next; cursor = &(curr_eb->edges[0]); cursor_index = 0; } else { // there is no further, end of traversal cursor = nullptr; } } return *this; } NodeID operator*() { assert(cursor->neighbor != -1); return cursor->neighbor; } Weight extractWeight() { return cursor->weight; } }; */ //specialization for stinger ---- NEW template<> class neighborhood_iter<stinger> { friend class neighborhood<stinger> ; private: //stinger *ds; //NodeID node; //bool in_neigh; stinger_edge *cursor; stinger_eb *curr_eb; int cursor_index; //stinger_vertex *sv; public: neighborhood_iter(stinger *_ds, NodeID _n, bool _in_neigh) { stinger_vertex* sv = &(_ds->vertices[_n]); if (_in_neigh) { curr_eb = sv->in_neighbors; } else{ curr_eb = sv->out_neighbors; } cursor_index = 0; //find first edge while(curr_eb){ while(cursor_index < curr_eb->high){ if(curr_eb->edges[cursor_index].neighbor >= 0){ cursor = curr_eb->edges + cursor_index; return; } cursor_index++; } cursor_index = 0; curr_eb = curr_eb->next; } cursor = nullptr; } bool operator!=(const neighborhood_iter<stinger> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { while(curr_eb){ cursor_index++; while(cursor_index < curr_eb->high){ if(curr_eb->edges[cursor_index].neighbor >= 0){ //valid edge (otherwise deleted) cursor = curr_eb->edges + cursor_index; return *this; } cursor_index++; } cursor_index = 0; curr_eb = curr_eb->next; } cursor = nullptr; return *this; } neighborhood_iter& operator++(int) { while(curr_eb){ cursor_index++; while(cursor_index < curr_eb->high){ if(curr_eb->edges[cursor_index].neighbor >= 0){ //valid edge (otherwise deleted) cursor = curr_eb->edges + cursor_index; return *this; } cursor_index++; } cursor_index = 0; curr_eb = curr_eb->next; } cursor = nullptr; return *this; } NodeID operator*() { //assert(cursor->neighbor != -1); return cursor->neighbor; } Weight extractWeight() { return cursor->weight; } }; //// // ------------------------------adList_chunk---------------------------------- OLD //template<typename U> //class neighborhood_iter<adListChunked<U>> { // friend class neighborhood<adListChunked<U>> ; //private: // adListChunked<U> *ds; // NodeID node; // bool in_neigh; // U *cursor; // // int64_t part_idx; // int64_t sub_idx; // //public: // neighborhood_iter(adListChunked<U> *_ds, NodeID _n, bool _in_neigh) : // ds(_ds), node(_n), in_neigh(_in_neigh) { // // part_idx = _n % (ds->num_partitions); // // sub_idx = (int) _n/(ds->num_partitions); // part_idx = ds->pt_hash(_n); // sub_idx = ds->hash_within_chunk(_n); // if (in_neigh) { // bool empty = ds->in[part_idx]->partAdList->neighbors[sub_idx].empty(); // cursor = empty ? nullptr : &(ds->in[part_idx]->partAdList->neighbors[sub_idx][0]); // } else { // bool empty = ds->out[part_idx]->partAdList->neighbors[sub_idx].empty(); // cursor = empty ? nullptr : &(ds->out[part_idx]->partAdList->neighbors[sub_idx][0]); // } // } // // bool operator!=(const neighborhood_iter<adListChunked<U>> &it) { // return cursor != it.cursor; // } // // neighborhood_iter& operator++() { // if (in_neigh) { // int size_in_neigh = ds->in[part_idx]->partAdList->neighbors[sub_idx].size(); // if (cursor == &(ds->in[part_idx]->partAdList->neighbors[sub_idx][size_in_neigh - 1])) // cursor = nullptr; // else // cursor = cursor + 1; // } else { // int size_out_neigh = ds->out[part_idx]->partAdList->neighbors[sub_idx].size(); // if (cursor == &(ds->out[part_idx]->partAdList->neighbors[sub_idx][size_out_neigh - 1])) // cursor = nullptr; // else // cursor = cursor + 1; // } // // return *this; // } // // neighborhood_iter& operator++(int) { // if (in_neigh) { // int size_in_neigh = ds->in[part_idx]->partAdList->neighbors[sub_idx].size(); // if (cursor == &(ds->in[part_idx]->partAdList->neighbors[sub_idx][size_in_neigh - 1])) // cursor = nullptr; // else // cursor = cursor + 1; // } else { // int size_out_neigh = ds->out[part_idx]->partAdList->neighbors[sub_idx].size(); // if (cursor == &(ds->out[part_idx]->partAdList->neighbors[sub_idx][size_out_neigh - 1])) // cursor = nullptr; // else // cursor = cursor + 1; // } // // return *this; // } // // NodeID operator*() { // return cursor->getNodeID(); // } // // Weight extractWeight() { // return cursor->getWeight(); // } //}; // ------------------------------adList_chunk---------------------------------- NEW template<typename U> class neighborhood_iter<adListChunked<U>> { friend class neighborhood<adListChunked<U>> ; private: U *cursor; U *endPtr; public: neighborhood_iter(adListChunked<U> *ds, NodeID node, bool in_neigh) { cursor = nullptr; endPtr = nullptr; int64_t part_idx = ds->pt_hash(node); int64_t sub_idx = ds->hash_within_chunk(node); if(in_neigh){ const int sz = ds->in[part_idx]->partAdList->neighbors[sub_idx].size(); if(sz){ cursor = &(ds->in[part_idx]->partAdList->neighbors[sub_idx][0]); endPtr = cursor + sz; } } else{ const int sz = ds->out[part_idx]->partAdList->neighbors[sub_idx].size(); if(sz){ cursor = &( ds->out[part_idx]->partAdList->neighbors[sub_idx][0]); endPtr = cursor + sz; } } while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return; } cursor++; } cursor = nullptr; endPtr = nullptr; } bool operator!=(const neighborhood_iter<adListChunked<U>> &it) { return cursor != it.cursor; } neighborhood_iter& operator++() { cursor++; while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return *this; } cursor++; } cursor = nullptr; return *this; } neighborhood_iter& operator++(int) { cursor++; while(cursor < endPtr){ if(cursor->node >= 0){ //found a valid node return *this; } cursor++; } cursor = nullptr; return *this; } NodeID operator*() { return cursor->getNodeID(); } Weight extractWeight() { return cursor->getWeight(); } }; template<typename U> class neighborhood_iter<darhh<U>> { friend class neighborhood<darhh<U>> ; private: hd_rhh<U> *hd; ld_rhh<U> *ld; typename hd_rhh<U>::iter hd_iter; typename ld_rhh<U>::iter ld_iter; bool low_degree; public: inline neighborhood_iter& operator=(neighborhood_iter const &it); inline bool operator!=(neighborhood_iter const &it); neighborhood_iter& operator++(); neighborhood_iter& operator++(int); inline NodeID operator*(); inline Weight extractWeight(); void set_begin(darhh<U> *ds, NodeID n, bool in); void set_end(); }; template<typename U> void neighborhood_iter<darhh<U>>::set_begin(darhh<U> *ds, NodeID src, bool in) { if (in) { ld = ds->in[ds->pt_hash(src)]->ld; hd = ds->in[ds->pt_hash(src)]->hd; } else { ld = ds->out[ds->pt_hash(src)]->ld; hd = ds->out[ds->pt_hash(src)]->hd; } low_degree = ld->get_degree(src); if (low_degree) ld_iter = ld->begin(src); else hd_iter = hd->begin(src); } template<typename U> void neighborhood_iter<darhh<U>>::set_end() { ld_iter.cursor = nullptr; hd_iter.cursor = nullptr; } template<typename U> neighborhood_iter<darhh<U>>& neighborhood_iter<darhh<U>>::operator=(neighborhood_iter const &other) { hd = other.hd; ld = other.ld; hd_iter = other.hd_iter; ld_iter = other.ld_iter; low_degree = other.low_degree; return *this; } template<typename U> bool neighborhood_iter<darhh<U>>::operator!=(neighborhood_iter const &it) { if (low_degree) return ld_iter != it.ld_iter; else return hd_iter != it.hd_iter; } template<typename U> neighborhood_iter<darhh<U>>& neighborhood_iter<darhh<U>>::operator++() { if (low_degree) ++ld_iter; else ++hd_iter; return *this; } template<typename U> neighborhood_iter<darhh<U>>& neighborhood_iter<darhh<U>>::operator++(int) { if (low_degree) ++ld_iter; else ++hd_iter; return *this; } template<typename U> NodeID neighborhood_iter<darhh<U>>::operator*() { if (low_degree) return ld_iter.cursor->getNodeID(); else return hd_iter.cursor->getNodeID(); } template<typename U> Weight neighborhood_iter<darhh<U>>::extractWeight() { if (low_degree) return ld_iter.cursor->getWeight(); else return hd_iter.cursor->getWeight(); } template<typename T> class neighborhood { private: T *ds; NodeID node; bool in_neigh; public: neighborhood(NodeID _node, T *_ds, bool _in_neigh) : ds(_ds), node(_node), in_neigh(_in_neigh) { } neighborhood_iter<T> begin() { return neighborhood_iter<T>(ds, node, in_neigh); } neighborhood_iter<T> end() { neighborhood_iter<T> n = neighborhood_iter<T>(ds, node, in_neigh); n.cursor = nullptr; return n; } }; //#if defined(USE_HYBRID_HASHMAP_WITH_GROUPING) \ // || defined(USE_HYBRID_HASHMAP_WITH_GROUPING_AND_EDGE_ARR_LOCKING) \ // || defined(USE_HYBRID_HASHMAP_WITH_GROUPING_TIGHTER) #if defined(USE_CAHCE_FRIENDLY_HASH_ONLY) template<typename U> class neighborhood<GraphTango<U>> { private: U* _start; uint64_t _size; public: neighborhood(NodeID _node, GraphTango<U> *_ds, bool _in_neigh) { Vertex<U> &v = _ds->vArray[_node]; if(_in_neigh){ GraphTangoHash<U> &edges = v.inEdges; _size = edges.degree; if(edges.adjList == nullptr){ //create adjacency list from hash table edges.adjList = (U*)globalAllocator.allocate(_size * sizeof(U)); u32 idx = 0; const u32 cap = edges.capacity; for(u32 j = 0; j < cap; j++){ if(edges.neighArr[j].node < FLAG_TOMB_STONE){ edges.adjList[idx++] = edges.neighArr[j]; } } //assert(idx == _size); } _start = edges.adjList; } else{ GraphTangoHash<U> &edges = v.outEdges; _size = edges.degree; if(edges.adjList == nullptr){ //create adjacency list from hash table edges.adjList = (U*)globalAllocator.allocate(_size * sizeof(U)); u32 idx = 0; const u32 cap = edges.capacity; for(u32 j = 0; j < cap; j++){ if(edges.neighArr[j].node < FLAG_TOMB_STONE){ edges.adjList[idx++] = edges.neighArr[j]; } } //assert(idx == _size); } _start = edges.adjList; } } neighborhood_iter<GraphTango<U>> begin() { return neighborhood_iter<GraphTango<U>>(_start); } neighborhood_iter<GraphTango<U>> end() { return neighborhood_iter<GraphTango<U>>(_start + _size); } }; #elif defined(USE_HYBRID_HASHMAP_WITH_GROUPING) \ || defined(USE_HYBRID_HASHMAP_WITH_GROUPING_AND_EDGE_ARR_LOCKING) \ || defined(USE_HYBRID_HASHMAP_WITH_GROUPING_TIGHTER) \ || defined(USE_GT_BALANCED_TYPE3_ONLY) template<typename U> class neighborhood<GraphTango<U>> { private: U* _start; uint64_t _size; public: neighborhood(NodeID _node, GraphTango<U> *_ds, bool _in_neigh) { if(_in_neigh){ _start = _ds->vArray[_node].inEdges.neighArr; _size = _ds->vArray[_node].inEdges.degree; } else{ _start = _ds->vArray[_node].outEdges.neighArr; _size = _ds->vArray[_node].outEdges.degree; } } neighborhood_iter<GraphTango<U>> begin() { return neighborhood_iter<GraphTango<U>>(_start); } neighborhood_iter<GraphTango<U>> end() { return neighborhood_iter<GraphTango<U>>(_start + _size); } }; #elif defined(USE_GT_BALANCED) \ || defined(USE_GT_BALANCED_MALLOC) \ || defined(USE_GT_BALANCED_STDMAP) \ || defined(USE_GT_BALANCED_MALLOC_STDMAP) \ || defined(USE_GT_BALANCED_DYN_PARTITION) \ || defined(USE_GT_BALANCED_ABSEIL) \ || defined(USE_GT_BALANCED_RHH) \ || defined(USE_GT_BALANCED_TSL_RHH) template<typename U> class neighborhood<GraphTango<U>> { private: U* _start; uint64_t _size; public: neighborhood(NodeID _node, GraphTango<U> *_ds, bool _in_neigh) { if(_in_neigh){ if(_ds->vArray[_node].inEdges.capacity <= EdgeArray<U>::TH0){ _start = _ds->vArray[_node].inEdges.etype.type1.neigh; } else{ _start = _ds->vArray[_node].inEdges.etype.type2_3.neighArr; } _size = _ds->vArray[_node].inEdges.degree; } else{ if(_ds->vArray[_node].outEdges.capacity <= EdgeArray<U>::TH0){ _start = _ds->vArray[_node].outEdges.etype.type1.neigh; } else{ _start = _ds->vArray[_node].outEdges.etype.type2_3.neighArr; } _size = _ds->vArray[_node].outEdges.degree; } } neighborhood_iter<GraphTango<U>> begin() { return neighborhood_iter<GraphTango<U>>(_start); } neighborhood_iter<GraphTango<U>> end() { return neighborhood_iter<GraphTango<U>>(_start + _size); } }; #elif defined(USE_GT_UPDATE) #else template<typename U> class neighborhood<GraphTango<U>> { private: U* _start; uint64_t _size; public: neighborhood(NodeID _node, GraphTango<U> *_ds, bool _in_neigh) { if(_in_neigh){ _start = _ds->vArray.inNeighArr[_node]; _size = _ds->vArray.inDegree[_node]; } else{ _start = _ds->vArray.outNeighArr[_node]; _size = _ds->vArray.outDegree[_node]; } } neighborhood_iter<GraphTango<U>> begin() { // #pragma omp atomic // g_totalEdges += _size; return neighborhood_iter<GraphTango<U>>(_start); } neighborhood_iter<GraphTango<U>> end() { return neighborhood_iter<GraphTango<U>>(_start + _size); } }; #endif template<typename U> class neighborhood<darhh<U>> { private: using iter = neighborhood_iter<darhh<U>>; NodeID src; darhh<U> *ds; bool in; public: neighborhood(NodeID src, darhh<U> *ds, bool in) : src(src), ds(ds), in(in) { } iter begin() { iter it; it.set_begin(ds, src, in); return it; } iter end() { iter it; it.set_end(); return it; } }; template<typename T> neighborhood<T> in_neigh(NodeID n, T *ds) { if (ds->directed) return neighborhood<T>(n, ds, true); else return neighborhood<T>(n, ds, false); } template<typename T> neighborhood<T> out_neigh(NodeID n, T *ds) { return neighborhood<T>(n, ds, false); } #endif // TRAVERSAL_H_
tasks.c
/* testing omp constructs to represents tasks https://www.openmp.org//wp-content/uploads/sc13.tasking.ruud.pdf compile: $ clang tasks.c -fopenmp=libomp -o tasks */ #include <stdio.h> #include <unistd.h> void task1(){ int i=0; while(1){ printf("task1 - %d\n", i); i++; sleep(5); } } void task2(){ int i=0; while(1){ printf("task2 - %d\n", i); i++; sleep(4); } } int main(int argc, char *argv[]) { #pragma omp parallel { #pragma omp single { printf("A "); #pragma omp task { //printf("car "); task2(); } #pragma omp task { //printf("race "); task1(); } #pragma omp taskwait printf("is fun to watch "); } } // End of parallel region printf("\n"); return(0); }
thd_info.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "thd_info.h" /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ /** * @brief Perform a parallel SUM reduction. * * @param thds The data we are reducing (one array for each thread). * @param buffer thread-local buffer. * @param nelems How many elements in the scratch array. */ static void p_reduce_sum( val_t * * reduce_ptrs, val_t * buffer, idx_t const nelems) { int const tid = splatt_omp_get_thread_num(); int const nthreads = splatt_omp_get_num_threads(); int half = nthreads / 2; while(half > 0) { if(tid < half && tid + half < nthreads) { val_t const * const target = reduce_ptrs[tid+half]; for(idx_t i=0; i < nelems; ++i) { buffer[i] += target[i]; } } #pragma omp barrier /* check for odd number */ #pragma omp master if(half > 1 && half % 2 == 1) { val_t const * const last = reduce_ptrs[half-1]; for(idx_t i=0; i < nelems; ++i) { buffer[i] += last[i]; } } /* next iteration */ half /= 2; } /* account for odd thread at end */ #pragma omp master { if(nthreads % 2 == 1) { val_t const * const last = reduce_ptrs[nthreads-1]; for(idx_t i=0; i < nelems; ++i) { buffer[i] += last[i]; } } } } /** * @brief Perform a parallel MAX reduction. * * @param thds The data we are reducing (one array for each thread). * @param buffer thread-local buffer. * @param nelems How many elements in the scratch array. */ static void p_reduce_max( val_t * * reduce_ptrs, val_t * buffer, idx_t const nelems) { int const tid = splatt_omp_get_thread_num(); int const nthreads = splatt_omp_get_num_threads(); int half = nthreads / 2; while(half > 0) { if(tid < half && tid + half < nthreads) { val_t const * const target = reduce_ptrs[tid+half]; for(idx_t i=0; i < nelems; ++i) { buffer[i] = SS_MAX(buffer[i], target[i]); } } #pragma omp barrier /* check for odd number */ #pragma omp master if(half > 1 && half % 2 == 1) { val_t const * const last = reduce_ptrs[half-1]; for(idx_t i=0; i < nelems; ++i) { buffer[i] = SS_MAX(buffer[i], last[i]); } } /* next iteration */ half /= 2; } /* account for odd thread at end */ #pragma omp master { if(nthreads % 2 == 1) { val_t const * const last = reduce_ptrs[nthreads-1]; for(idx_t i=0; i < nelems; ++i) { buffer[i] = SS_MAX(buffer[i], last[i]); } } } } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ void thread_allreduce( val_t * const buffer, idx_t const nelems, splatt_reduce_type const which) { int const tid = splatt_omp_get_thread_num(); int const nthreads = splatt_omp_get_num_threads(); /* used to get coherent all-to-all access to reduction data. */ static val_t ** reduce_ptrs; if(nthreads == 1) { return; } /* get access to all thread pointers */ #pragma omp master reduce_ptrs = splatt_malloc(nthreads * sizeof(*reduce_ptrs)); #pragma omp barrier reduce_ptrs[tid] = buffer; #pragma omp barrier /* do the reduction */ switch(which) { case SPLATT_REDUCE_SUM: p_reduce_sum(reduce_ptrs, buffer, nelems); break; case SPLATT_REDUCE_MAX: p_reduce_max(reduce_ptrs, buffer, nelems); break; default: fprintf(stderr, "SPLATT: thread_allreduce type '%d' not recognized.\n", which); } #pragma omp barrier /* now each thread grabs master values */ for(idx_t i=0; i < nelems; ++i) { buffer[i] = reduce_ptrs[0][i]; } #pragma omp barrier #pragma omp master splatt_free(reduce_ptrs); } thd_info * thd_init( idx_t const nthreads, idx_t const nscratch, ...) { thd_info * thds = (thd_info *) splatt_malloc(nthreads * sizeof(thd_info)); for(idx_t t=0; t < nthreads; ++t) { timer_reset(&thds[t].ttime); thds[t].nscratch = nscratch; thds[t].scratch = (void **) splatt_malloc(nscratch * sizeof(void*)); } va_list args; va_start(args, nscratch); for(idx_t s=0; s < nscratch; ++s) { idx_t const bytes = va_arg(args, idx_t); for(idx_t t=0; t < nthreads; ++t) { thds[t].scratch[s] = (void *) splatt_malloc(bytes); memset(thds[t].scratch[s], 0, bytes); } } va_end(args); return thds; } void thd_times( thd_info * thds, idx_t const nthreads) { for(idx_t t=0; t < nthreads; ++t) { printf(" thread: %"SPLATT_PF_IDX" %0.3fs\n", t, thds[t].ttime.seconds); } } void thd_time_stats( thd_info * thds, idx_t const nthreads) { double max_time = 0.; double avg_time = 0.; for(idx_t t=0; t < nthreads; ++t) { avg_time += thds[t].ttime.seconds; max_time = SS_MAX(max_time, thds[t].ttime.seconds); } avg_time /= nthreads; double const imbal = (max_time - avg_time) / max_time; printf(" avg: %0.3fs max: %0.3fs (%0.1f%% imbalance)\n", avg_time, max_time, 100. * imbal); } void thd_reset( thd_info * thds, idx_t const nthreads) { for(idx_t t=0; t < nthreads; ++t) { timer_reset(&thds[t].ttime); } } void thd_free( thd_info * thds, idx_t const nthreads) { for(idx_t t=0; t < nthreads; ++t) { for(idx_t s=0; s < thds[t].nscratch; ++s) { free(thds[t].scratch[s]); } free(thds[t].scratch); } free(thds); }
transform.h
/*! * Copyright 2018 XGBoost contributors */ #ifndef XGBOOST_COMMON_TRANSFORM_H_ #define XGBOOST_COMMON_TRANSFORM_H_ #include <dmlc/omp.h> #include <xgboost/data.h> #include <utility> #include <vector> #include <type_traits> // enable_if #include "host_device_vector.h" #include "common.h" #include "span.h" #if defined (__CUDACC__) #include "device_helpers.cuh" #endif // defined (__CUDACC__) namespace xgboost { namespace common { constexpr size_t kBlockThreads = 256; namespace detail { #if defined(__CUDACC__) template <typename Functor, typename... SpanType> __global__ void LaunchCUDAKernel(Functor _func, Range _range, SpanType... _spans) { for (auto i : dh::GridStrideRange(*_range.begin(), *_range.end())) { _func(i, _spans...); } } #endif // defined(__CUDACC__) } // namespace detail /*! \brief Do Transformation on HostDeviceVectors. * * \tparam CompiledWithCuda A bool parameter used to distinguish compilation * trajectories, users do not need to use it. * * Note: Using Transform is a VERY tricky thing to do. Transform uses template * argument to duplicate itself into two different types, one for CPU, * another for CUDA. The trick is not without its flaw: * * If you use it in a function that can be compiled by both nvcc and host * compiler, the behaviour is un-defined! Because your function is NOT * duplicated by `CompiledWithCuda`. At link time, cuda compiler resolution * will merge functions with same signature. */ template <bool CompiledWithCuda = WITH_CUDA()> class Transform { private: template <typename Functor> struct Evaluator { public: Evaluator(Functor func, Range range, GPUSet devices, bool shard) : func_(func), range_{std::move(range)}, shard_{shard}, distribution_{GPUDistribution::Block(devices)} {} Evaluator(Functor func, Range range, GPUDistribution dist, bool shard) : func_(func), range_{std::move(range)}, shard_{shard}, distribution_{std::move(dist)} {} /*! * \brief Evaluate the functor with input pointers to HostDeviceVector. * * \tparam HDV... HostDeviceVectors type. * \param vectors Pointers to HostDeviceVector. */ template <typename... HDV> void Eval(HDV... vectors) const { bool on_device = !distribution_.IsEmpty(); if (on_device) { LaunchCUDA(func_, vectors...); } else { LaunchCPU(func_, vectors...); } } private: // CUDA UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->DeviceSpan(_device); return span; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->ConstDeviceSpan(_device); return span; } // CPU UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec) const { return Span<T> {_vec->HostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec) const { return Span<T const> {_vec->ConstHostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } // Recursive unpack for Shard. template <typename T> void UnpackShard(GPUDistribution dist, const HostDeviceVector<T> *vector) const { vector->Shard(dist); } template <typename Head, typename... Rest> void UnpackShard(GPUDistribution dist, const HostDeviceVector<Head> *_vector, const HostDeviceVector<Rest> *... _vectors) const { _vector->Shard(dist); UnpackShard(dist, _vectors...); } #if defined(__CUDACC__) template <typename std::enable_if<CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { if (shard_) UnpackShard(distribution_, _vectors...); GPUSet devices = distribution_.Devices(); size_t range_size = *range_.end() - *range_.begin(); // Extract index to deal with possible old OpenMP. size_t device_beg = *(devices.begin()); size_t device_end = *(devices.end()); #pragma omp parallel for schedule(static, 1) if (devices.Size() > 1) for (omp_ulong device = device_beg; device < device_end; ++device) { // NOLINT // Ignore other attributes of GPUDistribution for spliting index. // This deals with situation like multi-class setting where // granularity is used in data vector. size_t shard_size = GPUDistribution::Block(devices).ShardSize( range_size, devices.Index(device)); Range shard_range {0, static_cast<Range::DifferenceType>(shard_size)}; dh::safe_cuda(cudaSetDevice(device)); const int GRID_SIZE = static_cast<int>(DivRoundUp(*(range_.end()), kBlockThreads)); detail::LaunchCUDAKernel<<<GRID_SIZE, kBlockThreads>>>( _func, shard_range, UnpackHDV(_vectors, device)...); } } #else /*! \brief Dummy funtion defined when compiling for CPU. */ template <typename std::enable_if<!CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { LOG(FATAL) << "Not part of device code. WITH_CUDA: " << WITH_CUDA(); } #endif // defined(__CUDACC__) template <typename... HDV> void LaunchCPU(Functor func, HDV*... vectors) const { omp_ulong end = static_cast<omp_ulong>(*(range_.end())); #pragma omp parallel for schedule(static) for (omp_ulong idx = 0; idx < end; ++idx) { func(idx, UnpackHDV(vectors)...); } } private: /*! \brief Callable object. */ Functor func_; /*! \brief Range object specifying parallel threads index range. */ Range range_; /*! \brief Whether sharding for vectors is required. */ bool shard_; GPUDistribution distribution_; }; public: /*! * \brief Initialize a Transform object. * * \tparam Functor A callable object type. * \return A Evaluator having one method Eval. * * \param func A callable object, accepting a size_t thread index, * followed by a set of Span classes. * \param range Range object specifying parallel threads index range. * \param devices GPUSet specifying GPUs to use, when compiling for CPU, * this should be GPUSet::Empty(). * \param shard Whether Shard for HostDeviceVector is needed. */ template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUSet const devices, bool const shard = true) { return Evaluator<Functor> {func, std::move(range), std::move(devices), shard}; } template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUDistribution const dist, bool const shard = true) { return Evaluator<Functor> {func, std::move(range), std::move(dist), shard}; } }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_TRANSFORM_H_
segment.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS EEEEE GGGG M M EEEEE N N TTTTT % % SS E G MM MM E NN N T % % SSS EEE G GGG M M M EEE N N N T % % SS E G G M M E N NN T % % SSSSS EEEEE GGGG M M EEEEE N N T % % % % % % MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means % % % % Software Design % % Cristy % % April 1993 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segment segments an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % c-means technique. The scale-space filter analyzes the histograms of % the three color components of the image and identifies a set of % classes. The extents of each class is used to coarsely segment the % image with thresholding. The color associated with each class is % determined by the mean color of all pixels within the extents of a % particular class. Finally, any unclassified pixels are assigned to % the closest class with the fuzzy c-means technique. % % The fuzzy c-Means algorithm can be summarized as follows: % % o Build a histogram, one for each color component of the image. % % o For each histogram, successively apply the scale-space filter and % build an interval tree of zero crossings in the second derivative % at each scale. Analyze this scale-space ''fingerprint'' to % determine which peaks and valleys in the histogram are most % predominant. % % o The fingerprint defines intervals on the axis of the histogram. % Each interval contains either a minima or a maxima in the original % signal. If each color component lies within the maxima interval, % that pixel is considered ''classified'' and is assigned an unique % class number. % % o Any pixel that fails to be classified in the above thresholding % pass is classified using the fuzzy c-Means technique. It is % assigned to one of the classes discovered in the histogram analysis % phase. % % The fuzzy c-Means technique attempts to cluster a pixel by finding % the local minima of the generalized within group sum of squared error % objective function. A pixel is assigned to the closest class of % which the fuzzy membership has a maximum value. % % Segment is strongly based on software written by Andy Gallo, % University of Delaware. % % The following reference was used in creating this program: % % Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation % Algorithm Based on the Thresholding and the Fuzzy c-Means % Techniques", Pattern Recognition, Volume 23, Number 9, pages % 935-952, 1990. % % */ #include "MagickCore/studio.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #define MaxDimension 3 #define DeltaTau 0.5f #if defined(FastClassify) #define WeightingExponent 2.0 #define SegmentPower(ratio) (ratio) #else #define WeightingExponent 2.5 #define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0))); #endif #define Tau 5.2f /* Typedef declarations. */ typedef struct _ExtentPacket { double center; ssize_t index, left, right; } ExtentPacket; typedef struct _Cluster { struct _Cluster *next; ExtentPacket red, green, blue; ssize_t count, id; } Cluster; typedef struct _IntervalTree { double tau; ssize_t left, right; double mean_stability, stability; struct _IntervalTree *sibling, *child; } IntervalTree; typedef struct _ZeroCrossing { double tau, histogram[256]; short crossings[256]; } ZeroCrossing; /* Constant declarations. */ static const int Blue = 2, Green = 1, Red = 0, SafeMargin = 3, TreeLength = 600; /* Method prototypes. */ static double OptimalTau(const ssize_t *,const double,const double,const double, const double,short *); static ssize_t DefineRegion(const short *,ExtentPacket *); static void FreeNodes(IntervalTree *), InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *), ScaleSpace(const ssize_t *,const double,double *), ZeroCrossHistogram(double *,const double,short *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Classify() defines one or more classes. Each pixel is thresholded to % determine which class it belongs to. If the class is not identified it is % assigned to the closest class based on the fuzzy c-Means technique. % % The format of the Classify method is: % % MagickBooleanType Classify(Image *image,short **extrema, % const double cluster_threshold, % const double weighting_exponent, % const MagickBooleanType verbose,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o weighting_exponent: Specifies the membership weighting exponent. % % o verbose: A value greater than zero prints detailed information about % the identified classes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType Classify(Image *image,short **extrema, const double cluster_threshold, const double weighting_exponent,const MagickBooleanType verbose, ExceptionInfo *exception) { #define SegmentImageTag "Segment/Image" #define ThrowClassifyException(severity,tag,label) \ {\ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \ { \ next_cluster=cluster->next; \ cluster=(Cluster *) RelinquishMagickMemory(cluster); \ } \ if (squares != (double *) NULL) \ { \ squares-=255; \ free_squares=squares; \ free_squares=(double *) RelinquishMagickMemory(free_squares); \ } \ ThrowBinaryException(severity,tag,label); \ } CacheView *image_view; Cluster *cluster, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickOffsetType progress; double *free_squares; MagickStatusType status; register ssize_t i; register double *squares; size_t number_clusters; ssize_t count, y; /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; squares=(double *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ status=MagickTrue; count=0; progress=0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register 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++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(double) ScaleQuantumToChar( GetPixelRed(image,p)); cluster->green.center+=(double) ScaleQuantumToChar( GetPixelGreen(image,p)); cluster->blue.center+=(double) ScaleQuantumToChar( GetPixelBlue(image,p)); cluster->count++; break; } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } number_clusters=(size_t) count; if (verbose != MagickFalse) { /* Print cluster statistics. */ (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n"); (void) FormatLocaleFile(stdout,"===================\n\n"); (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double) cluster_threshold); (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double) weighting_exponent); (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n", (double) number_clusters); /* Print the total number of points per cluster. */ (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n"); (void) FormatLocaleFile(stdout,"=============================\n\n"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double) cluster->id,(double) cluster->count); /* Print the cluster extents. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"================"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout, "%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double) cluster->red.left,(double) cluster->red.right,(double) cluster->green.left,(double) cluster->green.right,(double) cluster->blue.left,(double) cluster->blue.right); } /* Print the cluster center values. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"====================="); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout,"%g %g %g\n",(double) cluster->red.center,(double) cluster->green.center,(double) cluster->blue.center); } (void) FormatLocaleFile(stdout,"\n"); } if (number_clusters > 256) ThrowClassifyException(ImageError,"TooManyClusters",image->filename); /* Speed up distance calculations. */ squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares)); if (squares == (double *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); squares+=255; for (i=(-255); i <= 255; i++) squares[i]=(double) i*(double) i; /* Allocate image colormap. */ if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); i=0; for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char) (cluster->red.center+0.5)); image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char) (cluster->green.center+0.5)); image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char) (cluster->blue.center+0.5)); i++; } /* Do course grain classes. */ 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++) { Cluster *clust; register const PixelInfo *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,0,q); for (clust=head; clust != (Cluster *) NULL; clust=clust->next) { if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) >= (clust->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) <= (clust->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) >= (clust->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) <= (clust->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) >= (clust->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) <= (clust->blue.right+SafeMargin))) { /* Classify this pixel. */ SetPixelIndex(image,(Quantum) clust->id,q); break; } } if (clust == (Cluster *) NULL) { double distance_squared, local_minima, numerator, ratio, sum; register ssize_t j, k; /* Compute fuzzy membership. */ local_minima=0.0; for (j=0; j < (ssize_t) image->colors; j++) { sum=0.0; p=image->colormap+j; distance_squared=squares[(ssize_t) ScaleQuantumToChar( GetPixelRed(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->blue))]; numerator=distance_squared; for (k=0; k < (ssize_t) image->colors; k++) { p=image->colormap+k; distance_squared=squares[(ssize_t) ScaleQuantumToChar( GetPixelRed(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[ (ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[ (ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->blue))]; ratio=numerator/distance_squared; sum+=SegmentPower(ratio); } if ((sum != 0.0) && ((1.0/sum) > local_minima)) { /* Classify this pixel. */ local_minima=1.0/sum; SetPixelIndex(image,(Quantum) j,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,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status&=SyncImage(image,exception); /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } squares-=255; free_squares=squares; free_squares=(double *) RelinquishMagickMemory(free_squares); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C r o s s i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCrossings() guarantees that an even number of zero crossings % always lie between two crossings. % % The format of the ConsolidateCrossings method is: % % ConsolidateCrossings(ZeroCrossing *zero_crossing, % const size_t number_crossings) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void ConsolidateCrossings(ZeroCrossing *zero_crossing, const size_t number_crossings) { register ssize_t i, j, k, l; ssize_t center, correct, count, left, right; /* Consolidate zero crossings. */ for (i=(ssize_t) number_crossings-1; i >= 0; i--) for (j=0; j <= 255; j++) { if (zero_crossing[i].crossings[j] == 0) continue; /* Find the entry that is closest to j and still preserves the property that there are an even number of crossings between intervals. */ for (k=j-1; k > 0; k--) if (zero_crossing[i+1].crossings[k] != 0) break; left=MagickMax(k,0); center=j; for (k=j+1; k < 255; k++) if (zero_crossing[i+1].crossings[k] != 0) break; right=MagickMin(k,255); /* K is the zero crossing just left of j. */ for (k=j-1; k > 0; k--) if (zero_crossing[i].crossings[k] != 0) break; if (k < 0) k=0; /* Check center for an even number of crossings between k and j. */ correct=(-1); if (zero_crossing[i+1].crossings[j] != 0) { count=0; for (l=k+1; l < center; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (center != k)) correct=center; } /* Check left for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < left; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (left != k)) correct=left; } /* Check right for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < right; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (right != k)) correct=right; } l=(ssize_t) zero_crossing[i].crossings[j]; zero_crossing[i].crossings[j]=0; if (correct != -1) zero_crossing[i].crossings[correct]=(short) l; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineRegion() defines the left and right boundaries of a peak region. % % The format of the DefineRegion method is: % % ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) % % A description of each parameter follows. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o extents: This pointer to an ExtentPacket represent the extends % of a particular peak or valley of a color component. % */ static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) { /* Initialize to default values. */ extents->left=0; extents->center=0.0; extents->right=255; /* Find the left side (maxima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] > 0) break; if (extents->index > 255) return(MagickFalse); /* no left side - no region exists */ extents->left=extents->index; /* Find the right side (minima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] < 0) break; extents->right=extents->index-1; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e r i v a t i v e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DerivativeHistogram() determines the derivative of the histogram using % central differencing. % % The format of the DerivativeHistogram method is: % % DerivativeHistogram(const double *histogram, % double *derivative) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % % o derivative: This array of doubles is initialized by % DerivativeHistogram to the derivative of the histogram using central % differencing. % */ static void DerivativeHistogram(const double *histogram, double *derivative) { register ssize_t i, n; /* Compute endpoints using second order polynomial interpolation. */ n=255; derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]); derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]); /* Compute derivative using central differencing. */ for (i=1; i < n; i++) derivative[i]=(histogram[i+1]-histogram[i-1])/2.0; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e D y n a m i c T h r e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDynamicThreshold() returns the dynamic threshold for an image. % % The format of the GetImageDynamicThreshold method is: % % MagickBooleanType GetImageDynamicThreshold(const Image *image, % const double cluster_threshold,const double smooth_threshold, % PixelInfo *pixel,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o pixel: return the dynamic threshold here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image, const double cluster_threshold,const double smooth_threshold, PixelInfo *pixel,ExceptionInfo *exception) { Cluster *background, *cluster, *object, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickBooleanType proceed; double threshold; register const Quantum *p; register ssize_t i, x; short *extrema[MaxDimension]; ssize_t count, *histogram[MaxDimension], y; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetPixelInfo(image,pixel); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } } /* Initialize histogram. */ InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]); /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ count=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(double) ScaleQuantumToChar( GetPixelRed(image,p)); cluster->green.center+=(double) ScaleQuantumToChar( GetPixelGreen(image,p)); cluster->blue.center+=(double) ScaleQuantumToChar( GetPixelBlue(image,p)); cluster->count++; break; } p+=GetPixelChannels(image); } proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y, 2*image->rows); if (proceed == MagickFalse) break; } /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } object=head; background=head; if (count > 1) { object=head->next; for (cluster=object; cluster->next != (Cluster *) NULL; ) { if (cluster->count < object->count) object=cluster; cluster=cluster->next; } background=head->next; for (cluster=background; cluster->next != (Cluster *) NULL; ) { if (cluster->count > background->count) background=cluster; cluster=cluster->next; } } if (background != (Cluster *) NULL) { threshold=(background->red.center+object->red.center)/2.0; pixel->red=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->green.center+object->green.center)/2.0; pixel->green=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->blue.center+object->blue.center)/2.0; pixel->blue=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); } /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeHistogram() computes the histogram for an image. % % The format of the InitializeHistogram method is: % % InitializeHistogram(const Image *image,ssize_t **histogram) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % */ static void InitializeHistogram(const Image *image,ssize_t **histogram, ExceptionInfo *exception) { register const Quantum *p; register ssize_t i, x; ssize_t y; /* Initialize histogram. */ for (i=0; i <= 255; i++) { histogram[Red][i]=0; histogram[Green][i]=0; histogram[Blue][i]=0; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(image,p))]++; histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p))]++; histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p))]++; p+=GetPixelChannels(image); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e I n t e r v a l T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeIntervalTree() initializes an interval tree from the lists of % zero crossings. % % The format of the InitializeIntervalTree method is: % % InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes, % IntervalTree *node) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void InitializeList(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) list[(*number_nodes)++]=node; InitializeList(list,number_nodes,node->sibling); InitializeList(list,number_nodes,node->child); } static void MeanStability(IntervalTree *node) { register IntervalTree *child; if (node == (IntervalTree *) NULL) return; node->mean_stability=0.0; child=node->child; if (child != (IntervalTree *) NULL) { register ssize_t count; register double sum; sum=0.0; count=0; for ( ; child != (IntervalTree *) NULL; child=child->sibling) { sum+=child->stability; count++; } node->mean_stability=sum/(double) count; } MeanStability(node->sibling); MeanStability(node->child); } static void Stability(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) node->stability=0.0; else node->stability=node->tau-(node->child)->tau; Stability(node->sibling); Stability(node->child); } static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing, const size_t number_crossings) { IntervalTree *head, **list, *node, *root; register ssize_t i; ssize_t j, k, left, number_nodes; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return((IntervalTree *) NULL); /* The root is the entire histogram. */ root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root)); root->child=(IntervalTree *) NULL; root->sibling=(IntervalTree *) NULL; root->tau=0.0; root->left=0; root->right=255; root->mean_stability=0.0; root->stability=0.0; (void) memset(list,0,TreeLength*sizeof(*list)); for (i=(-1); i < (ssize_t) number_crossings; i++) { /* Initialize list with all nodes with no children. */ number_nodes=0; InitializeList(list,&number_nodes,root); /* Split list. */ for (j=0; j < number_nodes; j++) { head=list[j]; left=head->left; node=head; for (k=head->left+1; k < head->right; k++) { if (zero_crossing[i+1].crossings[k] != 0) { if (node == head) { node->child=(IntervalTree *) AcquireMagickMemory( sizeof(*node->child)); node=node->child; } else { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; } if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=k; left=k; } } if (left != head->left) { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=head->right; } } } /* Determine the stability: difference between a nodes tau and its child. */ Stability(root->child); MeanStability(root->child); list=(IntervalTree **) RelinquishMagickMemory(list); return(root); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m a l T a u % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimalTau() finds the optimal tau for each band of the histogram. % % The format of the OptimalTau method is: % % double OptimalTau(const ssize_t *histogram,const double max_tau, % const double min_tau,const double delta_tau, % const double smooth_threshold,short *extrema) % % A description of each parameter follows. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % */ static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->stability >= node->mean_stability) { list[(*number_nodes)++]=node; ActiveNodes(list,number_nodes,node->sibling); } else { ActiveNodes(list,number_nodes,node->sibling); ActiveNodes(list,number_nodes,node->child); } } static void FreeNodes(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; FreeNodes(node->sibling); FreeNodes(node->child); node=(IntervalTree *) RelinquishMagickMemory(node); } static double OptimalTau(const ssize_t *histogram,const double max_tau, const double min_tau,const double delta_tau,const double smooth_threshold, short *extrema) { IntervalTree **list, *node, *root; MagickBooleanType peak; double average_tau, *derivative, *second_derivative, tau, value; register ssize_t i, x; size_t count, number_crossings; ssize_t index, j, k, number_nodes; ZeroCrossing *zero_crossing; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return(0.0); /* Allocate zero crossing list. */ count=(size_t) ((max_tau-min_tau)/delta_tau)+2; zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count, sizeof(*zero_crossing)); if (zero_crossing == (ZeroCrossing *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } for (i=0; i < (ssize_t) count; i++) zero_crossing[i].tau=(-1.0); /* Initialize zero crossing list. */ derivative=(double *) AcquireCriticalMemory(256*sizeof(*derivative)); second_derivative=(double *) AcquireCriticalMemory(256* sizeof(*second_derivative)); i=0; for (tau=max_tau; tau >= min_tau; tau-=delta_tau) { zero_crossing[i].tau=tau; ScaleSpace(histogram,tau,zero_crossing[i].histogram); DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); i++; } /* Add an entry for the original histogram. */ zero_crossing[i].tau=0.0; for (j=0; j <= 255; j++) zero_crossing[i].histogram[j]=(double) histogram[j]; DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); number_crossings=(size_t) i; derivative=(double *) RelinquishMagickMemory(derivative); second_derivative=(double *) RelinquishMagickMemory(second_derivative); /* Ensure the scale-space fingerprints form lines in scale-space, not loops. */ ConsolidateCrossings(zero_crossing,number_crossings); /* Force endpoints to be included in the interval. */ for (i=0; i <= (ssize_t) number_crossings; i++) { for (j=0; j < 255; j++) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]); for (j=255; j > 0; j--) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]); } /* Initialize interval tree. */ root=InitializeIntervalTree(zero_crossing,number_crossings); if (root == (IntervalTree *) NULL) { zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } /* Find active nodes: stability is greater (or equal) to the mean stability of its children. */ number_nodes=0; ActiveNodes(list,&number_nodes,root->child); /* Initialize extrema. */ for (i=0; i <= 255; i++) extrema[i]=0; for (i=0; i < number_nodes; i++) { /* Find this tau in zero crossings list. */ k=0; node=list[i]; for (j=0; j <= (ssize_t) number_crossings; j++) if (zero_crossing[j].tau == node->tau) k=j; /* Find the value of the peak. */ peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue : MagickFalse; index=node->left; value=zero_crossing[k].histogram[index]; for (x=node->left; x <= node->right; x++) { if (peak != MagickFalse) { if (zero_crossing[k].histogram[x] > value) { value=zero_crossing[k].histogram[x]; index=x; } } else if (zero_crossing[k].histogram[x] < value) { value=zero_crossing[k].histogram[x]; index=x; } } for (x=node->left; x <= node->right; x++) { if (index == 0) index=256; if (peak != MagickFalse) extrema[x]=(short) index; else extrema[x]=(short) (-index); } } /* Determine the average tau. */ average_tau=0.0; for (i=0; i < number_nodes; i++) average_tau+=list[i]->tau; average_tau/=(double) number_nodes; /* Relinquish resources. */ FreeNodes(root); zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(average_tau); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S c a l e S p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleSpace() performs a scale-space filter on the 1D histogram. % % The format of the ScaleSpace method is: % % ScaleSpace(const ssize_t *histogram,const double tau, % double *scale_histogram) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % */ static void ScaleSpace(const ssize_t *histogram,const double tau, double *scale_histogram) { double alpha, beta, *gamma, sum; register ssize_t u, x; gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma)); if (gamma == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateGammaMap"); alpha=PerceptibleReciprocal(tau*sqrt(2.0*MagickPI)); beta=(-1.0*PerceptibleReciprocal(2.0*tau*tau)); for (x=0; x <= 255; x++) gamma[x]=0.0; for (x=0; x <= 255; x++) { gamma[x]=exp((double) beta*x*x); if (gamma[x] < MagickEpsilon) break; } for (x=0; x <= 255; x++) { sum=0.0; for (u=0; u <= 255; u++) sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)]; scale_histogram[x]=alpha*sum; } gamma=(double *) RelinquishMagickMemory(gamma); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e g m e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SegmentImage() segment an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % C-means technique. % % The format of the SegmentImage method is: % % MagickBooleanType SegmentImage(Image *image, % const ColorspaceType colorspace,const MagickBooleanType verbose, % const double cluster_threshold,const double smooth_threshold, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o colorspace: Indicate the colorspace. % % o verbose: Set to MagickTrue to print detailed information about the % identified classes. % % o cluster_threshold: This represents the minimum number of pixels % contained in a hexahedra before it can be considered valid (expressed % as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SegmentImage(Image *image, const ColorspaceType colorspace,const MagickBooleanType verbose, const double cluster_threshold,const double smooth_threshold, ExceptionInfo *exception) { ColorspaceType previous_colorspace; MagickBooleanType status; register ssize_t i; short *extrema[MaxDimension]; ssize_t *histogram[MaxDimension]; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename) } } /* Initialize histogram. */ previous_colorspace=image->colorspace; (void) TransformImageColorspace(image,colorspace,exception); InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]); /* Classify using the fuzzy c-Means technique. */ status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose, exception); (void) TransformImageColorspace(image,previous_colorspace,exception); /* Relinquish resources. */ for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Z e r o C r o s s H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroCrossHistogram() find the zero crossings in a histogram and marks % directions as: 1 is negative to positive; 0 is zero crossing; and -1 % is positive to negative. % % The format of the ZeroCrossHistogram method is: % % ZeroCrossHistogram(double *second_derivative, % const double smooth_threshold,short *crossings) % % A description of each parameter follows. % % o second_derivative: Specifies an array of doubles representing the % second derivative of the histogram of a particular color component. % % o crossings: This array of integers is initialized with % -1, 0, or 1 representing the slope of the first derivative of the % of a particular color component. % */ static void ZeroCrossHistogram(double *second_derivative, const double smooth_threshold,short *crossings) { register ssize_t i; ssize_t parity; /* Merge low numbers to zero to help prevent noise. */ for (i=0; i <= 255; i++) if ((second_derivative[i] < smooth_threshold) && (second_derivative[i] >= -smooth_threshold)) second_derivative[i]=0.0; /* Mark zero crossings. */ parity=0; for (i=0; i <= 255; i++) { crossings[i]=0; if (second_derivative[i] < 0.0) { if (parity > 0) crossings[i]=(-1); parity=1; } else if (second_derivative[i] > 0.0) { if (parity < 0) crossings[i]=1; parity=(-1); } } }
mm.c
/* Henrique, eu resolvi testar no meu proprio PC ao inves do server da PUC, porque lá demora demais, e se um unico aluno alem de mim resolver testar, o programa dele vai ocupar CPU time junto com o meu e os tempos vao ficar diferentes. Preferi testar no meu PC tambem porque assim eu consigo ter controle de quais programas rodam em background e saber que eu fechei tudo, pra minha CPU ficar exclusivamente pra rodar esse codigo. Config do meu PC: AMD Ryzen 5 5600X (6 cores 12 threads) Arch Linux - 5.13.12-arch1-1 GCC 11.1.0 Tempo - Sequencial real 0m24.447s user 0m24.413s sys 0m0.023s real 0m24.433s user 0m24.406s sys 0m0.017s real 0m24.379s user 0m24.231s sys 0m0.093s real 0m24.330s user 0m24.173s sys 0m0.083s real 0m24.346s user 0m24.319s sys 0m0.017s real 0m24.370s user 0m24.340s sys 0m0.020s real 0m24.416s user 0m24.382s sys 0m0.023s real 0m24.415s user 0m24.379s sys 0m0.027s ========================== Tempo - Paralelo real 0m3.762s user 0m43.229s sys 0m1.277s real 0m3.746s user 0m43.324s sys 0m1.323s real 0m3.726s user 0m42.869s sys 0m1.232s real 0m3.761s user 0m43.387s sys 0m1.387s real 0m3.791s user 0m43.662s sys 0m1.340s real 0m3.748s user 0m43.290s sys 0m1.284s real 0m3.765s user 0m43.465s sys 0m1.289s real 0m3.801s user 0m43.572s sys 0m1.314s */ #include <stdio.h> #include <stdlib.h> void mm(double* a, double* b, double* c, int width) { #pragma omp parallel for collapse(2) for (int i = 0; i < width; i++) { for (int j = 0; j < width; j++) { double sum = 0; #pragma omp parallel for for (int k = 0; k < width; k++) { double x = a[i * width + k]; double y = b[k * width + j]; sum += x * y; } c[i * width + j] = sum; } } } int main() { int width = 2000; double *a = (double*) malloc (width * width * sizeof(double)); double *b = (double*) malloc (width * width * sizeof(double)); double *c = (double*) malloc (width * width * sizeof(double)); #pragma omp parallel for collapse(2) for(int i = 0; i < width; i++) { for(int j = 0; j < width; j++) { a[i*width+j] = i; b[i*width+j] = j; c[i*width+j] = 0; } } mm(a,b,c,width); // for(int i = 0; i < width; i++) { // for(int j = 0; j < width; j++) { // printf("\n c[%d][%d] = %f",i,j,c[i*width+j]); // } // } }
parallel.h
/* Part of the Ironic Project. Distributed under MIT License, which means: - Do whatever you want - Keep this notice and include the license file to your project - I provide no warranty To get help with installation, visit README Created by Kyrylo Sovailo, github.com/Meta-chan, k.sovailo@gmail.com Reinventing bicycles since 2020 */ bool ir::Parallel::_ok = false; #ifndef IR_PARALLEL_IMPLEMENTATION ir::uint32 ir::Parallel::_n = 0; bool ir::Parallel::init(uint32 n) noexcept { if (_ok || n == 0) return false; _n = n; _ok = true; return true; } void ir::Parallel::finalize() noexcept { _ok = false; } bool ir::Parallel::parallel(const void *user, Function *function) noexcept { if (!_ok || function == nullptr) return false; for (uint32 i = 0; i < _n; i++) { function(user, i, _n); } return true; } #elif IR_PARALLEL_IMPLEMENTATION == 'w' #include <Windows.h> ir::Parallel::Function * volatile ir::Parallel::_function = nullptr; const void * volatile ir::Parallel::_user = nullptr; ir::uint32 ir::Parallel::_n = 0; volatile ir::uint32 ir::Parallel::_finished = 0; volatile ir::uint32 ir::Parallel::_task = 0; DWORD WINAPI ir::Parallel::_windows_function(LPVOID) noexcept { uint32 id = InterlockedIncrement(&_finished); uint32 task = 1; while (true) { if (task != _task) { //Wait for next task } else if (_function == nullptr) { //Quit InterlockedIncrement(&_finished); return 0; } else { //Execute task _function(_user, id, _n); InterlockedIncrement(&_finished); task++; } } } bool ir::Parallel::init(uint32 n) noexcept { if (_ok || n == 0) return false; _function = nullptr; _user = nullptr; _finished = 0; _task = 0; _n = n; for (uint32 i = 0; i < (n - 1); i++) { if (CreateThread(nullptr, 0, _windows_function, nullptr, 0, nullptr) == NULL) return false; } while (_finished != (n - 1)) {} _ok = true; return true; } void ir::Parallel::finalize() noexcept { _function = nullptr; _user = nullptr; _finished = 0; _task++; while (_finished != (_n - 1)) {} _ok = false; } bool ir::Parallel::parallel(const void *user, Function *function) noexcept { if (!_ok || function == nullptr) return false; _function = function; _user = user; _finished = 0; _task++; function(user, 0, _n); while (_finished != (_n - 1)) {} return true; } #elif IR_PARALLEL_IMPLEMENTATION == 'p' #include <pthread.h> ir::Parallel::Function * volatile ir::Parallel::_function = nullptr; const void * volatile ir::Parallel::_user = nullptr; ir::uint32 ir::Parallel::_n = 0; volatile std::atomic<ir::uint32> ir::Parallel::_finished = 0; volatile std::atomic<ir::uint32> ir::Parallel::_task = 0; void *ir::Parallel::_posix_function(void *) noexcept { uint32 id = _finished.fetch_add(1); uint32 task = 1; while (true) { if (task != _task) { //Wait for next task } else if (_function == nullptr) { //Quit _finished.fetch_add(1); return 0; } else { //Execute task _function(_user, id, _n); _finished.fetch_add(1); task++; } } } bool ir::Parallel::init(uint32 n) noexcept { if (_ok || n == 0) return false; _function = nullptr; _user = nullptr; _finished = 0; _task = 0; _n = n; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); for (uint32 i = 0; i < (n - 1); i++) { if (pthread_create(nullptr, &attr, _posix_function, this) != 0) return false; } pthread_attr_destroy(&attr); while (_finished != (n - 1)) {} _ok = true; return true; } void ir::Parallel::finalize() noexcept { _function = nullptr; _user = nullptr; _finished = 0; _task++; while (_finished != (_n - 1)) {} _ok = false; } bool ir::Parallel::parallel(const void *user, Function *function) noexcept { if (!_ok || function == nullptr) return false; _function = function; _user = user; _finished = 0; _task++; function(user, 0, _n); while (_finished != (_n - 1)) {} return true; } #elif IR_PARALLEL_IMPLEMENTATION == 'o' #include <omp.h> ir::uint32 ir::Parallel::_n = 0; bool ir::Parallel::init(uint32 n) noexcept { if (_ok || n == 0) return false; _n = n; _ok = true; return true; } void ir::Parallel::finalize() noexcept { _ok = false; } bool ir::Parallel::parallel(const void *user, Function *function) noexcept { if (!_ok || function == nullptr) return false; #pragma omp parallel num_threads(_n) { function(user, omp_get_thread_num(), _n); #pragma omp barrier } return true; } #endif bool ir::Parallel::ok() noexcept { return _ok; }
ch_common.h
#ifndef _BENCH_CHOLESKY_COMMON_ #define _BENCH_CHOLESKY_COMMON_ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <sys/syscall.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <assert.h> #include <mkl.h> #include <mpi.h> #include <omp.h> #ifdef TRACE #include "VT.h" #endif #ifdef MAIN int np; int mype; int num_threads; #else extern int np; extern int mype; extern int num_threads; #endif #if defined(USE_TIMING) void helper_start_timing(int tt); void helper_end_timing(int tt, double elapsed); #endif // #define SPEC_RESTRICT __restrict__ #define SPEC_RESTRICT restrict #if defined(CHAMELEON) || defined(CHAMELEON_TARGET) #include "chameleon.h" #endif #ifndef DPxMOD #define DPxMOD "0x%0*" PRIxPTR #endif #ifndef DPxPTR #define DPxPTR(ptr) ((int)(2*sizeof(uintptr_t))), ((uintptr_t) (ptr)) #endif #ifdef DEBUG int* __task_depth_counter; #define TASK_DEPTH_OFFSET 32 #define TASK_DEPTH_INIT do { \ __task_depth_counter = (int*) malloc((omp_get_max_threads()+1)*TASK_DEPTH_OFFSET*sizeof(int)); \ for (int i = 0; i < omp_get_max_threads(); i++) { \ __task_depth_counter[i*TASK_DEPTH_OFFSET] = 0; \ } \ } while(0) #define TASK_DEPTH_FINALIZE \ if(__task_depth_counter) \ free(__task_depth_counter); #define TASK_DEPTH_INCR ++__task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET] #define TASK_DEPTH_DECR --__task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET] #define TASK_DEPTH_GET __task_depth_counter[omp_get_thread_num()*TASK_DEPTH_OFFSET] #define DEBUG_PRINT(STR, ...) do { \ char* tmp_str = malloc(sizeof(char)*512); \ tmp_str[0] = '\0'; \ strcat(tmp_str,"R#%02d T#%02d (OS_TID:%06ld) Task-Depth:%02d : --> "); \ strcat(tmp_str,STR); \ fprintf(stderr, tmp_str, mype, omp_get_thread_num(), syscall(SYS_gettid), TASK_DEPTH_GET, __VA_ARGS__); \ free(tmp_str); \ } while(0) #else #define TASK_DEPTH_INIT #define TASK_DEPTH_FINALIZE #define TASK_DEPTH_INCR #define TASK_DEPTH_DECR #define TASK_DEPTH_GET 0 #define DEBUG_PRINT(STR, ...) #endif #ifdef _USE_HBW #include <hbwmalloc.h> #endif void dgemm_ (const char *transa, const char *transb, int *l, int *n, int *m, double *alpha, const void *a, int *lda, void *b, int *ldb, double *beta, void *c, int *ldc); void dtrsm_ (char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb); void dsyrk_ (char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc); void cholesky_single(const int ts, const int nt, double* A[nt][nt]); void cholesky_mpi(const int ts, const int nt, double *A[nt][nt], double *B, double *C[nt], int *block_rank); void omp_potrf(double * SPEC_RESTRICT const A, int ts, int ld); void omp_trsm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld); void omp_gemm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, double * SPEC_RESTRICT C, int ts, int ld); void omp_syrk(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld); int get_send_flags(char *send_flags, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n); void get_recv_flag(char *recv_flag, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n); void wait(MPI_Request *comm_req); inline static void waitall(MPI_Request *comm_req, int n) { #ifdef TRACE static int event_waitall = -1; if(event_waitall == -1) { char* event_name = "waitall"; int ierr; ierr = VT_funcdef(event_name, VT_NOCLASS, &event_waitall); } VT_begin(event_waitall); #endif #ifdef DISABLE_TASKYIELD MPI_Waitall(n, comm_req, MPI_STATUSES_IGNORE); #else while (1) { int flag = 0; MPI_Testall(n, comm_req, &flag, MPI_STATUSES_IGNORE); if (flag) break; (void)flag; // <-- make the Cray compiler happy #if defined(CHAMELEON) || defined(CHAMELEON_TARGET) int32_t res = chameleon_taskyield(); #else #pragma omp taskyield #endif } #endif #ifdef TRACE VT_end(event_waitall); #endif } void reset_send_flags(char *send_flags); #endif
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 8; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
repeat_base.h
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2010, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: David Weese <david.weese@fu-berlin.de> // ========================================================================== #ifndef SEQAN_HEADER_REPEAT_BASE_H #define SEQAN_HEADER_REPEAT_BASE_H #if SEQAN_ENABLE_PARALLELISM #include <seqan/parallel.h> #endif // #if SEQAN_ENABLE_PARALLELISM namespace seqan { /** .Class.Repeat ..summary:Store information about a repeat. ..cat:Index ..signature:Repeat<TPos, TPeriod> ..param.TPos:Type to use for storing positions. ...metafunction:Metafunction.Value ..param.TPeriod:Type to use for storing the repeat period. ...default:1 ...metafunction:Metafunction.Size ..include:seqan/index.h ..see:Function.findRepeats .Memvar.Repeat#beginPosition ..summary:The begin position of the repeat of type $TPos$. ..class:Class.Repeat .Memvar.Repeat#endPosition ..summary:The end position of the repeat of type $TPos$. ..class:Class.Repeat .Memvar.Repeat#period ..summary:The period of the repeat of type $TSize$. ..class:Class.Repeat */ template <typename TPos, typename TPeriod> struct Repeat { TPos beginPosition; TPos endPosition; TPeriod period; }; template <typename TPos, typename TPeriod> struct Value< Repeat<TPos, TPeriod> > { typedef TPos Type; }; template <typename TPos, typename TPeriod> struct Size< Repeat<TPos, TPeriod> > { typedef TPeriod Type; }; template <typename TSize> struct RepeatFinderParams { TSize minRepeatLen; TSize maxPeriod; }; // custom TSpec for our customized wotd-Index struct TRepeatFinder; template <typename TText> struct Cargo<Index<TText, IndexWotd<TRepeatFinder> > > { typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex; typedef typename Size<TIndex>::Type TSize; typedef RepeatFinderParams<TSize> Type; }; // node predicate template <typename TText, typename TSpec> bool nodePredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it) { // return countOccurrences(it) * nodeDepth(it) >= cargo(container(it)).minRepeatLen; return countOccurrences(it) * repLength(it) >= cargo(container(it)).minRepeatLen; } // monotonic hull template <typename TText, typename TSpec> bool nodeHullPredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it) { // return nodeDepth(it) <= cargo(container(it)).maxPeriod; return repLength(it) <= cargo(container(it)).maxPeriod; } template <typename TPos> struct RepeatLess_ : public ::std::binary_function<TPos, TPos, bool> { // key less inline bool operator() (TPos const &a, TPos const &b) { return posLess(a, b); } }; template <typename TValue> inline bool _repeatMaskValue(TValue const &) { // TODO(holtgrew): Maybe use unknownValue<TValue>() instead of specializing for all alphabets, especially since we have Rna5 now and might want Rna5Q later. return false; } template <> inline bool _repeatMaskValue(Dna5 const &val) { return val == unknownValue<Dna5>(); // 'N' } template <> inline bool _repeatMaskValue(Dna5Q const &val) { return val == unknownValue<Dna5Q>(); // 'N' } template <> inline bool _repeatMaskValue(Iupac const &val) { return val == unknownValue<Iupac>(); // 'N' } /* template <> inline bool _repeatMaskValue(AminoAcid val) { return val == 'X'; } */ /** .Function.findRepeats ..summary:Search for repeats in a text. ..cat:Index ..signature:findRepeats(repeatString, text, minRepeatLength[, maxPeriod]) ..param.repeatString:A @Class.String@ of @Class.Repeat@ objects. ..param.text:The text to search repeats in. ...type:Class.String ...type:Class.StringSet ..param.minRepeatLength:The minimum length each reported repeat must have. ..param.maxPeriod:Optionally, the maximal period that reported repeats can have. ...default:1 ..remarks:Subsequences of undefined values/$N$s will always be reported. ..example.text:The following demonstrates finding repeats of period 1. ..example.code: String<Repeat<unsigned, unsigned> > repeats; Dna5String text = "CGATAAAACTNN"; // repeat 0 AAAA // repeat 1 NN findRepeats(repeats, text, 3); // ==> length(repeats) == 2 // ==> repeats[0] == {beginPosition: 4, endPosition: 8, period: 1} // ==> repeats[1] == {beginPosition: 11, endPosition: 13, period: 1} ..see:Function.unknownValue ..include:seqan/index.h ..see:Class.Repeat */ // TODO(holtgrew): minRepeatLength is 1-off. // period-1 optimization template <typename TRepeatStore, typename TString, typename TRepeatSize> inline void findRepeats(TRepeatStore &repString, TString const &text, TRepeatSize minRepeatLen) { typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Iterator<TString const>::Type TIterator; typedef typename Value<TString>::Type TValue; typedef typename Size<TString>::Type TSize; #if SEQAN_ENABLE_PARALLELISM if (length(text) > (TSize)(omp_get_max_threads() * 2 * minRepeatLen)) { // std::cerr << ">>> PARALLEL WABOOGIE!" << std::endl; // std::cerr << "omp_get_max_threads() == " << omp_get_max_threads() << std::endl; // Parallel case. // NOTE(holtgrew): The minimum text length check above makes it impossible that more than two chunks are // required to form an otherwise too short repeat. // TODO(holtgrew): Load balancing? Probably not worth it. String<TSize> splitters; String<TRepeatStore> threadLocalStores; // Each threads finds repeats on its chunk in parallel. #pragma omp parallel { // We have to determine the number of available threads at this point. We will use the number of thread // local stores to determin the number of available threads later on. #pragma omp master { // std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl; computeSplitters(splitters, length(text), omp_get_num_threads()); resize(threadLocalStores, omp_get_num_threads()); } // end of #pragma omp master #pragma omp barrier int const t = omp_get_thread_num(); TRepeatStore & store = threadLocalStores[t]; TRepeat rep; rep.beginPosition = 0; rep.endPosition = 0; rep.period = 1; // Flags used for force-adding repeats for the chunks that have a left/right neighbour. bool forceFirst = t > 0; bool forceLast = (t + 1) < omp_get_num_threads(); // #pragma omp critical // std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl; TIterator it = iter(text, splitters[t], Standard()); TIterator itEnd = iter(text, splitters[t + 1], Standard()); if (it != itEnd) { TValue last = *it; TSize repLeft = 0; TSize repRight = 1; for (++it; it != itEnd; ++it, ++repRight) { if (*it != last) { // #pragma omp critical // std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceFirst = " << forceFirst << std::endl; if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceFirst) { forceFirst = false; // insert repeat rep.beginPosition = splitters[t] + repLeft; rep.endPosition = splitters[t] + repRight; // #pragma omp critical // std::cerr << " t == " << t << ", append" << std::endl; appendValue(store, rep); } repLeft = repRight; last = *it; } } // #pragma omp critical // std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceLast = " << forceLast << std::endl; if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceLast) { // Insert repeat but only if it is not already in there. if (empty(store) || (back(store).beginPosition != repLeft && back(store).endPosition != repRight)) { rep.beginPosition = splitters[t] + repLeft; rep.endPosition = splitters[t] + repRight; // #pragma omp critical // std::cerr << " t == " << t << ", append" << std::endl; appendValue(store, rep); } } } } // end of #pragma omp parallel // std::cerr << ",-- REPEATS BEFORE MENDING\n"; // for (unsigned i = 0; i < length(threadLocalStores); ++i) // { // std::cerr << "| i = " << i << std::endl; // for (unsigned j = 0; j < length(threadLocalStores[i]); ++j) // std::cerr << "| threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl; // } // std::cerr << "`--" << std::endl; // Mend the splice points. // // We will copy out infixes described by fromPositions. String<Pair<TSize> > fromPositions; resize(fromPositions, length(threadLocalStores)); for (unsigned i = 0; i < length(fromPositions); ++i) { fromPositions[i].i1 = 0; fromPositions[i].i2 = length(threadLocalStores[i]); } // First, merge repeats spanning blocks. Do this iteratively until all has been merged. bool anyChange; do { anyChange = false; int lastNonEmpty = -1; for (unsigned i = 0; i < length(threadLocalStores); ++i) { if (fromPositions[i].i1 == fromPositions[i].i2) continue; // Skip empty buckets. if (lastNonEmpty != -1) { bool const adjacent = back(threadLocalStores[lastNonEmpty]).endPosition == front(threadLocalStores[i]).beginPosition; bool const charsEqual = text[back(threadLocalStores[lastNonEmpty]).beginPosition] == text[front(threadLocalStores[i]).beginPosition]; if (adjacent && charsEqual) { anyChange = true; back(threadLocalStores[lastNonEmpty]).endPosition = front(threadLocalStores[i]).endPosition; fromPositions[i].i1 += 1; } } if (fromPositions[i].i1 != fromPositions[i].i2) lastNonEmpty = i; } } while (anyChange); // Then, remove any repeats in the beginning and end of blocks that are too short. for (unsigned i = 0; i < length(threadLocalStores); ++i) { if (fromPositions[i].i1 == fromPositions[i].i2) continue; unsigned j = fromPositions[i].i1; TRepeatSize len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition; if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value. len <= minRepeatLen) fromPositions[i].i1 += 1; if (fromPositions[i].i1 == fromPositions[i].i2) continue; j = fromPositions[i].i2 - 1; len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition; if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value. len <= minRepeatLen) fromPositions[i].i2 -= 1; } // Last, build splitters for output in parallel. String<unsigned> outSplitters; appendValue(outSplitters, 0); for (unsigned i = 0; i < length(threadLocalStores); ++i) appendValue(outSplitters, back(outSplitters) + fromPositions[i].i2 - fromPositions[i].i1); // std::cerr << ",-- REPEATS AFTER MENDING\n"; // for (unsigned i = 0; i < length(threadLocalStores); ++i) // { // std::cerr << "| i = " << i << std::endl; // std::cerr << "`--, fromPositions[" << i << "] = (" << fromPositions[i].i1 << ", " << fromPositions[i].i2 << std::endl; // for (unsigned j = 0; j < length(threadLocalStores[i]); ++j) // std::cerr << " | threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl; // } // std::cerr << " `--" << std::endl; // Allocate memory. clear(repString); resize(repString, back(outSplitters)); // Copy back the repeats in parallel. unsigned nt = length(threadLocalStores); (void) nt; // Otherwise, GCC 4.6 warns, does not see it used in pragma clause below. #pragma omp parallel num_threads(nt) { int const t = omp_get_thread_num(); arrayCopy(iter(threadLocalStores[t], fromPositions[t].i1, Standard()), iter(threadLocalStores[t], fromPositions[t].i2, Standard()), iter(repString, outSplitters[t], Standard())); } // end of #pragma omp parallel } else { #endif // #if SEQAN_ENABLE_PARALLELISM // Sequential case. TRepeat rep; rep.period = 1; clear(repString); TIterator it = begin(text, Standard()); TIterator itEnd = end(text, Standard()); if (it == itEnd) return; TSize repLen = 1; for (++it; it != itEnd; ++it) { if (*it != *(it-1)) { if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen) { // insert repeat rep.endPosition = it - begin(text, Standard()); rep.beginPosition = rep.endPosition - repLen; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } repLen = 1; } else ++repLen; } if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen) { // insert repeat rep.endPosition = length(text); rep.beginPosition = rep.endPosition - repLen; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } #if SEQAN_ENABLE_PARALLELISM } #endif // #if SEQAN_ENABLE_PARALLELISM // #pragma omp critical // { // std::cerr << "thread #" << omp_get_thread_num() << " REPEATS:"; // for (unsigned i = 0; i < length(repString); ++i) { // std::cerr << " (" << repString[i].beginPosition << ", " << repString[i].endPosition << ", " << repString[i].period << ")"; // } // std::cerr << std::endl; // } } // TODO(holtgrew): Why for TString const and StringSet<> const? template <typename TRepeatStore, typename TString, typename TSpec, typename TRepeatSize> inline void findRepeats(TRepeatStore &repString, StringSet<TString, TSpec> const &text, TRepeatSize minRepeatLen) { typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Iterator<TString>::Type TIterator; typedef typename Value<TString>::Type TValue; typedef typename Size<TString>::Type TSize; TRepeat rep; rep.period = 1; clear(repString); for (unsigned i = 0; i < length(text); ++i) { TIterator it = begin(text[i], Standard()); TIterator itEnd = end(text[i], Standard()); if (it == itEnd) continue; TValue last = *it; TSize repLeft = 0; TSize repRight = 1; rep.beginPosition.i1 = i; rep.endPosition.i1 = i; for (++it; it != itEnd; ++it, ++repRight) { if (last != *it) { if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen) { // insert repeat rep.beginPosition.i2 = repLeft; rep.endPosition.i2 = repRight; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } repLeft = repRight; last = *it; } } if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen) { // insert repeat rep.beginPosition.i2 = repLeft; rep.endPosition.i2 = repRight; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } } } // main function template <typename TRepeatStore, typename TText, typename TRepeatSize, typename TPeriodSize> void findRepeats(TRepeatStore &repString, TText const &text, TRepeatSize minRepeatLen, TPeriodSize maxPeriod) { typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex; typedef typename Size<TIndex>::Type TSize; typedef typename Iterator<TIndex, TopDown<ParentLinks<> > >::Type TNodeIterator; typedef typename Fibre<TIndex, FibreSA>::Type const TSA; typedef typename Infix<TSA>::Type TOccString; typedef typename Iterator<TOccString>::Type TOccIterator; typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Value<TOccString>::Type TOcc; typedef ::std::map<TOcc,TRepeat,RepeatLess_<TOcc> > TRepeatList; if (maxPeriod < 1) return; if (maxPeriod == 1) { findRepeats(repString, text, minRepeatLen); return; } TIndex index(text); TRepeatList list; // set repeat finder parameters cargo(index).minRepeatLen = minRepeatLen; cargo(index).maxPeriod = maxPeriod; TNodeIterator nodeIt(index); TOccIterator itA, itB, itRepBegin, itEnd; TRepeat rep; for (; !atEnd(nodeIt); goNext(nodeIt)) { if (isRoot(nodeIt)) continue; // get occurrences TOccString occ = getOccurrences(nodeIt); itA = begin(occ, Standard()); itEnd = end(occ, Standard()); itRepBegin = itB = itA; TSize repLen = repLength(nodeIt); // representative length if ((TSize)minRepeatLen <= repLen) continue; TSize diff, period = 0; // period of current repeat TSize repeatLen = 0; // overall length of current repeat TSize minLen = minRepeatLen - repLen; // minimum repeat length minus length of representative for (++itB; itB != itEnd; ++itB) { diff = posSub(*itB, *itA); if (diff != period || getSeqNo(*itA) != getSeqNo(*itB)) { // is the repeat long enough? if (repeatLen >= minLen) // is the repeat self overlapping or connected? if (parentRepLength(nodeIt) < period && period <= repLen) { // insert repeat rep.beginPosition = *itRepBegin; rep.endPosition = posAdd(*itA, period); rep.period = period; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep)); } itRepBegin = itA; period = diff; repeatLen = 0; } repeatLen += period; itA = itB; } // is the last repeat long enough? if (repeatLen >= minLen) // is the repeat self overlapping or connected? if (parentRepLength(nodeIt) < period && period <= repLen) { // insert repeat rep.beginPosition = *itRepBegin; rep.endPosition = posAdd(*itA, period); rep.period = period; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep)); } } // copy low-complex regions to result string clear(repString); reserve(repString, list.size(), Exact()); typename TRepeatList::const_iterator lit = list.begin(); typename TRepeatList::const_iterator litEnd = list.end(); for (TSize i = 0; lit != litEnd; ++lit, ++i) appendValue(repString, (*lit).second); } } // namespace seqan #endif
ChMatrix.h
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #ifndef CHMATRIX_H #define CHMATRIX_H #include <immintrin.h> #include "chrono/core/ChCoordsys.h" #include "chrono/core/ChException.h" #include "chrono/ChConfig.h" #include "chrono/serialization/ChArchive.h" #include "chrono/serialization/ChArchiveAsciiDump.h" namespace chrono { // // FAST MACROS TO SPEEDUP CODE // #define Set33Element(a, b, val) SetElementN(((a * 3) + (b)), val) #define Get33Element(a, b) GetElementN((a * 3) + (b)) #define Set34Element(a, b, val) SetElementN(((a * 4) + (b)), val) #define Get34Element(a, b) GetElementN((a * 4) + (b)) #define Set34Row(ma, a, val0, val1, val2, val3) \ ma.SetElementN((a * 4), val0); \ ma.SetElementN((a * 4) + 1, val1); \ ma.SetElementN((a * 4) + 2, val2); \ ma.SetElementN((a * 4) + 3, val3); #define Set44Element(a, b, val) SetElementN(((a * 4) + (b)), val) #define Get44Element(a, b) GetElementN((a * 4) + (b)) // forward declaration template <class Real = double> class ChMatrixDynamic; /// /// ChMatrix: /// /// A base class for matrix objects (tables of NxM numbers). /// To access elements, the indexes start from zero, and /// you must indicate first row, then column, that is: m(2,4) /// means the element at 3rd row, 5th column. /// This is an abstract class, so you cannot instantiate /// objects from it: you must rather create matrices using the /// specialized child classes like ChMatrixDynamic, ChMatrixNM, /// ChMatrix33 and so on; all of them have this same base class. /// Warning: for optimization reasons, not all functions will /// check about boundaries of element indexes and matrix sizes (in /// some cases, if sizes are wrong, debug asserts are used). /// /// Further info at the @ref mathematical_objects manual page. template <class Real = double> class ChMatrix { protected: // // DATA // int rows; int columns; Real* address; public: // // CONSTRUCTORS (none - abstract class that must be implemented with child classes) // virtual ~ChMatrix() {} // // OPERATORS OVERLOADING // /// Parenthesis () operator, to access a single element of the matrix, by /// supplying the row and the column (indexes start from 0). /// For example: m(3,5) gets the element at the 4th row, 6th column. /// Value is returned by reference, so it can be modified, like in m(1,2)=10. Real& operator()(const int row, const int col) { assert(row >= 0 && col >= 0 && row < rows && col < columns); return (*(address + col + (row * columns))); } const Real& operator()(const int row, const int col) const { assert(row >= 0 && col >= 0 && row < rows && col < columns); return (*(address + col + (row * columns))); } /// Parenthesis () operator, to access a single element of the matrix, by /// supplying the ordinal of the element (indexes start from 0). /// For example: m(3) gets the 4th element, counting row by row. /// Mostly useful if the matrix is Nx1 sized (i.e. a N-element vector). /// Value is returned by reference, so it can be modified, like in m(1,2)=10. Real& operator()(const int el) { assert(el >= 0 && el < rows * columns); return (*(address + el)); } const Real& operator()(const int el) const { assert(el >= 0 && el < rows * columns); return (*(address + el)); } /// The [] operator returns the address of the n-th row. This is mostly /// for compatibility with old matrix programming styles (2d array-like) /// where to access an element at row i, column j, one can write mymatrix[i][j]. Real* operator[](const int row) { assert(row >= 0 && row < rows); return ((address + (row * columns))); } const Real* operator[](const int row) const { assert(row >= 0 && row < rows); return ((address + (row * columns))); } /// Multiplies this matrix by a factor, in place ChMatrix<Real>& operator*=(const Real factor) { MatrScale(factor); return *this; } /// Increments this matrix by another matrix, in place template <class RealB> ChMatrix<Real>& operator+=(const ChMatrix<RealB>& matbis) { MatrInc(matbis); return *this; } /// Decrements this matrix by another matrix, in place template <class RealB> ChMatrix<Real>& operator-=(const ChMatrix<RealB>& matbis) { MatrDec(matbis); return *this; } /// Matrices are equal? bool operator==(const ChMatrix<Real>& other) { return Equals(other); } /// Matrices are not equal? bool operator!=(const ChMatrix<Real>& other) { return !Equals(other); } /// Assignment operator ChMatrix<Real>& operator=(const ChMatrix<Real>& matbis) { if (&matbis != this) CopyFromMatrix(matbis); return *this; } template <class RealB> ChMatrix<Real>& operator=(const ChMatrix<RealB>& matbis) { CopyFromMatrix(matbis); return *this; } // // FUNCTIONS // /// Sets the element at row,col position. Indexes start with zero. void SetElement(int row, int col, Real elem) { assert(row >= 0 && col >= 0 && row < rows && col < columns); // boundary checks *(address + col + (row * columns)) = elem; } /// Gets the element at row,col position. Indexes start with zero. /// The return value is a copy of original value. Use Element() instead if you /// want to access directly by reference the original element. Real GetElement(int row, int col) { assert(row >= 0 && col >= 0 && row < rows && col < columns); // boundary checks return (*(address + col + (row * columns))); } Real GetElement(int row, int col) const { assert(row >= 0 && col >= 0 && row < rows && col < columns); // boundary checks return (*(address + col + (row * columns))); } /// Sets the Nth element, counting row after row. void SetElementN(int index, Real elem) { assert(index >= 0 && index < (rows * columns)); // boundary checks *(address + index) = elem; } /// Gets the Nth element, counting row after row. Real GetElementN(int index) { assert(index >= 0 && index < (rows * columns)); return (*(address + index)); } const Real GetElementN(int index) const { assert(index >= 0 && index < (rows * columns)); return (*(address + index)); } /// Access a single element of the matrix, by /// supplying the row and the column (indexes start from 0). /// Value is returned by reference, so it can be modified, like in m.Element(1,2)=10. Real& Element(int row, int col) { assert(row >= 0 && col >= 0 && row < rows && col < columns); return (*(address + col + (row * columns))); } const Real& Element(int row, int col) const { assert(row >= 0 && col >= 0 && row < rows && col < columns); return (*(address + col + (row * columns))); } /// Access a single element of the matrix, the Nth element, counting row after row. /// Value is returned by reference, so it can be modified, like in m.Element(5)=10. Real& ElementN(int index) { assert(index >= 0 && index < (rows * columns)); return (*(address + index)); } const Real& ElementN(int index) const { assert(index >= 0 && index < (rows * columns)); return (*(address + index)); } /// Access directly the "Real* address" buffer. Warning! this is a low level /// function, it should be used in rare cases, if really needed! Real* GetAddress() { return address; } const Real* GetAddress() const { return address; } /// Gets the number of rows int GetRows() const { return rows; } /// Gets the number of columns int GetColumns() const { return columns; } /// Reallocate memory for a new size. VIRTUAL! Must be implemented by child classes! virtual void Resize(int nrows, int ncols) {} /// Swaps the columns a and b void SwapColumns(int a, int b) { Real temp; for (int i = 0; i < rows; i++) { temp = GetElement(i, a); SetElement(i, a, GetElement(i, b)); SetElement(i, b, temp); } } /// Swap the rows a and b void SwapRows(int a, int b) { Real temp; for (int i = 0; i < columns; i++) { temp = GetElement(a, i); SetElement(a, i, GetElement(b, i)); SetElement(b, i, temp); } } /// Fill the diagonal elements, given a sample. /// Note that the matrix must already be square (no check for /// rectangular matrices!), and the extra-diagonal elements are /// not modified -this function does not set them to 0- void FillDiag(Real sample) { for (int i = 0; i < rows; ++i) SetElement(i, i, sample); } /// Fill the matrix with the same value in all elements void FillElem(Real sample) { for (int i = 0; i < rows * columns; ++i) SetElementN(i, sample); } /// Fill the matrix with random float numbers, falling within the /// "max"/"min" range. void FillRandom(Real max, Real min) { for (int i = 0; i < rows * columns; ++i) SetElementN(i, min + (Real)ChRandom() * (max - min)); } /// Resets the matrix to zero (warning: simply sets memory to 0 bytes!) void Reset() { // SetZero(rows*columns); //memset(address, 0, sizeof(Real) * rows * columns); for (int i = 0; i < rows * columns; ++i) this->address[i] = 0; } /// Reset to zeroes and (if needed) changes the size to have row and col void Reset(int nrows, int ncols) { Resize(nrows, ncols); // SetZero(rows*columns); //memset(address, 0, sizeof(Real) * rows * columns); for (int i = 0; i < rows * columns; ++i) this->address[i] = 0; } /// Reset to identity matrix (ones on diagonal, zero elsewhere) void SetIdentity() { Reset(); FillDiag(1.0); } /// Copy a matrix "matra" into this matrix. Note that /// the destination matrix will be resized if necessary. template <class RealB> void CopyFromMatrix(const ChMatrix<RealB>& matra) { Resize(matra.GetRows(), matra.GetColumns()); // ElementsCopy(address, matra.GetAddress(), rows*columns); // memcpy (address, matra.address, (sizeof(Real) * rows * columns)); for (int i = 0; i < rows * columns; ++i) address[i] = (Real)matra.GetAddress()[i]; } /// Copy the transpose of matrix "matra" into this matrix. Note that /// the destination matrix will be resized if necessary. template <class RealB> void CopyFromMatrixT(const ChMatrix<RealB>& matra) { Resize(matra.GetColumns(), matra.GetRows()); for (int i = 0; i < matra.GetRows(); ++i) for (int j = 0; j < matra.GetColumns(); ++j) SetElement(j, i, (Real)matra.Element(i, j)); } /// Copy the transposed upper triangular part of "matra" in the lower triangular /// part of this matrix. (matra must be square) /// Note that the destination matrix will be resized if necessary. template <class RealB> // _______ // void CopyTUpMatrix(const ChMatrix<RealB>& matra) // \ | |\ // { // \ A'| ---> | \ // Resize(matra.GetRows(), matra.GetColumns()); // \ | |this\ // for (int i = 0; i < matra.GetRows(); i++) { // \| |______\ // for (int j = 0; j < matra.GetRows(); j++) SetElement(j, i, (Real)matra.GetElement(i, j)); } } /// Copy the transposed lower triangulat part of "matra" in the upper triangular /// part of this matrix. (matra must be square) /// Note that the destination matrix will be resized if necessary. template <class RealB> // _______ // void CopyTLwMatrix(const ChMatrix<RealB>& matra) // |\ \ | // { // | \ ---> \this| // Resize(matra.GetRows(), matra.GetColumns()); // |A' \ \ | // for (int i = 0; i < matra.GetRows(); i++) { // |______\ \| // for (int j = 0; j < matra.GetRows(); j++) SetElement(i, j, (Real)matra.GetElement(j, i)); } } // // STREAMING // /// Method to allow serialization of transient data in archives. virtual void ArchiveOUT(ChArchiveOut& marchive) { // suggested: use versioning marchive.VersionWrite(1); // stream out all member data marchive << make_ChNameValue("rows", rows); marchive << make_ChNameValue("columns", columns); // custom output of matrix data as array if (ChArchiveAsciiDump* mascii = dynamic_cast<ChArchiveAsciiDump*>(&marchive)) { // CUSTOM row x col 'intuitive' table-like log when using ChArchiveAsciiDump: for (int i = 0; i < rows; i++) { mascii->indent(); for (int j = 0; j < columns; j++) { (*mascii->GetStream()) << Element(i, j); mascii->GetStream()->operator<<(", "); } mascii->GetStream()->operator<<("\n"); } } else { // NORMAL array-based serialization: int tot_elements = GetRows() * GetColumns(); marchive.out_array_pre("data", tot_elements, typeid(Real).name()); for (int i = 0; i < tot_elements; i++) { marchive << CHNVP(ElementN(i), ""); marchive.out_array_between(tot_elements, typeid(Real).name()); } marchive.out_array_end(tot_elements, typeid(Real).name()); } } /// Method to allow de serialization of transient data from archives. virtual void ArchiveIN(ChArchiveIn& marchive) { // suggested: use versioning int version = marchive.VersionRead(); // stream in all member data int m_row, m_col; marchive >> make_ChNameValue("rows", m_row); marchive >> make_ChNameValue("columns", m_col); Reset(m_row, m_col); // custom input of matrix data as array size_t tot_elements = GetRows() * GetColumns(); marchive.in_array_pre("data", tot_elements); for (int i = 0; i < tot_elements; i++) { marchive >> CHNVP(ElementN(i)); marchive.in_array_between("data"); } marchive.in_array_end("data"); } /// Method to allow serializing transient data into in ascii /// as a readable item, for example "chrono::GetLog() << myobject;" /// ***OBSOLETE*** void StreamOUT(ChStreamOutAscii& mstream) { mstream << "\n" << "Matrix " << GetRows() << " rows, " << GetColumns() << " columns." << "\n"; for (int i = 0; i < ChMin(GetRows(), 8); i++) { for (int j = 0; j < ChMin(GetColumns(), 8); j++) mstream << GetElement(i, j) << " "; if (GetColumns() > 8) mstream << "..."; mstream << "\n"; } if (GetRows() > 8) mstream << "... \n\n"; } /// Method to allow serializing transient data into an ascii stream (ex. a file) /// as a Matlab .dat file (all numbers in a row, separated by space, then CR) void StreamOUTdenseMatlabFormat(ChStreamOutAscii& mstream) { for (int ii = 0; ii < this->GetRows(); ii++) { for (int jj = 0; jj < this->GetColumns(); jj++) { mstream << this->GetElement(ii, jj); if (jj < (this->GetColumns() - 1)) mstream << " "; } mstream << "\n"; } } // // MATH MEMBER FUNCTIONS. // For speed reasons, sometimes size checking of operands is left to the user! // /// Changes the sign of all the elements of this matrix, in place. void MatrNeg() { for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) = -ElementN(nel); } /// Sum two matrices, and stores the result in "this" matrix: [this]=[A]+[B]. template <class RealB, class RealC> void MatrAdd(const ChMatrix<RealB>& matra, const ChMatrix<RealC>& matrb) { assert(matra.GetColumns() == matrb.GetColumns() && matra.rows == matrb.GetRows()); assert(this->columns == matrb.GetColumns() && this->rows == matrb.GetRows()); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) = (Real)(matra.ElementN(nel) + matrb.ElementN(nel)); } /// Subtract two matrices, and stores the result in "this" matrix: [this]=[A]-[B]. template <class RealB, class RealC> void MatrSub(const ChMatrix<RealB>& matra, const ChMatrix<RealC>& matrb) { assert(matra.GetColumns() == matrb.GetColumns() && matra.rows == matrb.GetRows()); assert(this->columns == matrb.GetColumns() && this->rows == matrb.GetRows()); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) = (Real)(matra.ElementN(nel) - matrb.ElementN(nel)); } /// Increments this matrix with another matrix A, as: [this]+=[A] template <class RealB> void MatrInc(const ChMatrix<RealB>& matra) { assert(matra.GetColumns() == columns && matra.GetRows() == rows); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) += (Real)matra.ElementN(nel); } /// Decrements this matrix with another matrix A, as: [this]-=[A] template <class RealB> void MatrDec(const ChMatrix<RealB>& matra) { assert(matra.GetColumns() == columns && matra.GetRows() == rows); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) -= (Real)matra.ElementN(nel); } /// Scales a matrix, multiplying all elements by a constant value: [this]*=f void MatrScale(Real factor) { for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) *= factor; } /// Scales a matrix, multiplying all element by all oter elements of /// matra (it is not the classical matrix multiplication!) template <class RealB> void MatrScale(const ChMatrix<RealB>& matra) { assert(matra.GetColumns() == columns && matra.GetRows() == rows); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) *= (Real)matra.ElementN(nel); } /// Scales a matrix, dividing all elements by a constant value: [this]/=f void MatrDivScale(Real factor) { for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) /= factor; } /// Scales a matrix, dividing all element by all oter elements of /// matra (it is not the classical matrix multiplication!) template <class RealB> void MatrDivScale(const ChMatrix<RealB>& matra) { assert(matra.GetColumns() == columns && matra.GetRows() == rows); for (int nel = 0; nel < rows * columns; ++nel) ElementN(nel) /= (Real)matra.ElementN(nel); } /// Multiplies two matrices, and stores the result in "this" matrix: [this]=[A]*[B]. template <class RealB, class RealC> void MatrMultiply(const ChMatrix<RealB>& matra, const ChMatrix<RealC>& matrb) { assert(matra.GetColumns() == matrb.GetRows()); assert(this->rows == matra.GetRows()); assert(this->columns == matrb.GetColumns()); int col, row, colres; Real sum; for (colres = 0; colres < matrb.GetColumns(); ++colres) { for (row = 0; row < matra.GetRows(); ++row) { sum = 0; for (col = 0; col < matra.GetColumns(); ++col) sum += (Real)(matra.Element(row, col) * matrb.Element(col, colres)); SetElement(row, colres, sum); } } } #ifdef CHRONO_HAS_AVX /// Multiplies two matrices, and stores the result in "this" matrix: [this]=[A]*[B]. /// AVX implementation: The speed up is marginal if size of the matrices are small, e.g. 3*3 /// Generally, as the matra.GetColumns() increases the method performs better void MatrMultiplyAVX(const ChMatrix<double>& matra, const ChMatrix<double>& matrb) { assert(matra.GetColumns() == matrb.GetRows()); assert(this->rows == matra.GetRows()); assert(this->columns == matrb.GetColumns()); int A_Nrow = matra.GetRows(); int B_Nrow = matrb.GetRows(); int A_NCol = matra.GetColumns(); int B_NCol = matrb.GetColumns(); const double* A_add = matra.GetAddress(); const double* B_add = matrb.GetAddress(); double* this_Add = this->GetAddress(); for (int rowA = 0; rowA < A_Nrow; rowA++) { for (int colB = 0; colB < B_NCol; colB += 4) { __m256d sum = _mm256_setzero_pd(); for (int elem = 0; elem < A_NCol; elem++) { __m256d ymmA = _mm256_broadcast_sd(A_add + A_NCol * rowA + elem); __m256d ymmB = _mm256_loadu_pd(B_add + elem * B_NCol + colB); __m256d prod = _mm256_mul_pd(ymmA, ymmB); sum = _mm256_add_pd(sum, prod); } _mm256_storeu_pd(this_Add + rowA * B_NCol + colB, sum); } } } /// Multiplies two matrices (the second is considered transposed): [this]=[A]*[B]' /// Note: This method is faster than MatrMultiplyT if matra.GetColumns()%4=0 && matra.GetColumns()>8 /// It is still fast if matra.GetColumns() is large enough even if matra.GetColumns()%4!=0 void MatrMultiplyTAVX(const ChMatrix<double>& matra, const ChMatrix<double>& matrb) { assert(matra.GetColumns() == matrb.GetColumns()); assert(this->GetRows() == matra.GetRows()); assert(this->GetColumns() == matrb.GetRows()); int A_Nrow = matra.GetRows(); int B_Nrow = matrb.GetRows(); int A_NCol = matra.GetColumns(); int B_NCol = matrb.GetColumns(); const double* A_add = matra.GetAddress(); const double* B_add = matrb.GetAddress(); bool NeedsPadding = (B_NCol % 4 != 0); int CorrectFAT = ((B_NCol >> 2) << 2); for (int rowA = 0; rowA < A_Nrow; rowA++) { for (int rowB = 0; rowB < B_Nrow; rowB++) { int colB; double temp_sum = 0.0; __m256d sum = _mm256_setzero_pd(); for (colB = 0; colB < CorrectFAT; colB += 4) { __m256d ymmA = _mm256_loadu_pd(A_add + rowA * A_NCol + colB); __m256d ymmB = _mm256_loadu_pd(B_add + rowB * B_NCol + colB); __m256d prod = _mm256_mul_pd(ymmA, ymmB); sum = _mm256_add_pd(sum, prod); } sum = _mm256_hadd_pd(sum, sum); temp_sum = ((double*)&sum)[0] + ((double*)&sum)[2]; if (NeedsPadding) for (colB = CorrectFAT; colB < B_NCol; colB++) { temp_sum += (matra.Element(rowA, colB) * matrb.Element(rowB, colB)); } SetElement(rowA, rowB, temp_sum); } } } #endif /// Multiplies two matrices (the second is considered transposed): [this]=[A]*[B]' /// Faster than doing B.MatrTranspose(); result.MatrMultiply(A,B); /// Note: no check on mistaken size of this! template <class RealB, class RealC> void MatrMultiplyT(const ChMatrix<RealB>& matra, const ChMatrix<RealC>& matrb) { assert(matra.GetColumns() == matrb.GetColumns()); assert(this->rows == matra.GetRows()); assert(this->columns == matrb.GetRows()); int col, row, colres; Real sum; for (colres = 0; colres < matrb.GetRows(); ++colres) { for (row = 0; row < matra.GetRows(); ++row) { sum = 0; for (col = 0; col < matra.GetColumns(); ++col) sum += (Real)(matra.Element(row, col) * matrb.Element(colres, col)); SetElement(row, colres, sum); } } } /// Multiplies two matrices (the first is considered transposed): [this]=[A]'*[B] /// Faster than doing A.MatrTranspose(); result.MatrMultiply(A,B); template <class RealB, class RealC> void MatrTMultiply(const ChMatrix<RealB>& matra, const ChMatrix<RealC>& matrb) { assert(matra.GetRows() == matrb.GetRows()); assert(this->rows == matra.GetColumns()); assert(this->columns == matrb.GetColumns()); int col, row, colres; Real sum; for (colres = 0; colres < matrb.GetColumns(); ++colres) { for (row = 0; row < matra.GetColumns(); ++row) { sum = 0; for (col = 0; col < (matra.GetRows()); ++col) sum += (Real)(matra.Element(col, row) * matrb.Element(col, colres)); SetElement(row, colres, sum); } } } /// Computes dot product between two column-matrices (vectors) with /// same size. Returns a scalar value. template <class RealB, class RealC> static Real MatrDot(const ChMatrix<RealB>& ma, const ChMatrix<RealC>& mb) { assert(ma.GetColumns() == mb.GetColumns() && ma.GetRows() == mb.GetRows()); Real tot = 0; for (int i = 0; i < ma.GetRows(); ++i) tot += (Real)(ma.ElementN(i) * mb.ElementN(i)); return tot; } /// Transpose this matrix in place void MatrTranspose() { if (columns == rows) // Square transp.is optimized { for (int row = 0; row < rows; ++row) for (int col = row; col < columns; ++col) if (row != col) { Real temp = Element(row, col); Element(row, col) = Element(col, row); Element(col, row) = temp; } int tmpr = rows; rows = columns; columns = tmpr; } else // Naive implementation for rectangular case. Not in-place. Slower. { ChMatrixDynamic<Real> matrcopy(*this); int tmpr = rows; rows = columns; columns = tmpr; // dont' realloc buffer, anyway for (int row = 0; row < rows; ++row) for (int col = 0; col < columns; ++col) Element(row, col) = matrcopy.Element(col, row); } } /// Returns the determinant of the matrix. /// Note! This method must be used only with max 4x4 matrices, /// otherwise it throws an exception. Real Det() { assert(this->GetRows() == this->GetColumns()); assert(this->GetRows() <= 4); if (this->GetRows() != this->GetColumns()) throw("Cannot compute matrix determinant because rectangular matrix"); if (this->GetRows() > 4) throw("Cannot compute matrix determinant because matr. larger than 3x3"); Real det = 0; switch (this->GetRows()) { case 1: det = (*this)(0, 0); break; case 2: det = (*this)(0, 0) * (*this)(1, 1) - (*this)(0, 1) * (*this)(1, 0); break; case 3: det = (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 2) + (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 0) + (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 1) - (*this)(2, 0) * (*this)(1, 1) * (*this)(0, 2) - (*this)(2, 1) * (*this)(1, 2) * (*this)(0, 0) - (*this)(2, 2) * (*this)(1, 0) * (*this)(0, 1); break; case 4: det = (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 3) + (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 1) + (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 2) + (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 2) + (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 3) + (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 0) + (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 3) + (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 0) + (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 1) + (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 1) + (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 2) + (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 0) - (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 2) - (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 3) - (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 1) - (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 3) - (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 0) - (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 2) - (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 1) - (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 3) - (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 2) - (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 1); break; } return det; } /// Returns the inverse of the matrix. /// Note! This method must be used only with max 4x4 matrices, /// otherwise it throws an exception. void MatrInverse() { assert(this->GetRows() == this->GetColumns()); assert(this->GetRows() <= 4); assert(this->Det() != 0); if (this->GetRows() != this->GetColumns()) throw("Cannot compute matrix inverse because rectangular matrix"); if (this->GetRows() > 4) throw("Cannot compute matrix inverse because matr. larger than 4x4"); if (this->Det() == 0) throw("Cannot compute matrix inverse because singular matrix"); switch (this->GetRows()) { case 1: (*this)(0, 0) = (1 / (*this)(0, 0)); break; case 2: { ChMatrixDynamic<Real> inv(2, 2); inv(0, 0) = (*this)(1, 1); inv(0, 1) = -(*this)(0, 1); inv(1, 1) = (*this)(0, 0); inv(1, 0) = -(*this)(1, 0); inv.MatrDivScale(this->Det()); this->CopyFromMatrix(inv); break; } case 3: { ChMatrixDynamic<Real> inv(3, 3); inv(0, 0) = (*this)(1, 1) * (*this)(2, 2) - (*this)(1, 2) * (*this)(2, 1); inv(0, 1) = (*this)(2, 1) * (*this)(0, 2) - (*this)(0, 1) * (*this)(2, 2); inv(0, 2) = (*this)(0, 1) * (*this)(1, 2) - (*this)(0, 2) * (*this)(1, 1); inv(1, 0) = (*this)(1, 2) * (*this)(2, 0) - (*this)(1, 0) * (*this)(2, 2); inv(1, 1) = (*this)(2, 2) * (*this)(0, 0) - (*this)(2, 0) * (*this)(0, 2); inv(1, 2) = (*this)(0, 2) * (*this)(1, 0) - (*this)(1, 2) * (*this)(0, 0); inv(2, 0) = (*this)(1, 0) * (*this)(2, 1) - (*this)(1, 1) * (*this)(2, 0); inv(2, 1) = (*this)(0, 1) * (*this)(2, 0) - (*this)(0, 0) * (*this)(2, 1); inv(2, 2) = (*this)(0, 0) * (*this)(1, 1) - (*this)(0, 1) * (*this)(1, 0); inv.MatrDivScale(this->Det()); this->CopyFromMatrix(inv); break; } case 4: { ChMatrixDynamic<Real> inv(4, 4); inv.SetElement( 0, 0, (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 1) - (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 1) + (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 2) - (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 2) - (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 3) + (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 3)); inv.SetElement( 0, 1, (*this)(0, 3) * (*this)(2, 2) * (*this)(3, 1) - (*this)(0, 2) * (*this)(2, 3) * (*this)(3, 1) - (*this)(0, 3) * (*this)(2, 1) * (*this)(3, 2) + (*this)(0, 1) * (*this)(2, 3) * (*this)(3, 2) + (*this)(0, 2) * (*this)(2, 1) * (*this)(3, 3) - (*this)(0, 1) * (*this)(2, 2) * (*this)(3, 3)); inv.SetElement( 0, 2, (*this)(0, 2) * (*this)(1, 3) * (*this)(3, 1) - (*this)(0, 3) * (*this)(1, 2) * (*this)(3, 1) + (*this)(0, 3) * (*this)(1, 1) * (*this)(3, 2) - (*this)(0, 1) * (*this)(1, 3) * (*this)(3, 2) - (*this)(0, 2) * (*this)(1, 1) * (*this)(3, 3) + (*this)(0, 1) * (*this)(1, 2) * (*this)(3, 3)); inv.SetElement( 0, 3, (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 1) - (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 1) - (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 2) + (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 2) + (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 3) - (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 3)); inv.SetElement( 1, 0, (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 0) - (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 0) - (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 2) + (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 2) + (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 3) - (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 3)); inv.SetElement( 1, 1, (*this)(0, 2) * (*this)(2, 3) * (*this)(3, 0) - (*this)(0, 3) * (*this)(2, 2) * (*this)(3, 0) + (*this)(0, 3) * (*this)(2, 0) * (*this)(3, 2) - (*this)(0, 0) * (*this)(2, 3) * (*this)(3, 2) - (*this)(0, 2) * (*this)(2, 0) * (*this)(3, 3) + (*this)(0, 0) * (*this)(2, 2) * (*this)(3, 3)); inv.SetElement( 1, 2, (*this)(0, 3) * (*this)(1, 2) * (*this)(3, 0) - (*this)(0, 2) * (*this)(1, 3) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 0) * (*this)(3, 2) + (*this)(0, 0) * (*this)(1, 3) * (*this)(3, 2) + (*this)(0, 2) * (*this)(1, 0) * (*this)(3, 3) - (*this)(0, 0) * (*this)(1, 2) * (*this)(3, 3)); inv.SetElement( 1, 3, (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 0) - (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 0) + (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 2) - (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 2) - (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 3) + (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 3)); inv.SetElement( 2, 0, (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 0) - (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 0) + (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 1) - (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 1) - (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 3) + (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 3)); inv.SetElement( 2, 1, (*this)(0, 3) * (*this)(2, 1) * (*this)(3, 0) - (*this)(0, 1) * (*this)(2, 3) * (*this)(3, 0) - (*this)(0, 3) * (*this)(2, 0) * (*this)(3, 1) + (*this)(0, 0) * (*this)(2, 3) * (*this)(3, 1) + (*this)(0, 1) * (*this)(2, 0) * (*this)(3, 3) - (*this)(0, 0) * (*this)(2, 1) * (*this)(3, 3)); inv.SetElement( 2, 2, (*this)(0, 1) * (*this)(1, 3) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 1) * (*this)(3, 0) + (*this)(0, 3) * (*this)(1, 0) * (*this)(3, 1) - (*this)(0, 0) * (*this)(1, 3) * (*this)(3, 1) - (*this)(0, 1) * (*this)(1, 0) * (*this)(3, 3) + (*this)(0, 0) * (*this)(1, 1) * (*this)(3, 3)); inv.SetElement( 2, 3, (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 0) - (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 0) - (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 1) + (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 1) + (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 3) - (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 3)); inv.SetElement( 3, 0, (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 0) - (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 0) - (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 1) + (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 1) + (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 2) - (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 2)); inv.SetElement( 3, 1, (*this)(0, 1) * (*this)(2, 2) * (*this)(3, 0) - (*this)(0, 2) * (*this)(2, 1) * (*this)(3, 0) + (*this)(0, 2) * (*this)(2, 0) * (*this)(3, 1) - (*this)(0, 0) * (*this)(2, 2) * (*this)(3, 1) - (*this)(0, 1) * (*this)(2, 0) * (*this)(3, 2) + (*this)(0, 0) * (*this)(2, 1) * (*this)(3, 2)); inv.SetElement( 3, 2, (*this)(0, 2) * (*this)(1, 1) * (*this)(3, 0) - (*this)(0, 1) * (*this)(1, 2) * (*this)(3, 0) - (*this)(0, 2) * (*this)(1, 0) * (*this)(3, 1) + (*this)(0, 0) * (*this)(1, 2) * (*this)(3, 1) + (*this)(0, 1) * (*this)(1, 0) * (*this)(3, 2) - (*this)(0, 0) * (*this)(1, 1) * (*this)(3, 2)); inv.SetElement( 3, 3, (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 0) - (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 0) + (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 1) - (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 1) - (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 2) + (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 2)); inv.MatrDivScale(this->Det()); this->CopyFromMatrix(inv); break; } } } /// Returns true if vector is identical to other matrix bool Equals(const ChMatrix<Real>& other) { return Equals(other, 0.0); } /// Returns true if vector equals another vector, within a tolerance 'tol' bool Equals(const ChMatrix<Real>& other, Real tol) { if ((other.GetColumns() != this->columns) || (other.GetRows() != this->rows)) return false; for (int nel = 0; nel < rows * columns; ++nel) if (fabs(ElementN(nel) - other.ElementN(nel)) > tol) return false; return true; } /// Multiplies this 3x4 matrix by a quaternion, as v=[G]*q /// The matrix must be 3x4. /// \return The result of the multiplication, i.e. a vector. template <class RealB> ChVector<Real> Matr34_x_Quat(const ChQuaternion<RealB>& qua) { assert((rows == 3) && (columns == 4)); return ChVector<Real>(Get34Element(0, 0) * (Real)qua.e0() + Get34Element(0, 1) * (Real)qua.e1() + Get34Element(0, 2) * (Real)qua.e2() + Get34Element(0, 3) * (Real)qua.e3(), Get34Element(1, 0) * (Real)qua.e0() + Get34Element(1, 1) * (Real)qua.e1() + Get34Element(1, 2) * (Real)qua.e2() + Get34Element(1, 3) * (Real)qua.e3(), Get34Element(2, 0) * (Real)qua.e0() + Get34Element(2, 1) * (Real)qua.e1() + Get34Element(2, 2) * (Real)qua.e2() + Get34Element(2, 3) * (Real)qua.e3()); } /// Multiplies this 3x4 matrix (transposed) by a vector, as q=[G]'*v /// The matrix must be 3x4. /// \return The result of the multiplication, i.e. a quaternion. template <class RealB> ChQuaternion<Real> Matr34T_x_Vect(const ChVector<RealB>& va) { assert((rows == 3) && (columns == 4)); return ChQuaternion<Real>( Get34Element(0, 0) * (Real)va.x() + Get34Element(1, 0) * (Real)va.y() + Get34Element(2, 0) * (Real)va.z(), Get34Element(0, 1) * (Real)va.x() + Get34Element(1, 1) * (Real)va.y() + Get34Element(2, 1) * (Real)va.z(), Get34Element(0, 2) * (Real)va.x() + Get34Element(1, 2) * (Real)va.y() + Get34Element(2, 2) * (Real)va.z(), Get34Element(0, 3) * (Real)va.x() + Get34Element(1, 3) * (Real)va.y() + Get34Element(2, 3) * (Real)va.z()); } /// Multiplies this 4x4 matrix (transposed) by a quaternion, /// The matrix must be 4x4. /// \return The result of the multiplication, i.e. a quaternion. template <class RealB> ChQuaternion<Real> Matr44_x_Quat(const ChQuaternion<RealB>& qua) { assert((rows == 4) && (columns == 4)); return ChQuaternion<Real>(Get44Element(0, 0) * (Real)qua.e0() + Get44Element(0, 1) * (Real)qua.e1() + Get44Element(0, 2) * (Real)qua.e2() + Get44Element(0, 3) * (Real)qua.e3(), Get44Element(1, 0) * (Real)qua.e0() + Get44Element(1, 1) * (Real)qua.e1() + Get44Element(1, 2) * (Real)qua.e2() + Get44Element(1, 3) * (Real)qua.e3(), Get44Element(2, 0) * (Real)qua.e0() + Get44Element(2, 1) * (Real)qua.e1() + Get44Element(2, 2) * (Real)qua.e2() + Get44Element(2, 3) * (Real)qua.e3(), Get44Element(3, 0) * (Real)qua.e0() + Get44Element(3, 1) * (Real)qua.e1() + Get44Element(3, 2) * (Real)qua.e2() + Get44Element(3, 3) * (Real)qua.e3()); } /// Transposes only the lower-right 3x3 submatrix of a hemisymmetric 4x4 matrix, /// used when the 4x4 matrix is a "star" matrix [q] coming from a quaternion q: /// the non commutative quat. product is: /// q1 x q2 = [q1]*q2 = [q2st]*q1 /// where [q2st] is the "semi-transpose of [q2]. void MatrXq_SemiTranspose() { SetElement(1, 2, -GetElement(1, 2)); SetElement(1, 3, -GetElement(1, 3)); SetElement(2, 1, -GetElement(2, 1)); SetElement(2, 3, -GetElement(2, 3)); SetElement(3, 1, -GetElement(3, 1)); SetElement(3, 2, -GetElement(3, 2)); } /// Change the sign of the 2nd, 3rd and 4th columns of a 4x4 matrix, /// The product between a quaternion q1 and the conjugate of q2 (q2'), is: /// q1 x q2' = [q1]*q2' = [q1sn]*q2 /// where [q1sn] is the semi-negation of the 4x4 matrix [q1]. void MatrXq_SemiNeg() { for (int i = 0; i < rows; ++i) for (int j = 1; j < columns; ++j) SetElement(i, j, -GetElement(i, j)); } /// Gets the norm infinite of the matrix, i.e. the max. /// of its elements in absolute value. Real NormInf() { Real norm = 0; for (int nel = 0; nel < rows * columns; ++nel) if ((fabs(ElementN(nel))) > norm) norm = fabs(ElementN(nel)); return norm; } /// Gets the norm two of the matrix, i.e. the square root /// of the sum of the elements squared. Real NormTwo() { Real norm = 0; for (int nel = 0; nel < rows * columns; ++nel) norm += ElementN(nel) * ElementN(nel); return (sqrt(norm)); } /// Finds max value among the values of the matrix Real Max() { Real mmax = GetElement(0, 0); for (int nel = 0; nel < rows * columns; ++nel) if (ElementN(nel) > mmax) mmax = ElementN(nel); return mmax; } /// Finds min value among the values of the matrix Real Min() { Real mmin = GetElement(0, 0); for (int nel = 0; nel < rows * columns; ++nel) if (ElementN(nel) < mmin) mmin = ElementN(nel); return mmin; } /// Linear interpolation of two matrices. Parameter mx must be 0...1. /// [this] =(1-x)[A]+ (x)[B] Matrices must have the same size!! void LinInterpolate(const ChMatrix<Real>& matra, const ChMatrix<Real>& matrb, Real mx) { assert(matra.columns == matrb.columns && matra.rows == matrb.rows); for (int nel = 0; nel < rows * columns; nel++) ElementN(nel) = matra.ElementN(nel) * (1 - mx) + matrb.ElementN(nel) * (mx); } /// Fills a matrix or a vector with a bilinear interpolation, /// from corner values (as a u-v patch). void RowColInterp(Real vmin, Real vmax, Real umin, Real umax) { for (int iu = 0; iu < GetColumns(); iu++) for (int iv = 0; iv < GetRows(); iv++) { if (GetRows() > 1) Element(iv, iu) = vmin + (vmax - vmin) * ((Real)iv / ((Real)(GetRows() - 1))); if (GetColumns() > 1) Element(iv, iu) += umin + (umax - umin) * ((Real)iu / ((Real)(GetColumns() - 1))); } } // // BOOKKEEPING // /// Paste a matrix "matra" into "this", inserting at location insrow-inscol. /// Normal copy for insrow=inscol=0 template <class RealB> void PasteMatrix(const ChMatrix<RealB>& matra, int insrow, int inscol) { for (int i = 0; i < matra.GetRows(); ++i) for (int j = 0; j < matra.GetColumns(); ++j) Element(i + insrow, j + inscol) = (Real)matra.Element(i, j); } /// Paste a matrix "matra" into "this", inserting at location insrow-inscol /// and performing a sum with the preexisting values. template <class RealB> void PasteSumMatrix(const ChMatrix<RealB>& matra, int insrow, int inscol) { for (int i = 0; i < matra.GetRows(); ++i) for (int j = 0; j < matra.GetColumns(); ++j) Element(i + insrow, j + inscol) += (Real)matra.Element(i, j); } /// Paste a matrix "matra", transposed, into "this", inserting at location insrow-inscol. /// Normal copy for insrow=inscol=0 template <class RealB> void PasteTranspMatrix(const ChMatrix<RealB>& matra, int insrow, int inscol) { for (int i = 0; i < matra.GetRows(); ++i) for (int j = 0; j < matra.GetColumns(); ++j) Element(j + insrow, i + inscol) = (Real)matra.Element(i, j); } /// Paste a matrix "matra", transposed, into "this", inserting at location insrow-inscol /// and performing a sum with the preexisting values. template <class RealB> void PasteSumTranspMatrix(const ChMatrix<RealB>& matra, int insrow, int inscol) { for (int i = 0; i < matra.GetRows(); ++i) for (int j = 0; j < matra.GetColumns(); ++j) Element(j + insrow, i + inscol) += (Real)matra.Element(i, j); } /// Paste a clipped portion of the matrix "matra" into "this", /// inserting the clip (of size nrows, ncolumns) at the location insrow-inscol. template <class RealB> void PasteClippedMatrix(const ChMatrix<RealB>& matra, int cliprow, int clipcol, int nrows, int ncolumns, int insrow, int inscol) { for (int i = 0; i < nrows; ++i) for (int j = 0; j < ncolumns; ++j) Element(i + insrow, j + inscol) = (Real)matra.Element(i + cliprow, j + clipcol); } /// Paste a clipped portion of the matrix "matra" into "this", where "this" /// is a vector (of ChMatrix type), /// inserting the clip (of size nrows, ncolumns) at the location insindex. template <class RealB> void PasteClippedMatrixToVector(const ChMatrix<RealB>& matra, int cliprow, int clipcol, int nrows, int ncolumns, int insindex) { for (int i = 0; i < nrows; ++i) for (int j = 0; j < ncolumns; ++j) ElementN(insindex + i * ncolumns + j) = (Real)matra.Element(cliprow + i, clipcol + j); } /// Paste a clipped portion of a vector into "this", where "this" /// is a matrix (of ChMatrix type), /// inserting the clip (of size nrows, ncolumns) at the location insindex. template <class RealB> void PasteClippedVectorToMatrix(const ChMatrix<RealB>& matra, int cliprow, int clipcol, int nrows, int ncolumns, int insindex) { for (int i = 0; i < nrows; ++i) for (int j = 0; j < ncolumns; ++j) Element(i + cliprow, j + clipcol) = (Real)matra.ElementN(insindex + i * ncolumns + j); } /// Paste a clipped portion of the matrix "matra" into "this", performing a sum with preexisting values, /// inserting the clip (of size nrows, ncolumns) at the location insrow-inscol. template <class RealB> void PasteSumClippedMatrix(const ChMatrix<RealB>& matra, int cliprow, int clipcol, int nrows, int ncolumns, int insrow, int inscol) { for (int i = 0; i < nrows; ++i) for (int j = 0; j < ncolumns; ++j) #pragma omp atomic Element(i + insrow, j + inscol) += (Real)matra.Element(i + cliprow, j + clipcol); } /// Paste a vector "va" into the matrix. template <class RealB> void PasteVector(const ChVector<RealB>& va, int insrow, int inscol) { SetElement(insrow + 0, inscol, (Real)va.x()); SetElement(insrow + 1, inscol, (Real)va.y()); SetElement(insrow + 2, inscol, (Real)va.z()); } /// Paste a vector "va" into the matrix, summing it with preexisting values. template <class RealB> void PasteSumVector(const ChVector<RealB>& va, int insrow, int inscol) { Element(insrow + 0, inscol) += (Real)va.x(); Element(insrow + 1, inscol) += (Real)va.y(); Element(insrow + 2, inscol) += (Real)va.z(); } /// Paste a vector "va" into the matrix, subtracting it from preexisting values. template <class RealB> void PasteSubVector(const ChVector<RealB>& va, int insrow, int inscol) { Element(insrow + 0, inscol) -= (Real)va.x(); Element(insrow + 1, inscol) -= (Real)va.y(); Element(insrow + 2, inscol) -= (Real)va.z(); } /// Paste a quaternion into the matrix. template <class RealB> void PasteQuaternion(const ChQuaternion<RealB>& qa, int insrow, int inscol) { SetElement(insrow + 0, inscol, (Real)qa.e0()); SetElement(insrow + 1, inscol, (Real)qa.e1()); SetElement(insrow + 2, inscol, (Real)qa.e2()); SetElement(insrow + 3, inscol, (Real)qa.e3()); } /// Paste a quaternion into the matrix, summing it with preexisting values. template <class RealB> void PasteSumQuaternion(const ChQuaternion<RealB>& qa, int insrow, int inscol) { Element(insrow + 0, inscol) += (Real)qa.e0(); Element(insrow + 1, inscol) += (Real)qa.e1(); Element(insrow + 2, inscol) += (Real)qa.e2(); Element(insrow + 3, inscol) += (Real)qa.e3(); } /// Paste a coordsys into the matrix. template <class RealB> void PasteCoordsys(const ChCoordsys<RealB>& cs, int insrow, int inscol) { PasteVector(cs.pos, insrow, inscol); PasteQuaternion(cs.rot, insrow + 3, inscol); } /// Returns the vector clipped from insrow, inscol. ChVector<Real> ClipVector(int insrow, int inscol) const { return ChVector<Real>(Element(insrow, inscol), Element(insrow + 1, inscol), Element(insrow + 2, inscol)); } /// Returns the quaternion clipped from insrow, inscol. ChQuaternion<Real> ClipQuaternion(int insrow, int inscol) const { return ChQuaternion<Real>(Element(insrow, inscol), Element(insrow + 1, inscol), Element(insrow + 2, inscol), Element(insrow + 3, inscol)); } /// Returns the coordsys clipped from insrow, inscol. ChCoordsys<Real> ClipCoordsys(int insrow, int inscol) const { return ChCoordsys<Real>(ClipVector(insrow, inscol), ClipQuaternion(insrow + 3, inscol)); } // // MULTIBODY SPECIFIC MATH FUCTION // /// Fills a 4x4 matrix as the "star" matrix, representing quaternion cross product. /// That is, given two quaternions a and b, aXb= [Astar]*b template <class RealB> void Set_Xq_matrix(const ChQuaternion<RealB>& q) { Set44Element(0, 0, (Real)q.e0()); Set44Element(0, 1, -(Real)q.e1()); Set44Element(0, 2, -(Real)q.e2()); Set44Element(0, 3, -(Real)q.e3()); Set44Element(1, 0, (Real)q.e1()); Set44Element(1, 1, (Real)q.e0()); Set44Element(1, 2, -(Real)q.e3()); Set44Element(1, 3, (Real)q.e2()); Set44Element(2, 0, (Real)q.e2()); Set44Element(2, 1, (Real)q.e3()); Set44Element(2, 2, (Real)q.e0()); Set44Element(2, 3, -(Real)q.e1()); Set44Element(3, 0, (Real)q.e3()); Set44Element(3, 1, -(Real)q.e2()); Set44Element(3, 2, (Real)q.e1()); Set44Element(3, 3, (Real)q.e0()); } }; } // end namespace chrono #endif
NDArray.h
#ifndef NDARRAY_H #define NDARRAY_H #include <initializer_list> #include <functional> #include <shape.h> #include "NativeOpExcutioner.h" #include <memory/Workspace.h> #include <indexing/NDIndex.h> #include <indexing/IndicesList.h> #include <graph/Intervals.h> #include <array/DataType.h> #include <stdint.h> namespace nd4j { template<typename T> class ND4J_EXPORT NDArray; ND4J_EXPORT NDArray<float> operator-(const float, const NDArray<float>&); ND4J_EXPORT NDArray<float16> operator-(const float16, const NDArray<float16>&); ND4J_EXPORT NDArray<double> operator-(const double, const NDArray<double>&); ND4J_EXPORT NDArray<float> operator+(const float, const NDArray<float>&); ND4J_EXPORT NDArray<float16> operator+(const float16, const NDArray<float16>&); ND4J_EXPORT NDArray<double> operator+(const double, const NDArray<double>&); template<typename T> NDArray<T> mmul(const NDArray<T>&, const NDArray<T>&); template<typename T> class NDArray { protected: /** * if true then array doesn't own buffer and simply points to another's buffer */ bool _isView = false; /** * pointer on flattened data array in memory */ T *_buffer = nullptr; /** * contains shape info: matrix rank, numbers of elements per each dimension, dimensions strides, element-wise-stride, c-like or fortan-like order */ Nd4jLong *_shapeInfo = nullptr; /** * pointer on externally allocated memory where _buffer and _shapeInfo are stored */ nd4j::memory::Workspace* _workspace = nullptr; /** * alternative buffers for special computational devices (like GPUs for CUDA) */ T* _bufferD = nullptr; Nd4jLong *_shapeInfoD = nullptr; /** * indicates whether user allocates memory for _buffer/_shapeInfo by himself, in opposite case the memory must be allocated from outside */ bool _isShapeAlloc = false; bool _isBuffAlloc = false; /** * type of array elements */ DataType _dataType = DataType_FLOAT; std::string toStringValue(T value); public: /** * default constructor, do not allocate memory, memory for array is passed from outside */ NDArray(T *buffer = nullptr, Nd4jLong* shapeInfo = nullptr, nd4j::memory::Workspace* workspace = nullptr); NDArray(std::initializer_list<Nd4jLong> shape, nd4j::memory::Workspace* workspace = nullptr); /** * Constructor for scalar NDArray */ NDArray(T scalar); /** * copy constructor */ NDArray(const NDArray<T>& other); /** * move constructor */ NDArray(NDArray<T>&& other) noexcept; #ifndef __JAVACPP_HACK__ // this method only available out of javacpp /** * This constructor creates vector of T * * @param values */ NDArray(std::initializer_list<T> values, nd4j::memory::Workspace* workspace = nullptr); NDArray(std::vector<T> &values, nd4j::memory::Workspace* workspace = nullptr); #endif /** * constructor, create empty array stored at given workspace */ NDArray(nd4j::memory::Workspace* workspace); /** * this constructor creates new NDArray with shape matching "other" array, do not copy "other" elements into new array */ NDArray(const NDArray<T> *other, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr); /** * constructor creates new NDArray using shape information from "shapeInfo", set all elements in new array to be zeros, if copyStrides is true then use stride values from "shapeInfo", else calculate strides independently */ NDArray(const Nd4jLong* shapeInfo, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr); /** * this constructor creates new array using shape information contained in vector argument */ NDArray(const char order, const std::vector<Nd4jLong> &shape, nd4j::memory::Workspace* workspace = nullptr); /** * This constructor creates new array with elements copied from data and using shape information stored in shape * * PLEASE NOTE: data will be copied AS IS, without respect to specified order. You must ensure order match here. */ NDArray(const char order, const std::vector<Nd4jLong> &shape, const std::vector<T> &data, nd4j::memory::Workspace* workspace = nullptr); /** * this constructor creates new array using given buffer (without memory allocating) and shape information stored in shape */ NDArray(T *buffer, const char order, const std::vector<Nd4jLong> &shape , nd4j::memory::Workspace* workspace = nullptr); /** * copy assignment operator */ NDArray<T>& operator=(const NDArray<T>& other); /** * move assignment operator */ NDArray<T>& operator=(NDArray<T>&& other) noexcept; /** * assignment operator, assigns the same scalar to all array elements */ NDArray<T>& operator=(const T scalar); /** * operators for memory allocation and deletion */ void* operator new(size_t i); void operator delete(void* p); /** * method replaces existing buffer/shapeinfo, AND releases original pointers (if releaseExisting TRUE) */ void replacePointers(T *buffer, Nd4jLong *shapeInfo, const bool releaseExisting = true); /** * create a new array by replicating current array by repeats times along given dimension * dimension - dimension along which to repeat elements * repeats - number of repetitions */ NDArray<T>* repeat(int dimension, const std::vector<Nd4jLong>& repeats) const; /** * fill target array by repeating current array * dimension - dimension along which to repeat elements */ void repeat(int dimension, NDArray<T>& target) const; /** * return _dataType; */ DataType dataType() const; /** * creates array which is view of this array */ NDArray<T>* getView(); /** * creates array which points on certain sub-range of this array, sub-range is defined by given indices */ NDArray<T> *subarray(IndicesList& indices) const; NDArray<T> *subarray(IndicesList& indices, std::vector<Nd4jLong>& strides) const; NDArray<T>* subarray(const std::initializer_list<NDIndex*>& idx) const; NDArray<T>* subarray(const Intervals& idx) const; /** * cast array elements to given dtype */ NDArray<T>* cast(DataType dtype); void cast(NDArray<T>* target, DataType dtype); /** * returns _workspace */ nd4j::memory::Workspace* getWorkspace() const { return _workspace; } /** * returns _buffer */ T* getBuffer(); T* buffer(); /** * returns _shapeInfo */ Nd4jLong* shapeInfo(); Nd4jLong* getShapeInfo() const; /** * if _bufferD==nullptr return _buffer, else return _bufferD */ T* specialBuffer(); /** * if _shapeInfoD==nullptr return _shapeInfo, else return _shapeInfoD */ Nd4jLong* specialShapeInfo(); /** * set values for _bufferD and _shapeInfoD */ void setSpecialBuffers(T * buffer, Nd4jLong *shape); /** * permutes (in-place) the dimensions in array according to "dimensions" array */ bool permutei(const std::initializer_list<int>& dimensions); bool permutei(const std::vector<int>& dimensions); bool permutei(const int* dimensions, const int rank); bool permutei(const std::initializer_list<Nd4jLong>& dimensions); bool permutei(const std::vector<Nd4jLong>& dimensions); bool permutei(const Nd4jLong* dimensions, const int rank); /** * permutes the dimensions in array according to "dimensions" array, new array points on _buffer of this array */ NDArray<T>* permute(const std::initializer_list<int>& dimensions) const; NDArray<T>* permute(const std::vector<int>& dimensions) const; NDArray<T>* permute(const int* dimensions, const int rank) const; void permute(const int* dimensions, const int rank, NDArray<T>& target) const; void permute(const std::vector<int>& dimensions, NDArray<T>& target) const; NDArray<T>* permute(const std::initializer_list<Nd4jLong>& dimensions) const; NDArray<T>* permute(const std::vector<Nd4jLong>& dimensions) const; NDArray<T>* permute(const Nd4jLong* dimensions, const int rank) const; void permute(const Nd4jLong* dimensions, const int rank, NDArray<T>& target) const; void permute(const std::vector<Nd4jLong>& dimensions, NDArray<T>& target) const; /** * This method streamlines given view or permuted array, and reallocates buffer */ void streamline(char order = 'a'); /** * check whether array is contiguous in memory */ bool isContiguous(); /** * prints information about array shape * msg - message to print out */ void printShapeInfo(const char * msg = nullptr) const; /** * prints buffer elements * msg - message to print out * limit - number of array elements to print out */ void printBuffer(const char* msg = nullptr, Nd4jLong limit = -1); /** * prints buffer elements, takes into account offset between elements (element-wise-stride) * msg - message to print out * limit - number of array elements to print out */ void printIndexedBuffer(const char* msg = nullptr, Nd4jLong limit = -1) const; std::string asIndexedString(Nd4jLong limit = -1); std::string asString(Nd4jLong limit = -1); /** * this method assigns values of given array to this one */ void assign(const NDArray<T>* other); /** * this method assigns values of given array to this one */ void assign(const NDArray<T>& other); /** * this method assigns given value to all elements in array */ void assign(const T value); /** * returns new copy of this array, optionally in different order */ NDArray<T> *dup(const char newOrder = 'a'); /** * returns sum of all elements of array */ T sumNumber() const; /** * returns mean number of array */ T meanNumber() const; /** * This method explicitly enforces new shape for this NDArray, old shape/stride information is lost */ void enforce(const std::initializer_list<Nd4jLong> &dimensions, char order = 'a'); void enforce(std::vector<Nd4jLong> &dimensions, char order = 'a'); /** * calculates sum along dimension(s) in this array and save it to created reduced array * dimensions - array of dimensions to calculate sum over * keepDims - if true then put unities in place of reduced dimensions */ NDArray<T> *sum(const std::vector<int> &dimensions) const; /** * method reduces array by excluding its shapes along dimensions present in given dimensions vector, result is stored in new array to be returned * dimensions - array of dimensions to reduce along * keepDims - if true then put unities in place of reduced dimensions */ template<typename OpName> NDArray<T>* reduceAlongDimension(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; template<typename OpName> NDArray<T>* reduceAlongDimension(const std::initializer_list<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; template<typename OpName> NDArray<T> reduceAlongDims(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; /** * method reduces array by excluding its shapes along dimensions present in given dimensions vector * target - where to save result of reducing * dimensions - array of dimensions to reduce along * keepDims - if true then put unities in place of reduced dimensions * extras - extra parameters */ template<typename OpName> void reduceAlongDimension(NDArray<T>* target, const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false, T *extras = nullptr) const; /** * return variance of array elements set * biasCorrected - if true bias correction will be applied */ template<typename OpName> T varianceNumber(bool biasCorrected = true); /** * apply scalar operation to array * extraParams - extra parameters for operation */ template<typename OpName> T reduceNumber(T *extraParams = nullptr) const; /** * returns element index which corresponds to some condition imposed by operation * extraParams - extra parameters for operation */ template<typename OpName> Nd4jLong indexReduceNumber(T *extraParams = nullptr); /** * returns index of max element in a given array (optionally: along given dimension(s)) * dimensions - optional vector with dimensions */ Nd4jLong argMax(std::initializer_list<int> dimensions = {}); /** * apply OpName transformation directly to array * extraParams - extra parameters for operation */ template<typename OpName> void applyTransform(T *extraParams = nullptr); /** * apply OpName transformation to array and store result in target * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyTransform(NDArray<T> *target, T *extraParams = nullptr); /** * apply OpName transformation to this array and store result in new array being returned * extraParams - extra parameters for operation */ template<typename OpName> NDArray<T> transform(T *extraParams = nullptr) const; /** * apply pairwise OpName transformation based on "this" and "other" arras elements, store result in this array * other - second array necessary for pairwise operation * extraParams - extra parameters for operation */ template<typename OpName> void applyPairwiseTransform(NDArray<T> *other, T *extraParams); /** * apply pairwise OpName transformation based on "this" and "other" arras elements, store result in target array * other - second array necessary for pairwise operation * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyPairwiseTransform(NDArray<T> *other, NDArray<T> *target, T *extraParams); /** * apply operation which requires broadcasting, broadcast a smaller array (tad) along bigger one (this) * tad - array to broadcast * dimensions - dimensions array to broadcast along * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyBroadcast(std::initializer_list<int> dimensions, const NDArray<T>* tad, NDArray<T>* target = nullptr, T* extraArgs = nullptr); template <typename OpName> void applyBroadcast(std::vector<int> &dimensions, const NDArray<T> *tad, NDArray<T> *target = nullptr, T *extraArgs = nullptr); /** * apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting * other - input array * extraParams - extra parameters for operation */ template <typename OpName> NDArray<T> applyTrueBroadcast(const NDArray<T>& other, T *extraArgs = nullptr) const; template <typename OpName> NDArray<T>* applyTrueBroadcast(const NDArray<T>* other, T *extraArgs = nullptr) const; /** * apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting * other - input array * target - where to store result * checkTargetShape - if true check whether target shape is suitable for broadcasting * extraParams - extra parameters for operation */ template <typename OpName> void applyTrueBroadcast(const NDArray<T>* other, NDArray<T>* target, const bool checkTargetShape = true, T *extraArgs = nullptr) const; /** * apply a scalar operation to an array * scalar - input scalar * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyScalar(T scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr) const; /** * apply a scalar operation to an array * scalar - input array which is simple scalar * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyScalar(NDArray<T>& scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr) const; #ifndef __JAVACPP_HACK__ /** * apply operation "func" to an array * func - what operation to apply * target - where to store result */ void applyLambda(const std::function<T(T)>& func, NDArray<T>* target = nullptr); void applyIndexedLambda(const std::function<T(Nd4jLong, T)>& func, NDArray<T>* target = nullptr); /** * apply pairwise operation "func" to an array * other - input array * func - what pairwise operation to apply * target - where to store result */ void applyPairwiseLambda(NDArray<T>* other, const std::function<T(T, T)>& func, NDArray<T>* target = nullptr); void applyIndexedPairwiseLambda(NDArray<T>* other, const std::function<T(Nd4jLong, T, T)>& func, NDArray<T>* target = nullptr); void applyTriplewiseLambda(NDArray<T>* second, NDArray<T> *third, const std::function<T(T, T, T)>& func, NDArray<T>* target = nullptr); #endif /** * apply OpName random operation to array * buffer - pointer on RandomBuffer * y - optional input array * z - optional input array * extraArgs - extra parameters for operation */ template<typename OpName> void applyRandom(nd4j::random::RandomBuffer *buffer, NDArray<T>* y = nullptr, NDArray<T>* z = nullptr, T* extraArgs = nullptr); /** * apply transpose operation to the copy of this array, that is this array remains unaffected */ NDArray<T> *transpose() const; /** * perform transpose operation and store result in target, this array remains unaffected * target - where to store result */ void transpose(NDArray<T>& target) const; /** * apply in-place transpose operation to this array, so this array becomes transposed */ void transposei(); /** * return array pointing on certain range of this array * index - the number of array to be returned among set of possible arrays * dimensions - array of dimensions to point on */ NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::initializer_list<int>& dimensions) const; NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::vector<int>& dimensions) const; /** * returns the number of arrays pointing on specified dimension(s) * dimensions - array of dimensions to point on */ Nd4jLong tensorsAlongDimension(const std::initializer_list<int> dimensions) const ; Nd4jLong tensorsAlongDimension(const std::vector<int>& dimensions) const ; /** * returns true if elements of two arrays are equal to within given epsilon value * other - input array to compare * eps - epsilon, this value defines the precision of elements comparison */ bool equalsTo(const NDArray<T> *other, T eps = (T) 1e-5f) const; bool equalsTo(NDArray<T> &other, T eps = (T) 1e-5f) const; /** * add given row vector to all rows of this array * row - row vector to add */ void addiRowVector(const NDArray<T> *row); /** * add given row vector to all rows of this array, store result in target * row - row vector to add * target - where to store result */ void addRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * subtract given row vector from all rows of this array, store result in target * row - row vector to subtract * target - where to store result */ void subRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * multiply all rows of this array on given row vector, store result in target * row - row vector to multiply on * target - where to store result */ void mulRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * divide all rows of this array on given row vector, store result in target * row - row vector to divide on * target - where to store result */ void divRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * add given column vector to all columns of this array, store result in target * column - column vector to add * target - where to store result */ void addColumnVector(const NDArray<T> *column, NDArray<T>* target) const; /** * add given column vector to all columns of this array, this array becomes affected (in-place operation) * column - column vector to add */ void addiColumnVector(const NDArray<T> *column); /** * multiply all columns of this array on given column vector, this array becomes affected (in-place operation) * column - column vector to multiply on */ void muliColumnVector(const NDArray<T> *column); /** * returns number of bytes used by _buffer & _shapeInfo */ Nd4jLong memoryFootprint(); /** * these methods suited for FlatBuffers use */ std::vector<T> getBufferAsVector(); std::vector<Nd4jLong> getShapeAsVector(); std::vector<Nd4jLong> getShapeInfoAsVector(); std::vector<int64_t> getShapeInfoAsFlatVector(); /** * set new order and shape in case of suitable array length (in-place operation) * order - order to set * shape - shape to set * * if there was permute applied before or there are weird strides, then new buffer is allocated for array */ bool reshapei(const char order, const std::initializer_list<Nd4jLong>& shape); bool reshapei(const char order, const std::vector<Nd4jLong>& shape); bool reshapei(const std::initializer_list<Nd4jLong>& shape); bool reshapei(const std::vector<Nd4jLong>& shape); /** * creates new array with corresponding order and shape, new array will point on _buffer of this array * order - order to set * shape - shape to set * * if permute have been applied before or there are weird strides, then new buffer is allocated for new array */ NDArray<T>* reshape(const char order, const std::vector<Nd4jLong>& shape) const; /** * calculate strides and set given order * order - order to set */ void updateStrides(const char order); /** * change an array by repeating it the number of times given by reps (in-place operation) * repeats - contains numbers of repetitions */ void tilei(const std::vector<Nd4jLong>& repeats); /** * returns new array which is created by by repeating of this array the number of times given by reps * repeats - contains numbers of repetitions */ NDArray<T> tile(const std::vector<Nd4jLong>& repeats) const; /** * change an array by repeating it the number of times given by reps (in-place operation) * repeats - contains numbers of repetitions * target - where to store result */ void tile(const std::vector<Nd4jLong>& repeats, NDArray<T>& target) const; /** * change an array by repeating it the number of times to acquire the new shape which is the same as target shape * target - where to store result */ void tile(NDArray<T>& target) const; /** * returns an array which is result of broadcasting of this and other arrays * other - input array */ NDArray<T>* broadcast(const NDArray<T>& other); /** * check whether array's rows (arg=0) or columns (arg=1) create orthogonal basis * arg - 0 -> row, 1 -> column */ bool hasOrthonormalBasis(const int arg); /** * check whether array is identity matrix */ bool isIdentityMatrix(); /** * check whether array is unitary matrix */ bool isUnitary(); /** * reduces dimensions in this array relying on index operation OpName * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyIndexReduce(const std::vector<int>& dimensions, const T *extraParams = nullptr) const; /** * reduces dimensions in array relying on index operation OpName * target - where to store result * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> void applyIndexReduce(const NDArray<T>* target, const std::vector<int>& dimensions, const T *extraParams = nullptr) const; /** * apply reduce3 operation OpName to this and other array, return result in new output array * other - input array * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyReduce3(const NDArray<T>* other, const T* extraParams = nullptr) const; /** * apply reduce3 operation OpName to this and other array, return result in new output array * other - input array * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyAllReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const; /** * apply reduce3 (exec) operation OpName to this and other array, return result in new output array * other - input array * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const; /** * returns variance along given dimensions * biasCorrected - if true bias correction will be applied * dimensions - vector of dimensions to calculate variance along */ template<typename OpName> NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::vector<int>& dimensions) const; template<typename OpName> NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::initializer_list<int>& dimensions) const; template<typename OpName> void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::vector<int>& dimensions); template<typename OpName> void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::initializer_list<int>& dimensions); /** * operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals * idx - intervals of indexes which define the sub-arrays to point on * keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b} */ NDArray<T> operator()(const Intervals& idx, bool keepUnitiesInShape = false) const; /** * operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals * idx - intervals of indexes which define the sub-arrays to point on, idx has form {dim0Start,dim0End, dim1Start,dim1End, ....} and length (2 * this->rankOf()) * when (dimStart == dimEnd) then whole range will be used for current dimension * keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b} */ NDArray<T> operator()(const int* idx, bool keepUnitiesInShape = false) const; /** * addition operator: array + other * other - input array to add */ NDArray<T> operator+(const NDArray<T>& other) const; /** * addition operator: array + scalar * scalar - input scalar to add */ NDArray<T> operator+(const T scalar) const; /** * friend functions which implement addition operator: scalar + array * scalar - input scalar to add */ friend NDArray<float> nd4j::operator+(const float scalar, const NDArray<float>& arr); friend NDArray<float16> nd4j::operator+(const float16 scalar, const NDArray<float16>& arr); friend NDArray<double> nd4j::operator+(const double scalar, const NDArray<double>& arr); /** * addition unary operator array += other * other - input array to add */ void operator+=(const NDArray<T>& other); /** * subtraction unary operator array -= other * other - input array to add */ void operator-=(const NDArray<T>& other); void operator+=(const T other); void operator-=(const T other); /** * subtraction operator: array - other * other - input array to subtract */ NDArray<T> operator-(const NDArray<T>& other) const; /** * subtraction operator: array - scalar * scalar - input scalar to subtract */ NDArray<T> operator-(const T& scalar) const; /** * negative operator, it changes sign of all array elements on opposite */ NDArray<T> operator-() const; /** * friend functions which implement subtraction operator: scalar - array * scalar - input scalar to subtract */ friend NDArray<float> nd4j::operator-(const float scalar, const NDArray<float>& arr); friend NDArray<float16> nd4j::operator-(const float16 scalar, const NDArray<float16>& arr); friend NDArray<double> nd4j::operator-(const double scalar, const NDArray<double>& arr); /** * pairwise multiplication operator: array * other * other - input array to multiply on */ NDArray<T> operator*(const NDArray<T>& other) const; /** * multiplication operator: array * scalar * scalar - input scalar to multiply on */ NDArray<T> operator*(const T scalar) const; /** * pairwise multiplication unary operator array *= other * other - input array to multiply on */ void operator*=(const NDArray<T>& other); /** * multiplication unary operator array *= scalar * scalar - input scalar to multiply on */ void operator*=(const T scalar); /** * pairwise division operator: array / other * other - input array to divide on */ NDArray<T> operator/(const NDArray<T>& other) const; /** * division operator: array / scalar * scalar - input scalar to divide each array element on */ NDArray<T> operator/(const T scalar) const; /** * pairwise division unary operator: array /= other * other - input array to divide on */ void operator/=(const NDArray<T>& other); /** * division unary operator: array /= scalar * scalar - input scalar to divide on */ void operator/=(const T scalar); /** * friend function which implements mathematical multiplication of two arrays * left - input array * right - input array */ friend NDArray<T> mmul<>(const NDArray<T>& left, const NDArray<T>& right); /** * this method assigns elements of other array to the sub-array of this array defined by given intervals * other - input array to assign elements from * idx - intervals of indexes which define the sub-array */ void assign(const NDArray<T>& other, const Intervals& idx); /** * return vector containing _buffer as flat binary array */ std::vector<int8_t> asByteVector(); /** * makes array to be identity matrix (not necessarily square), that is set all diagonal elements = 1, rest = 0 */ void setIdentity(); /** * swaps the contents of tow arrays, * PLEASE NOTE: method doesn't take into account the shapes of arrays, shapes may be different except one condition: arrays lengths must be the same */ void swapUnsafe(NDArray<T>& other); /** * return vector with buffer which points on corresponding diagonal elements of array * type - means of vector to be returned: column ('c') or row ('r') */ NDArray<T>* diagonal(const char type ) const; /** * fill matrix with given value starting from specified diagonal in given direction, works only with 2D matrix * * diag - diagonal starting from matrix is filled. * diag = 0 corresponds to main diagonal, * diag < 0 below main diagonal * diag > 0 above main diagonal * direction - in what direction to fill matrix. There are 2 possible directions: * 'u' - fill up, mathematically this corresponds to lower triangular matrix * 'l' - fill down, mathematically this corresponds to upper triangular matrix */ void setValueInDiagMatrix(const T& value, const int diag, const char direction); /** * change an array by repeating it the number of times in order to acquire new shape equal to the input shape * * shape - contains new shape to broadcast array to * target - optional argument, if target != nullptr the resulting array will be placed it target, in opposite case tile operation is done in place */ void tileToShape(const std::vector<Nd4jLong>& shape, NDArray<T>* target = nullptr); void tileToShape(const std::initializer_list<Nd4jLong>& shape, NDArray<T>* target = nullptr); template <typename N> NDArray<N>* asT(); /** * calculates the trace of an array, that is sum of elements on main diagonal = sum array[i, i, i, ...] */ T getTrace() const; /** * default destructor */ ~NDArray() noexcept; /** * set _shapeInfo */ FORCEINLINE void setShapeInfo(Nd4jLong *shapeInfo); /** * set _buffer */ FORCEINLINE void setBuffer(T* buffer); /** * set _isBuffAlloc and _isShapeAlloc */ FORCEINLINE void triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated); /** * returns the value of "dim" dimension */ Nd4jLong sizeAt(int dim) const; /** * returns order of array */ FORCEINLINE char ordering() const; /** * return _isView */ FORCEINLINE bool isView(); /** * returns shape portion of shapeInfo */ FORCEINLINE Nd4jLong* shapeOf() const; /** * returns strides portion of shapeInfo */ FORCEINLINE Nd4jLong* stridesOf() const; /** * returns rank of array */ FORCEINLINE int rankOf() const; /** * returns length of array */ FORCEINLINE Nd4jLong lengthOf() const; /** * returns number of rows in array */ FORCEINLINE Nd4jLong rows() const; /** * returns number of columns in array */ FORCEINLINE Nd4jLong columns() const; /** * returns size of array elements type */ FORCEINLINE int sizeOfT() const; /** * returns element-wise-stride */ FORCEINLINE Nd4jLong ews() const; // returns true if arrays have same shape FORCEINLINE bool isSameShape(const NDArray<T> *other) const; FORCEINLINE bool isSameShape(NDArray<T> &other) const; FORCEINLINE bool isSameShape(const std::initializer_list<Nd4jLong>& shape) const; FORCEINLINE bool isSameShape(const std::vector<Nd4jLong>& shape) const; /** * returns true if these two NDArrays have same rank, dimensions, strides, ews and order */ FORCEINLINE bool isSameShapeStrict(const NDArray<T> *other) const; /** * returns true if buffer && shapeInfo were defined (non nullptr) */ FORCEINLINE bool nonNull() const; /** * returns array element with given index from linear buffer * i - element index in array */ FORCEINLINE T getScalar(const Nd4jLong i) const; /** * returns array element with given index, takes into account offset between elements (element-wise-stride) * i - element index in array */ FORCEINLINE T getIndexedScalar(const Nd4jLong i) const; /** * returns element with given indexes from 2D array * i - number of row * j - number of column */ FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j) const; /** * returns element with given indexes from 3D array * i - height * j - width * k - depth */ FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const; /** * assigns given scalar to array element by given index, takes into account offset between elements (element-wise-stride) * i - element index in array * value - scalar value to assign */ FORCEINLINE void putIndexedScalar(const Nd4jLong i, const T value); /** * assigns given scalar to array element by given index, regards array buffer as linear * i - element index in array * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const T value); /** * assigns given scalar to 2D array element by given indexes * i - number of row * j - number of row * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const T value); /** * assigns given scalar to 3D array element by given indexes * i - height * j - width * k - depth * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value); /** * returns true if array is 2D */ FORCEINLINE bool isMatrix() const; /** * returns true if array is vector */ FORCEINLINE bool isVector() const; /** * returns true if array is column vector */ FORCEINLINE bool isColumnVector() const; /** * returns true if array is row vector */ FORCEINLINE bool isRowVector() const; /** * returns true if array is scalar */ FORCEINLINE bool isScalar() const; /** * inline accessing operator for matrix, i - absolute index */ FORCEINLINE T operator()(const Nd4jLong i) const; /** * inline modifying operator for matrix, i - absolute index */ FORCEINLINE T& operator()(const Nd4jLong i); /** * inline accessing operator for 2D array, i - row, j - column */ FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j) const; /** * inline modifying operator for 2D array, i - row, j - column */ FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j); /** * inline accessing operator for 3D array, i - height, j - width, k - depth */ FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const; /** * inline modifying operator for 3D array, i - height, j - width, k - depth */ FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k); /** * inline modifying operator for 4D array, i - height, j - width, k - depth */ FORCEINLINE T& operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w); /** * inline accessing operator for 4D array, i - height, j - width, k - depth */ FORCEINLINE T operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const; template <typename T2> FORCEINLINE std::vector<T2> asVectorT(); FORCEINLINE bool isAttached(); NDArray<T>* detach(); }; ////////////////////////////////////////////////////////////////////////// ///// IMLEMENTATION OF INLINE METHODS ///// ////////////////////////////////////////////////////////////////////////// template <typename T> template <typename T2> std::vector<T2> NDArray<T>::asVectorT() { std::vector<T2> result(this->lengthOf()); #pragma omp parallel for simd for (int e = 0; e < this->lengthOf(); e++) result[e] = (T2) this->getIndexedScalar(e); return result; } template<typename T> bool NDArray<T>::isAttached() { return this->_workspace != nullptr; } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::setShapeInfo(Nd4jLong *shapeInfo) { if(_isShapeAlloc && _workspace == nullptr) delete []_shapeInfo; _shapeInfo = shapeInfo; _isShapeAlloc = false; } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::setBuffer(T* buffer) { if(_isBuffAlloc && _workspace == nullptr) delete []_buffer; _buffer = buffer; _isBuffAlloc = false; } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated) { _isBuffAlloc = bufferAllocated; _isShapeAlloc = shapeAllocated; } ////////////////////////////////////////////////////////////////////////// template<typename T> char NDArray<T>::ordering() const { return shape::order(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isView() { return _isView; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong* NDArray<T>::shapeOf() const { return shape::shapeOf(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong* NDArray<T>::stridesOf() const { return shape::stride(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> int NDArray<T>::rankOf() const { return shape::rank(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::lengthOf() const { return shape::length(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::rows() const { return shapeOf()[0]; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::columns() const { return shapeOf()[1]; } ////////////////////////////////////////////////////////////////////////// template<typename T> int NDArray<T>::sizeOfT() const { return sizeof(T); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::ews() const { return shape::elementWiseStride(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::nonNull() const { return this->_buffer != nullptr && this->_shapeInfo != nullptr; } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isMatrix() const { return shape::isMatrix(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isVector() const { return !isScalar() && shape::isVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isColumnVector() const { return !isScalar() && shape::isColumnVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isRowVector() const { // 1D edge case if (shape::rank(this->_shapeInfo) == 1) return true; return !isScalar() && shape::isRowVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isScalar() const { return shape::isScalar(this->_shapeInfo); } // accessing operator for matrix, i - absolute index template<typename T> T NDArray<T>::operator()(const Nd4jLong i) const { if (i >= shape::length(_shapeInfo)) throw std::invalid_argument("NDArray::operator(i): dinput index is out of array length !"); auto ews = shape::elementWiseStride(_shapeInfo); char order = ordering(); if(ews == 1 && order == 'c') return _buffer[i]; else if(ews > 1 && order == 'c') return _buffer[i*ews]; else { Nd4jLong idx[MAX_RANK]; shape::ind2subC(rankOf(), shapeOf(), i, idx); Nd4jLong offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf()); return _buffer[offset]; } } ////////////////////////////////////////////////////////////////////////// // modifying operator for matrix, i - absolute index template<typename T> T& NDArray<T>::operator()(const Nd4jLong i) { if (i >= shape::length(_shapeInfo)) throw std::invalid_argument("NDArray::operator(i): input index is out of array length !"); auto ews = shape::elementWiseStride(_shapeInfo); auto order = ordering(); if(ews == 1 && order == 'c') return _buffer[i]; else if(ews > 1 && order == 'c') return _buffer[i*ews]; else { Nd4jLong idx[MAX_RANK]; shape::ind2subC(rankOf(), shapeOf(), i, idx); auto offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf()); return _buffer[offset]; } } ////////////////////////////////////////////////////////////////////////// // accessing operator for 2D matrix, i - row, j - column template<typename T> T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) const { if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1]) throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !"); Nd4jLong coords[2] = {i, j}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // modifying operator for 2D matrix, i - row, j - column template<typename T> T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) { if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1]) throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !"); Nd4jLong coords[2] = {i, j}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // accessing operator for 3D array, i - row, j - column template<typename T> T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const { if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || j >= shapeOf()[2]) throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !"); Nd4jLong coords[3] = {i, j, k}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // modifying operator for 3D array template<typename T> T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) { if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || k >= shapeOf()[2]) throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !"); Nd4jLong coords[3] = {i, j, k}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } template<typename T> T NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const { if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3]) throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !"); Nd4jLong coords[4] = {t, u, v, w}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } template<typename T> T& NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) { if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3]) throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !"); Nd4jLong coords[4] = {t, u, v, w}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // Return value from linear buffer template<typename T> T NDArray<T>::getScalar(const Nd4jLong i) const { return (*this)(i); } ////////////////////////////////////////////////////////////////////////// template<typename T> T NDArray<T>::getIndexedScalar(const Nd4jLong i) const { return (*this)(i); } ////////////////////////////////////////////////////////////////////////// // Returns value from 2D matrix by coordinates/indexes template<typename T> T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j) const { return (*this)(i, j); } ////////////////////////////////////////////////////////////////////////// // returns value from 3D tensor by coordinates template<typename T> T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const { return (*this)(i, j, k); } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::putIndexedScalar(const Nd4jLong i, const T value) { (*this)(i) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in linear buffer to position i template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const T value) { (*this)(i) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in 2D matrix to position i, j template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const T value) { (*this)(i,j) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in 3D matrix to position i,j,k template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value) { (*this)(i,j,k) = value; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::memoryFootprint() { Nd4jLong size = this->lengthOf() * this->sizeOfT(); size += shape::shapeInfoByteLength(this->rankOf()); return size; } ////////////////////////////////////////////////////////////////////////// // returns true if these two NDArrays have same shape // still the definition of inline function must be in header file template<typename T> bool NDArray<T>::isSameShape(const std::vector<Nd4jLong>& other) const{ if (this->rankOf() != (int) other.size()) return false; for (int e = 0; e < this->rankOf(); e++) { if (this->shapeOf()[e] != other.at(e) && other.at(e) != -1) return false; } return true; } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(const NDArray<T> *other) const { return isSameShape(std::vector<Nd4jLong>(other->_shapeInfo+1, other->_shapeInfo+1+other->_shapeInfo[0])); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(NDArray<T> &other) const { return isSameShape(&other); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(const std::initializer_list<Nd4jLong>& other) const { return isSameShape(std::vector<Nd4jLong>(other)); } ////////////////////////////////////////////////////////////////////////// // returns true if these two NDArrays have same _shapeInfo // still the definition of inline function must be in header file template<typename T> bool NDArray<T>::isSameShapeStrict(const NDArray<T> *other) const { return shape::equalsStrict(_shapeInfo, other->_shapeInfo); } } #endif
GB_unaryop__ainv_int64_fp32.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__ainv_int64_fp32 // op(A') function: GB_tran__ainv_int64_fp32 // C type: int64_t // A type: float // cast: int64_t cij ; GB_CAST_SIGNED(cij,aij,64) // unaryop: cij = -aij #define GB_ATYPE \ float #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ int64_t z ; GB_CAST_SIGNED(z,aij,64) ; // 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_AINV || GxB_NO_INT64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int64_fp32 ( int64_t *Cx, // Cx and Ax may be aliased float *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__ainv_int64_fp32 ( 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
gen_vow.c
#include <stdio.h> #include <time.h> #include <omp.h> #include "settings.h" #include "triples.h" #include "bintree.h" #include "gen_vow.h" #include "memory.h" #include "vow.c" // Functions for swig interface #include "swig_helpers.c" #include "state.c" // Print statements for debugging void print_st(st_t *s, shared_state_t *shared_state) { uint64_t i; if (s->bytes == NULL) { for (i = 0; i < shared_state->NBYTES_STATE; i++) printf("--"); return; } for (i = 0; i < shared_state->NBYTES_STATE; i++) printf("%02x", s->bytes[i]); } void print_trip(trip_t *t, shared_state_t *shared_state) { print_st(&t->initial_state, shared_state); printf(" %lu ", (unsigned long)t->current_steps); print_st(&t->initial_state, shared_state); printf("\n"); } /* ______ / \ | $$$$$$\ ______ ______ ______ | $$_ \$$/ \ / \ / \ | $$ \ | $$$$$$\| $$$$$$\| $$$$$$\ | $$$$ | $$ \$$| $$ $$| $$ $$ | $$ | $$ | $$$$$$$$| $$$$$$$$ | $$ | $$ \$$ \ \$$ \ \$$ \$$ \$$$$$$$ \$$$$$$$ | \ ______ ____ ______ ______ ____ ______ ______ __ __ | $$ | \ \ / \ | \ \ / \ / \ | \ | \| $$ | $$$$$$\$$$$\| $$$$$$\| $$$$$$\$$$$\| $$$$$$\| $$$$$$\| $$ | $$| $$ | $$ | $$ | $$| $$ $$| $$ | $$ | $$| $$ | $$| $$ \$$| $$ | $$ \$$ | $$ | $$ | $$| $$$$$$$$| $$ | $$ | $$| $$__/ $$| $$ | $$__/ $$ __ | $$ | $$ | $$ \$$ \| $$ | $$ | $$ \$$ $$| $$ \$$ $$| \ \$$ \$$ \$$ \$$$$$$$ \$$ \$$ \$$ \$$$$$$ \$$ _\$$$$$$$ \$$ | \__| $$ \$$ $$ \$$$$$$ */ /* Initializations */ static st_t init_st(uint64_t nwords_state) { st_t s; s.words = calloc(nwords_state, sizeof(digit_t)); return s; } static void free_st(st_t *s) { free(s->words); } /* Simple functions on states */ static void copy_st(st_t *r, const st_t *s, const uint64_t nwords_state) { for (unsigned int i = 0; i < nwords_state; i++) r->words[i] = s->words[i]; } static void copy_st2uint64(uint64_t *r, const st_t *s, const uint64_t nwords_state) { for (unsigned int i = 0; i < nwords_state; i++) r[i] = s->words[i]; } static void copy_uint642st(st_t *r, const uint64_t *s, const uint64_t nwords_state) { for (unsigned int i = 0; i < nwords_state; i++) r->words[i] = s[i]; } /* TODO: Include a seed here.. */ void init_shared_state(instance_t *inst, shared_state_t *S #ifdef STORE_IN_DATABASE , db_settings_t *db_settings #endif ) { /* Initialize state */ S->instance = inst; S->NBITS_STATE = inst->NBITS_STATE; S->NBYTES_STATE = ((inst->NBITS_STATE + 7) / 8); /* Number of bytes needed for state */ S->NWORDS_STATE = ((inst->NBITS_STATE + RADIX64 - 1) / RADIX64); /* Number of words need for state */ S->NBITS_OVERFLOW = (inst->NBITS_STATE % 8); S->PRNG_SEED = (unsigned long)inst->PRNG_SEED; /* Initialize memory */ S->MEMORY_LOG_SIZE = inst->MEMORY_LOG_SIZE; S->MEMORY_SIZE = (uint64_t)(1 << S->MEMORY_LOG_SIZE); S->MEMORY_SIZE_MASK = S->MEMORY_SIZE - 1; assert(S->MEMORY_LOG_SIZE < 64); /* Assumes that MEMORY_SIZE <= 2^RADIX */ /* Prepare the global memory */ if (initialize_shared_memory(S) == EXIT_FAILURE) { printf("Error initialising shared memory\n"); assert(0); } /* Initialize omp params */ S->N_OF_CORES = inst->N_OF_CORES; #ifdef STORE_IN_DATABASE /* db settings */ S->db_settings = db_settings; #endif /* Initialise H&G */ S->HANSEL_GRETEL = inst->HANSEL_GRETEL; S->MAX_CRUMBS = inst->MAX_CRUMBS; /* Initialize vOW params */ double THETA = inst->ALPHA * sqrt((double)S->MEMORY_SIZE / (double)pow(2,(double)inst->NBITS_STATE)); S->MAX_DIST = (uint64_t)(inst->BETA * S->MEMORY_SIZE); S->MAX_STEPS = ceil(inst->GAMMA / THETA); S->MAX_FUNCTION_VERSIONS = 10000; if (inst->NBITS_STATE <= S->MEMORY_LOG_SIZE) printf("\nToo much memory for too small state, can't use last word to distinguish points.\n\n"); // Assumes we are not filling digit_t, should shift by min(sizeof(digit_t)*8, inst->NBITS_STATE) - S->MEMORY_LOG_SIZE if (inst->NBITS_STATE - S->MEMORY_LOG_SIZE <= 64) { S->DIST_BOUND = THETA * pow(2,(double)(inst->NBITS_STATE - S->MEMORY_LOG_SIZE)); } else { /* Use max precision */ S->DIST_BOUND = THETA * pow(2,64); } assert(inst->NBITS_STATE > S->MEMORY_LOG_SIZE); // > -log(theta), we want some resolution /* Statistics */ S->collect_vow_stats = false; // By default don't collect stats (=> terminate run when successful) initTree(&S->dist_cols); // Initing even if not using S->success = false; S->wall_time = 0.; S->collisions = 0; S->mem_collisions = 0; S->dist_points = 0; S->number_steps_collect = 0; S->number_steps_locate = 0; S->number_steps = 0; S->initial_function_version = 1; S->final_avg_random_functions = 0.; /* Resync */ S->resync_frequency = 1; S->resync_cores = (uint8_t *)calloc(S->N_OF_CORES, sizeof(uint8_t)); /* Initial golden preimages and image, uses a temporary prng state */ prng_state_t prng_state; init_prng(&prng_state, S->PRNG_SEED); S->image.words = calloc(S->NWORDS_STATE, sizeof(digit_t)); S->preimages[0].words = calloc(S->NWORDS_STATE, sizeof(digit_t)); S->preimages[1].words = calloc(S->NWORDS_STATE, sizeof(digit_t)); sample_prng(&prng_state, S->image.bytes, (unsigned long)S->NBYTES_STATE); sample_prng(&prng_state, S->preimages[0].bytes, (unsigned long)S->NBYTES_STATE); do { sample_prng(&prng_state, S->preimages[1].bytes, (unsigned long)S->NBYTES_STATE); } while (is_equal_st(&S->preimages[0], &S->preimages[1], S->NWORDS_STATE)); fix_overflow(&S->image, S->NBYTES_STATE, S->NBITS_OVERFLOW); fix_overflow(&S->preimages[0], S->NBYTES_STATE, S->NBITS_OVERFLOW); fix_overflow(&S->preimages[1], S->NBYTES_STATE, S->NBITS_OVERFLOW); } void free_shared_state(shared_state_t *S) { cleanup_shared_memory(S); free(S->image.words); free(S->preimages[0].words); free(S->preimages[1].words); if (S->dist_cols.size != 0) { freeTree(S->dist_cols.root); } free(S->resync_cores); } //-------------------------------------------------------------------- static void SwapStGen(st_t *r, st_t *s, uint64_t nwords_state) { st_t t = init_st(nwords_state); copy_st(&t, r, nwords_state); copy_st(r, s, nwords_state); copy_st(s, &t, nwords_state); free_st(&t); } bool is_equal_st(const st_t *s, const st_t *t, const uint64_t nwords_state) { for (unsigned int i = 0; i < nwords_state; i++) { if (s->words[i] != t->words[i]) return false; } return true; } static bool is_equal_st_words(const st_t *s, const uint64_t *r, const uint64_t nwords_state) { for (unsigned int i = 0; i < nwords_state; i++) { if (s->words[i] != r[i]) return false; } return true; } void copy_trip(trip_t *t, const trip_t *u, const uint64_t nwords_state) { copy_st(&t->current_state, &u->current_state, nwords_state); t->current_steps = u->current_steps; copy_st(&t->initial_state, &u->initial_state, nwords_state); } static void get_val(uint64_t *val, uint64_t NWORDS_STATE, digit_t *state_words, uint64_t MEMORY_LOG_SIZE) { /* Use as many bits as possible, with a max of 64 (word size) * This limits the precision of distinguishedness checking to 64 bits */ if (NWORDS_STATE == 1) { *val = state_words[0] >> MEMORY_LOG_SIZE; } else { *val = (state_words[0] >> MEMORY_LOG_SIZE) | (state_words[1] << (64-MEMORY_LOG_SIZE)); } } static void add_fv(uint64_t *val, const uint64_t fv, const uint64_t db) { *val = *val + fv*db; } // /* Functions for vOW */ /** * @brief Evaluates whether a point is distinguished * * @param S * @param private_state * @return true point is distinguished * @return false point is not distinguished */ bool DistinguishedGen(private_state_t *private_state) { /* Divide distinguishedness over interval to avoid bad cases */ assert(private_state->MEMORY_LOG_SIZE > 0); uint64_t val; get_val(&val, private_state->NWORDS_STATE, private_state->current.current_state.words, private_state->MEMORY_LOG_SIZE); add_fv(&val, private_state->function_version, (uint64_t)private_state->DIST_BOUND); /* Zero top bits if < 64 bits filled */ if ((private_state->NBITS_STATE - private_state->MEMORY_LOG_SIZE) <= 64) { val &= (((uint64_t)1 << (private_state->NBITS_STATE - private_state->MEMORY_LOG_SIZE)) - 1); } return (val <= (uint64_t)private_state->DIST_BOUND); } /** * @brief Recovers memory index for storing current distinguished point * * @param S * @param private_state * @return uint64_t */ uint64_t MemIndexGen(private_state_t *private_state) { // Returns (lob + function) mod memsize return (uint64_t)((private_state->current.current_state.words[0] + private_state->random_functions) & private_state->MEMORY_SIZE_MASK); } /** * @brief Samples a new starting point * * @param private_state pointer */ void SampleGen(private_state_t *private_state) { sample_prng(&private_state->prng_state, private_state->current.current_state.bytes, (unsigned long)private_state->NBYTES_STATE); fix_overflow(&private_state->current.current_state, private_state->NBYTES_STATE, private_state->NBITS_OVERFLOW); private_state->current.current_steps = 0; copy_st(&private_state->current.initial_state, &private_state->current.current_state, private_state->NWORDS_STATE); // Hansel & Gretel clean_private_state(private_state); } static void UpdateStGen(st_t *r, const st_t *s, private_state_t *private_state) { if (is_equal_st(s, &private_state->preimages[0], private_state->NWORDS_STATE) || is_equal_st(s, &private_state->preimages[1], private_state->NWORDS_STATE)) { copy_st(r, &private_state->image, private_state->NWORDS_STATE); } else { XOF(r->bytes, s->bytes, (unsigned long)private_state->NBYTES_STATE, (unsigned long)private_state->NBYTES_STATE, (unsigned long)private_state->function_version); fix_overflow(r, private_state->NBYTES_STATE, private_state->NBITS_OVERFLOW); if (is_equal_st(r, &private_state->image, private_state->NWORDS_STATE)) r->words[0] += 1; // Force golden collision fix_overflow(r, private_state->NBYTES_STATE, private_state->NBITS_OVERFLOW); } } /** * @brief walk to the next point in the vOW, following the random function * * @param S * @param private_state */ void UpdateGen(private_state_t *private_state) { uint64_t i, temp; UpdateStGen(&private_state->current.current_state, &private_state->current.current_state, private_state); private_state->number_steps_collect += 1; if (private_state->HANSEL_GRETEL) { if (private_state->crumbs.num_crumbs < private_state->crumbs.max_crumbs) { copy_st2uint64(&private_state->crumbs.crumbs[private_state->crumbs.position], &private_state->current.current_state, private_state->NWORDS_STATE); private_state->crumbs.positions[private_state->crumbs.position] = private_state->crumbs.position; private_state->crumbs.index_crumbs[private_state->crumbs.position] = private_state->crumbs.position; private_state->crumbs.num_crumbs++; } else if (private_state->crumbs.position - private_state->crumbs.positions[private_state->crumbs.max_crumbs - 1] == private_state->crumbs.max_dist) { temp = private_state->crumbs.index_crumbs[private_state->crumbs.index_position]; for (i = private_state->crumbs.index_position; i < private_state->crumbs.max_crumbs - 1; i++) { // Updating table with crumb indices for the crump table private_state->crumbs.index_crumbs[i] = private_state->crumbs.index_crumbs[i + 1]; } private_state->crumbs.index_crumbs[private_state->crumbs.max_crumbs - 1] = temp; private_state->crumbs.index_position++; if (private_state->crumbs.index_position > private_state->crumbs.max_crumbs - 1) private_state->crumbs.index_position = 0; copy_st2uint64(&private_state->crumbs.crumbs[temp], &private_state->current.current_state, private_state->NWORDS_STATE); // Inserting a new crumb at the end of the crumb table for (i = private_state->crumbs.scratch_position; i < private_state->crumbs.max_crumbs - 1; i++) { // Updating table with crumb positions private_state->crumbs.positions[i] = private_state->crumbs.positions[i + 1]; } private_state->crumbs.positions[private_state->crumbs.max_crumbs - 1] = private_state->crumbs.position; private_state->crumbs.swap_position += 2 * private_state->crumbs.real_dist; private_state->crumbs.scratch_position++; if (private_state->crumbs.swap_position > private_state->crumbs.max_crumbs - 1) { // Kind of cumbersome, maybe this can be simplified (but not time critical) private_state->crumbs.swap_position = 0; private_state->crumbs.real_dist <<= 1; } if (private_state->crumbs.scratch_position > private_state->crumbs.max_crumbs - 1) { private_state->crumbs.scratch_position = 0; private_state->crumbs.max_dist <<= 1; private_state->crumbs.swap_position = private_state->crumbs.max_dist; } } private_state->crumbs.position++; } } /** * @brief generate a new random function to walk on * * @param S * @param private_state */ void UpdateRandomFunctionGen(shared_state_t *S, private_state_t *private_state) { private_state->function_version++; // Reset "resync done" flag if (private_state->thread_id == 0) { S->resync_cores[0] = 0; } } static inline bool BacktrackGen_core(trip_t *c0, trip_t *c1, shared_state_t *S, private_state_t *private_state) { uint64_t L; uint64_t i; st_t c0_; st_t c1_; (void)private_state; // Make c0 have the largest number of steps if (c0->current_steps < c1->current_steps) { SwapStGen(&c0->initial_state, &c1->initial_state, private_state->NWORDS_STATE); L = (unsigned long)(c1->current_steps - c0->current_steps); } else { L = (unsigned long)(c0->current_steps - c1->current_steps); } // Catch up the trails for (i = 0; i < L; i++) { UpdateStGen(&c0->initial_state, &c0->initial_state, private_state); private_state->number_steps_locate += 1; } if (is_equal_st(&c0->initial_state, &c1->initial_state, private_state->NWORDS_STATE)) return false; // Robin Hood c0_ = init_st(private_state->NWORDS_STATE); c1_ = init_st(private_state->NWORDS_STATE); for (i = 0; i < c1->current_steps + 1; i++) { UpdateStGen(&c0_, &c0->initial_state, private_state); private_state->number_steps_locate += 1; UpdateStGen(&c1_, &c1->initial_state, private_state); private_state->number_steps_locate += 1; if (is_equal_st(&c0_, &c1_, private_state->NWORDS_STATE)) { /* Record collision */ private_state->collisions += 1; if (private_state->collect_vow_stats) { #pragma omp critical { insertTree(&S->dist_cols, c0->initial_state, c1->initial_state, private_state->NWORDS_STATE); } } if (is_equal_st(&c0_, &private_state->image, private_state->NWORDS_STATE)) { free_st(&c0_); free_st(&c1_); return true; } else { free_st(&c0_); free_st(&c1_); return false; } } else { copy_st(&c0->initial_state, &c0_, private_state->NWORDS_STATE); copy_st(&c1->initial_state, &c1_, private_state->NWORDS_STATE); } } // If multiprocessing, it may reach here if a thread backtracks while another changes function version free_st(&c0_); free_st(&c1_); return false; } static inline bool BacktrackGen_Hansel_Gretel(trip_t *c_mem, trip_t *c_crumbs, shared_state_t *S, private_state_t *private_state) { uint64_t L; trip_t c0_, cmem; uint64_t i, k, index; uint64_t crumb; bool resp, equal; cmem = init_trip(private_state->NWORDS_STATE); copy_trip(&cmem, c_mem, private_state->NWORDS_STATE); // Make the memory trail (without crumbs) at most the length of the crumbs trail. if (cmem.current_steps > c_crumbs->current_steps) { L = cmem.current_steps - c_crumbs->current_steps; for (i = 0; i < L; i++) { UpdateStGen(&cmem.initial_state, &cmem.initial_state, private_state); private_state->number_steps_locate += 1; } cmem.current_steps = c_crumbs->current_steps; } // Check for Robin Hood if (is_equal_st(&cmem.initial_state, &c_crumbs->initial_state, private_state->NWORDS_STATE)) { return false; } // The memory path is L steps shorter than the crumbs path. L = c_crumbs->current_steps - cmem.current_steps; k = 0; // Since there has been at least one step, there is at least one crumb. // Crumbs only store intermediate points, not the initial state and not // necessarily the current state. index = private_state->crumbs.positions[0] + 1; while ((L > index) && (k + 1 < private_state->crumbs.num_crumbs)) { // There are still crumbs to check and we haven't found the next crumb to reach. k++; index = private_state->crumbs.positions[k] + 1; } // Either have found the next crumb or ran out of crumbs to check. if (L > index) { // Ran out of crumbs to check, i.e. already in the interval beyond the last crumb. // Trails collide after last crumb. // Call original BacktrackGen on memory trail and shortened crumbs trail. copy_uint642st(&c_crumbs->initial_state, &private_state->crumbs.crumbs[private_state->crumbs.index_crumbs[k]], private_state->NWORDS_STATE); c_crumbs->current_steps -= (private_state->crumbs.positions[k] + 1); resp = BacktrackGen_core(&cmem, c_crumbs, S, private_state); } else { // Next crumb to check lies before (or is) the last crumb. c0_ = init_trip(private_state->NWORDS_STATE); copy_trip(&c0_, &cmem, private_state->NWORDS_STATE); do { cmem.current_steps = c0_.current_steps; copy_st(&cmem.initial_state, &c0_.initial_state, private_state->NWORDS_STATE); crumb = private_state->crumbs.crumbs[private_state->crumbs.index_crumbs[k]]; index = private_state->crumbs.positions[k] + 1; L = cmem.current_steps - (c_crumbs->current_steps - index); for (i = 0; i < L; i++) { UpdateStGen(&c0_.initial_state, &c0_.initial_state, private_state); private_state->number_steps_locate += 1; } c0_.current_steps -= L; k++; equal = is_equal_st_words(&c0_.initial_state, &crumb, private_state->NWORDS_STATE); } while (!equal && k < private_state->crumbs.num_crumbs); // Either found the colliding crumb or moved to the interval beyond the last crumb. if (equal) { // Have a colliding crumb. copy_uint642st(&cmem.current_state, &crumb, private_state->NWORDS_STATE); cmem.current_steps -= c0_.current_steps; if (k == 1) { c0_.current_steps = private_state->crumbs.positions[0] + 1; copy_uint642st(&c0_.initial_state, c_crumbs->initial_state.words, private_state->NWORDS_STATE); } else { c0_.current_steps = private_state->crumbs.positions[k - 1] - private_state->crumbs.positions[k - 2]; copy_uint642st(&c0_.initial_state, &private_state->crumbs.crumbs[private_state->crumbs.index_crumbs[k - 2]], private_state->NWORDS_STATE); } copy_uint642st(&c0_.current_state, &crumb, private_state->NWORDS_STATE); } else { // Collision happens after the last crumb. cmem.current_steps = c0_.current_steps; copy_uint642st(&cmem.initial_state, &crumb, private_state->NWORDS_STATE); } resp = BacktrackGen_core(&cmem, &c0_, S, private_state); free_trip(&c0_); } free_trip(&cmem); return resp; } bool BacktrackGen(trip_t *c0, trip_t *c1, shared_state_t *S, private_state_t *private_state) { // Backtrack function selection if (private_state->HANSEL_GRETEL) return BacktrackGen_Hansel_Gretel(c0, c1, S, private_state); else return BacktrackGen_core(c0, c1, S, private_state); }
merge.c
/**********************************************************/ /** * 234Compositor - Image data merging library * * Copyright (c) 2013-2015 Advanced Institute for Computational Science, RIKEN. * All rights reserved. * **/ /**********************************************************/ // @file merge.c // @brief Image data merging routines for 234Compositor // @author Jorji Nonaka (jorji@riken.jp) #ifndef COMPOSITOR234_H_INCLUDE #include "234compositor.h" #define COMPOSITOR234_H_INCLUDE #endif #ifndef COMPOSITOR234_MISC_H_INCLUDE #include "misc.h" #define COMPOSITOR234_MISC_H_INCLUDE #endif #include "merge.h" /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA32 Pixels) * Back-to-Front Order * * Consider Pre-multiplied (Weighted) images * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba32 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { over_a = (BYTE)over_image[ i + 3 ]; under_a = (BYTE)under_image[ i + 3 ]; if ( over_a == 0 ) { blend_a = under_a; blend_r = (BYTE)under_image[ i ]; blend_g = (BYTE)under_image[ i + 1 ]; blend_b = (BYTE)under_image[ i + 2 ]; } else if ( over_a == 255 ) { blend_a = over_a; blend_r = (BYTE)over_image[ i ]; blend_g = (BYTE)over_image[ i + 1 ]; blend_b = (BYTE)over_image[ i + 2 ]; } else { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; // Pre-calculate 1 - Src_A one_minus_alpha = (float)( 1.0f - ( over_a / 255.0f )); // ======================================================= blend_a = saturate_add( over_a, (BYTE)( under_a * one_minus_alpha )); blend_r = saturate_add( over_r, (BYTE)( under_r * one_minus_alpha )); blend_g = saturate_add( over_g, (BYTE)( under_g * one_minus_alpha )); blend_b = saturate_add( over_b, (BYTE)( under_b * one_minus_alpha )); // ======================================================= } blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); } return EXIT_SUCCESS; } #ifdef C99 int composite_alpha_rgbaz64 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz64 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; float over_z_f; float under_z_f; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; float blend_z; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ64; // 8 BYTES //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBAZ64; // 8 BYTES #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, \ over_r, over_g, over_b, over_a, over_z_f, \ under_r, under_g, under_b, under_a, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ64 ) // SKIP 8 BYTES { over_r = (BYTE)over_image_ptr[ i ]; over_g = (BYTE)over_image_ptr[ i + 1 ]; over_b = (BYTE)over_image_ptr[ i + 2 ]; over_a = (BYTE)over_image_ptr[ i + 3 ]; over_image_f_ptr = (float *)&over_image_ptr[ i + 4 ]; over_z_f = (float)over_image_f_ptr[ 0 ]; under_r = (BYTE)under_image_ptr[ i ]; under_g = (BYTE)under_image_ptr[ i + 1 ]; under_b = (BYTE)under_image_ptr[ i + 2 ]; under_a = (BYTE)under_image_ptr[ i + 3 ]; under_image_f_ptr = (float *)&under_image_ptr[ i + 4 ]; under_z_f = (float)under_image_f_ptr[ 0 ]; // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = under_r; blend_g = under_g; blend_b = under_b; blend_a = under_a; blend_z = under_z_f; } else { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z_f; } blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)blend_z; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA32 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba32f \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32f \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_a = (BYTE)over_image[ i + 3 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_a = (BYTE)under_image[ i + 3 ]; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float)( over_a / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float)( under_a / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = (float)( 1.0f - over_a_f ); // ======================================================= blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0f, 1.0f ); blend_g = clamp_float( blend_g, 0.0f, 1.0f ); blend_b = clamp_float( blend_b, 0.0f, 1.0f ); blend_a = clamp_float( blend_a, 0.0f, 1.0f ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a * 255 ); } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ64 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz64f \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz64f \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ64; // 8 BYTES //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBAZ64; // 8 BYTES #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, over_z_f, \ under_r, under_g, under_b, under_a, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ64 ) // SKIP 8 BYTES { over_r = (BYTE)over_image_ptr[ i ]; over_g = (BYTE)over_image_ptr[ i + 1 ]; over_b = (BYTE)over_image_ptr[ i + 2 ]; over_a = (BYTE)over_image_ptr[ i + 3 ]; over_image_f_ptr = (float *)&over_image_ptr[ i + 4 ]; over_z_f = (float)over_image_f_ptr[ 0 ]; under_r = (BYTE)under_image_ptr[ i ]; under_g = (BYTE)under_image_ptr[ i + 1 ]; under_b = (BYTE)under_image_ptr[ i + 2 ]; under_a = (BYTE)under_image_ptr[ i + 3 ]; under_image_f_ptr = (float *)&under_image_ptr[ i + 4 ]; under_z_f = (float)under_image_f_ptr[ 0 ]; // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a = under_a; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float)( over_a / 255.0f) ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float)( under_a / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a * 255 ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)over_z_f; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA56 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba56 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba56 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE under_r; BYTE under_g; BYTE under_b; float under_a; BYTE over_r; BYTE over_g; BYTE over_b; float over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA56; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA56 ) // SKIP 7 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_image_f_ptr = (float *)&over_image[ i + 3 ]; over_a = (float)*over_image_f_ptr; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_image_f_ptr = (float *)&under_image[ i + 3 ]; under_a = (float)*under_image_f_ptr; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float) over_a ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float) under_a ; // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 3 ]; *blend_image_f_ptr = (float) blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA64 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba64 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba64 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE under_r; BYTE under_g; BYTE under_b; float under_a; BYTE over_r; BYTE over_g; BYTE over_b; float over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA64; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA64 ) // SKIP 8 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_image_f_ptr = (float *)&over_image[ i + 4 ]; over_a = (float)*over_image_f_ptr; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_image_f_ptr = (float *)&under_image[ i + 4 ]; under_a = (float)*under_image_f_ptr; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float) over_a ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float) under_a ; // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); // R blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image_ptr[ i + 3 ] = (BYTE)0; // X blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; // A *blend_image_f_ptr = (float) blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ88 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz88 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz88 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE under_r; BYTE under_g; BYTE under_b; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; blend_z = 0; full_image_size = image_size * RGBAZ88; // 11 BYTES //===================================== // Depth Sorting //===================================== over_image_f_ptr = (float *)&over_image_ptr[ 3 ]; over_z_f = (float) over_image_f_ptr[ 1 ]; // Z under_image_f_ptr = (float *)&under_image_ptr[ 3 ]; under_z_f = (float)under_image_f_ptr[ 1 ]; // Z //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r_f, over_g_f, over_b_f, over_a_f, over_z_f, \ under_r, under_g, under_b_f, under_a_f, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ88 ) // SKIP 11 BYTES { over_r = (BYTE)over_image_ptr[ i ]; // R over_g = (BYTE)over_image_ptr[ i + 1 ]; // G over_b = (BYTE)over_image_ptr[ i + 2 ]; // B over_image_f_ptr = (float *)&over_image_ptr[ i + 3 ]; over_a_f = (float)over_image_f_ptr[ 0 ]; // A over_z_f = (float)over_image_f_ptr[ 1 ]; // Z under_r = (BYTE)under_image_ptr[ i ]; // R under_g = (BYTE)under_image_ptr[ i + 1 ]; // G under_b = (BYTE)under_image_ptr[ i + 2 ]; // B under_image_f_ptr = (float *)&under_image_ptr[ i + 3 ]; under_a_f = (float)under_image_f_ptr[ 0 ]; // A under_z_f = (float)under_image_f_ptr[ 1 ]; // Z // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a_f; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a_f = under_a_f; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a_f = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); // R blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image_f_ptr = (float *)&blend_image_ptr[ i + 3 ]; blend_image_f_ptr[ 0 ] = (float)blend_a; // A blend_image_f_ptr[ 1 ] = (float)over_z_f; // Z } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ96 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz96 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz96 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE under_r; BYTE under_g; BYTE under_b; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ96; // 12 BYTES //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_image_f_ptr, under_image_f_ptr, blend_image_f_ptr, \ over_r, over_g, over_b, \ under_r, under_g, under_b, \ over_r_f, over_g_f, over_b_f, over_a_f, over_z_f, \ under_r_f, under_g_f, under_b_f, under_a_f, under_z_f, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBAZ96 ) // SKIP 12 BYTES { over_r = (BYTE)over_image[ i ]; // R over_g = (BYTE)over_image[ i + 1 ]; // G over_b = (BYTE)over_image[ i + 2 ]; // B over_image_f_ptr = (float *)&over_image[ i + 4 ]; over_a_f = (float)over_image_f_ptr[ 0 ]; // A over_z_f = (float)over_image_f_ptr[ 1 ]; // Z under_r = (BYTE)under_image[ i ]; // R under_g = (BYTE)under_image[ i + 1 ]; // G under_b = (BYTE)under_image[ i + 2 ]; // B under_image_f_ptr = (float *)&under_image[ i + 4 ]; under_a_f = (float)under_image_f_ptr[ 0 ]; // A under_z_f = (float)under_image_f_ptr[ 1 ]; // Z // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a_f; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a_f = under_a_f; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a_f = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (BYTE)( blend_r * 255 ); // R blend_image[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image[ i + 3 ] = (BYTE)0; // X blend_image_f_ptr = (float *)&blend_image[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)blend_a; // A blend_image_f_ptr[ 1 ] = (float)over_z_f; // Z } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA128 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba128 \ ( float* restrict over_image, \ float* restrict under_image, \ float* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba128 \ ( float* over_image, \ float* under_image, \ float* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float under_r; float under_g; float under_b; float under_a; float over_r; float over_g; float over_b; float over_a; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA; // 4 elements #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements(FLOAT) { // Separate R, G, B and A values of both // the foreground and background colors over_r = (float)over_image[ i ]; over_g = (float)over_image[ i + 1 ]; over_b = (float)over_image[ i + 2 ]; over_a = (float)over_image[ i + 3 ]; under_r = (float)under_image[ i ]; under_g = (float)under_image[ i + 1 ]; under_b = (float)under_image[ i + 2 ]; under_a = (float)under_image[ i + 3 ]; // ============================================= // Eliminate branching for compiler optimization // ============================================= // Pre-calculate 1 - Src_A one_minus_alpha = (float)(1.0f - over_a); // Calculate Final alpha value blend_a = (float)( over_a + ( under_a * one_minus_alpha )); blend_r = (float)( over_r + ( under_r * one_minus_alpha )); blend_g = (float)( over_g + ( under_g * one_minus_alpha )); blend_b = (float)( over_b + ( under_b * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (float)blend_r; blend_image[ i + 1 ] = (float)blend_g; blend_image[ i + 2 ] = (float)blend_b; blend_image[ i + 3 ] = (float)blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ160 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz160 \ ( float* restrict over_image, \ float* restrict under_image, \ float* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz160 \ ( float* over_image, \ float* under_image, \ float* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float under_r; float under_g; float under_b; float under_a; float under_z; float over_r; float over_g; float over_b; float over_a; float over_z; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_z = 0.0f; full_image_size = image_size * RGBAZ; // 5 elements //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, over_z, \ under_r, under_g, under_b, under_a, under_z, \ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ ) // SKIP 5 elements(FLOAT) { // Separate R, G, B and A values of both // the foreground and background colors over_r = (float)over_image[ i ]; over_g = (float)over_image[ i + 1 ]; over_b = (float)over_image[ i + 2 ]; over_a = (float)over_image[ i + 3 ]; over_z = (float)over_image[ i + 4 ]; under_r = (float)under_image[ i ]; under_g = (float)under_image[ i + 1 ]; under_b = (float)under_image[ i + 2 ]; under_a = (float)under_image[ i + 3 ]; under_z = (float)under_image[ i + 4 ]; // Depth sorting if necessary if ( over_z > under_z ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z; over_r = under_r; over_g = under_g; over_b = under_b; over_a = under_a; over_z = under_z; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a = blend_a; under_z = blend_z; } // ======================================================= // Pre-calculate 1 - Src_A one_minus_alpha = (float)(1.0f - over_a); // Calculate Final alpha value blend_a = (float)( over_a + ( under_a * one_minus_alpha )); blend_r = (float)( over_r + ( under_r * one_minus_alpha )); blend_g = (float)( over_g + ( under_g * one_minus_alpha )); blend_b = (float)( over_b + ( under_b * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (float)blend_r; blend_image[ i + 1 ] = (float)blend_g; blend_image[ i + 2 ] = (float)blend_b; blend_image[ i + 3 ] = (float)blend_a; blend_image[ i + 4 ] = (float)over_z; } return EXIT_SUCCESS; } // ================================================================= // ALPHA BLENDING IMAGE COMPOSITION // ================================================================= // Optimization based on LUT (HP Image Compositing Library) // // Parallel Compositing Library // http://sourceforge.net/projects/paracomp // ================================================================= /* BEGINPARACOMPCOPYRIGHT * The Parallel Compositing Library * Copyright (c) 2007 Hewlett-Packard Development Company, L.P. * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * ENDPARACOMPCOPYRIGHT */ /*===========================================================================*/ /** * @brief Generate look up tables for alpha blending operation. */ /*===========================================================================*/ void Create_AlphaBlend_LUT ( void ) { unsigned int Alpha; unsigned int Color; unsigned int Saturation; unsigned int Color_Val; unsigned int Alpha_Div_256; unsigned int Alpha_Sub_255; // Generate Product Lookup Table for ( Alpha = 0; Alpha < 256; Alpha++ ) { Alpha_Div_256 = Alpha << 8; Alpha_Sub_255 = 255 - Alpha; for ( Color = 0; Color < 256; Color++ ) { Color_Val = (unsigned int)(( Alpha_Sub_255 * Color ) + 0x80 ) >> 8; LUT_Mult[ Alpha_Div_256 | Color ] = ( BYTE )Color_Val; } } // Generate Saturation Lookup Table for ( Saturation = 0; Saturation < 512; Saturation++ ) { LUT_Sat[ Saturation ] = (BYTE)(( Saturation > 255 ) ? 255 : Saturation); } } /*===========================================================================*/ /** * @brief Alpha-blend compositing. * * @param order [in] OVER or UNDER * @param othr_image [in] Image to be alpha blended * @param recv_image [in] Image to be alpha blended * @param image_size [in] Image size * @param blnd_image [out] Alpha blended image */ /*===========================================================================*/ #ifdef C99 int composite_alpha_rgba32_LUT \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32_LUT \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE *blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; unsigned int Alpha_Div_256; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, Alpha_Div_256, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_a = (BYTE)over_image[ i + 3 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_a = (BYTE)under_image[ i + 3 ]; Alpha_Div_256 = ((unsigned int)over_a) << 8; // Calculate RGBA component values blend_r = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_r ) ] ) \ + ((unsigned int)over_r ) ]; blend_g = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_g) ] ) \ + ((unsigned int)over_g) ]; blend_b = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_b ) ] ) \ + ((unsigned int)over_b ) ]; blend_a = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_a) ] ) \ + ((unsigned int)over_a) ]; blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); } return EXIT_SUCCESS; }
ssor.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB LU code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif #include "applu.incl" #include "timers.h" //--------------------------------------------------------------------- // Thread synchronization for pipeline operation //--------------------------------------------------------------------- /* common /threadinfo1/ */ int isync[ISIZ2+1]; /* common /threadinfo2/ */ int mthreadnum, iam; #pragma omp threadprivate(mthreadnum,iam) //--------------------------------------------------------------------- // to perform pseudo-time stepping SSOR iterations // for five nonlinear pde's. //--------------------------------------------------------------------- void ssor(int niter) { //kai // int k1,k2,k3,k4; // consistent_data(&k1, "int", 1); // consistent_data(&k2, "int", 1); // consistent_data(&k3, "int", 1); // consistent_data(&k4, "int", 1); //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m, n; int istep; double tmp, tmp2, tv[ISIZ2][ISIZ1][5]; double delunm[5]; //kai consistent_data(&istep, "int", 1); //--------------------------------------------------------------------- // begin pseudo-time stepping iterations //--------------------------------------------------------------------- tmp = 1.0 / ( omega * ( 2.0 - omega ) ); //--------------------------------------------------------------------- // initialize a,b,c,d to zero (guarantees that page tables have been // formed, if applicable on given architecture, before timestepping). //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(m,n,i,j) { #pragma omp for nowait for (j = jst; j < jend; j++) { for (i = ist; i < iend; i++) { for (n = 0; n < 5; n++) { for (m = 0; m < 5; m++) { a[j][i][n][m] = 0.0; b[j][i][n][m] = 0.0; c[j][i][n][m] = 0.0; d[j][i][n][m] = 0.0; } } } } #pragma omp for nowait for (j = jend - 1; j >= jst; j--) { for (i = iend - 1; i >= ist; i--) { for (n = 0; n < 5; n++) { for (m = 0; m < 5; m++) { au[j][i][n][m] = 0.0; bu[j][i][n][m] = 0.0; cu[j][i][n][m] = 0.0; du[j][i][n][m] = 0.0; } } } } } //end parallel for (i = 1; i <= t_last; i++) { timer_clear(i); } //--------------------------------------------------------------------- // compute the steady-state residuals //--------------------------------------------------------------------- rhs(); //--------------------------------------------------------------------- // compute the L2 norms of newton iteration residuals //--------------------------------------------------------------------- l2norm( ISIZ1, ISIZ2, ISIZ3, nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm ); for (i = 1; i <= t_last; i++) { timer_clear(i); } timer_start(1); //kai if (niter > 1) { flush_whole_cache(); //start_crash(); } //--------------------------------------------------------------------- // the timestep loop //--------------------------------------------------------------------- for (istep = 1; istep <= niter; istep++) { if ((istep % 20) == 0 || istep == itmax || istep == 1) { if (niter > 1) printf(" Time step %4d\n", istep); } //if(istep == 5) // start_crash(); //if(istep == 11) // end_crash(); //--------------------------------------------------------------------- // perform SSOR iteration //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(i,j,k,m,tmp2) \ shared(ist,iend,jst,jend,nx,ny,nz,nx0,ny0,omega) { #pragma omp master if (timeron) timer_start(t_rhs); tmp2 = dt; #pragma omp for nowait for (k = 1; k < nz - 1; k++) { for (j = jst; j < jend; j++) { for (i = ist; i < iend; i++) { for (m = 0; m < 5; m++) { rsd[k][j][i][m] = tmp2 * rsd[k][j][i][m]; } } } //kai k1 = k; } #pragma omp master if (timeron) timer_stop(t_rhs); mthreadnum = 0; mthreadnum = omp_get_num_threads() - 1; if (mthreadnum > jend - jst) mthreadnum = jend - jst; iam = 0; iam = omp_get_thread_num(); if (iam <= mthreadnum) isync[iam] = 0; #pragma omp barrier for (k = 1; k < nz -1; k++) { //--------------------------------------------------------------------- // form the lower triangular part of the jacobian matrix //--------------------------------------------------------------------- #pragma omp master if (timeron) timer_start(t_jacld); jacld(k); #pragma omp master { if (timeron) timer_stop(t_jacld); //--------------------------------------------------------------------- // perform the lower triangular solution //--------------------------------------------------------------------- if (timeron) timer_start(t_blts); } blts( ISIZ1, ISIZ2, ISIZ3, nx, ny, nz, k, omega, rsd, a, b, c, d, ist, iend, jst, jend, nx0, ny0 ); #pragma omp master if (timeron) timer_stop(t_blts); //kai k2 = k; if(k2 == 30 && istep == 55) { FILE *file; file = fopen("checkpoint.txt","w"); int iteration1=0,iteration2=0,iteration3=0,iteration4=0; for(iteration1=0; iteration1<ISIZ2;iteration1++) { for(iteration2 = 0; iteration2<ISIZ1/2*2+1; iteration2++) for(iteration3 = 0; iteration3<5; iteration3++) for(iteration4 = 0; iteration4<5; iteration4++) fprintf(file,"%20.12E\n",a[iteration1][iteration2][iteration3][iteration4]); } for(iteration1=0; iteration1<ISIZ2;iteration1++) { for(iteration2 = 0; iteration2<ISIZ1/2*2+1; iteration2++) for(iteration3 = 0; iteration3<5; iteration3++) for(iteration4 = 0; iteration4<5; iteration4++) fprintf(file,"%20.12E\n",b[iteration1][iteration2][iteration3][iteration4]); } for(iteration1=0; iteration1<ISIZ2;iteration1++) { for(iteration2 = 0; iteration2<ISIZ1/2*2+1; iteration2++) for(iteration3 = 0; iteration3<5; iteration3++) for(iteration4 = 0; iteration4<5; iteration4++) fprintf(file,"%20.12E\n",c[iteration1][iteration2][iteration3][iteration4]); } for(iteration1=0; iteration1<ISIZ2;iteration1++) { for(iteration2 = 0; iteration2<ISIZ1/2*2+1; iteration2++) for(iteration3 = 0; iteration3<5; iteration3++) for(iteration4 = 0; iteration4<5; iteration4++) fprintf(file,"%20.12E\n",d[iteration1][iteration2][iteration3][iteration4]); } fclose(file); } } #pragma omp barrier for (k = nz - 2; k > 0; k--) { //--------------------------------------------------------------------- // form the strictly upper triangular part of the jacobian matrix //--------------------------------------------------------------------- #pragma omp master if (timeron) timer_start(t_jacu); jacu(k); #pragma omp master { if (timeron) timer_stop(t_jacu); //--------------------------------------------------------------------- // perform the upper triangular solution //--------------------------------------------------------------------- if (timeron) timer_start(t_buts); } buts( ISIZ1, ISIZ2, ISIZ3, nx, ny, nz, k, omega, rsd, tv, du, au, bu, cu, ist, iend, jst, jend, nx0, ny0 ); #pragma omp master if (timeron) timer_stop(t_buts); //kai k3 = k; /* if(k3 == 30 && istep == 55) { FILE *file; file = fopen("checkpoint.txt","w"); int iteration1=0,iteration2=0,iteration3=0,iteration4=0; for(iteration1=0; iteration1<ISIZ3;iteration1++) { for(iteration2 = 0; iteration2<ISIZ2/2*2+1; iteration2++) for(iteration3 = 0; iteration3<ISIZ1/2*2+1; iteration3++) for(iteration4 = 0; iteration4<5; iteration4++) fprintf(file,"%20.12E\n",rsd[iteration1][iteration2][iteration3][iteration4]); } fclose(file); }*/ } #pragma omp barrier //--------------------------------------------------------------------- // update the variables //--------------------------------------------------------------------- #pragma omp master if (timeron) timer_start(t_add); tmp2 = tmp; #pragma omp for nowait for (k = 1; k < nz-1; k++) { for (j = jst; j < jend; j++) { for (i = ist; i < iend; i++) { for (m = 0; m < 5; m++) { u[k][j][i][m] = u[k][j][i][m] + tmp2 * rsd[k][j][i][m]; } } } //kai k4 = k; } } //end parallel if (timeron) timer_stop(t_add); //--------------------------------------------------------------------- // compute the max-norms of newton iteration corrections //--------------------------------------------------------------------- if ( (istep % inorm) == 0 ) { if (timeron) timer_start(t_l2norm); l2norm( ISIZ1, ISIZ2, ISIZ3, nx0, ny0, nz0, ist, iend, jst, jend, rsd, delunm ); if (timeron) timer_stop(t_l2norm); /* if ( ipr == 1 ) { printf(" \n RMS-norm of SSOR-iteration correction " "for first pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for second pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for third pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for fourth pde = %12.5E\n", " RMS-norm of SSOR-iteration correction " "for fifth pde = %12.5E\n", delunm[0], delunm[1], delunm[2], delunm[3], delunm[4]); } else if ( ipr == 2 ) { printf("(%5d,%15.6f)\n", istep, delunm[4]); } */ } //--------------------------------------------------------------------- // compute the steady-state residuals //--------------------------------------------------------------------- rhs(); //--------------------------------------------------------------------- // compute the max-norms of newton iteration residuals //--------------------------------------------------------------------- if ( ((istep % inorm ) == 0 ) || ( istep == itmax ) ) { if (timeron) timer_start(t_l2norm); l2norm( ISIZ1, ISIZ2, ISIZ3, nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm ); if (timeron) timer_stop(t_l2norm); /* if ( ipr == 1 ) { printf(" \n RMS-norm of steady-state residual for " "first pde = %12.5E\n" " RMS-norm of steady-state residual for " "second pde = %12.5E\n" " RMS-norm of steady-state residual for " "third pde = %12.5E\n" " RMS-norm of steady-state residual for " "fourth pde = %12.5E\n" " RMS-norm of steady-state residual for " "fifth pde = %12.5E\n", rsdnm[0], rsdnm[1], rsdnm[2], rsdnm[3], rsdnm[4]); } */ } //--------------------------------------------------------------------- // check the newton-iteration residuals against the tolerance levels //--------------------------------------------------------------------- if ( ( rsdnm[0] < tolrsd[0] ) && ( rsdnm[1] < tolrsd[1] ) && ( rsdnm[2] < tolrsd[2] ) && ( rsdnm[3] < tolrsd[3] ) && ( rsdnm[4] < tolrsd[4] ) ) { //if (ipr == 1 ) { printf(" \n convergence was achieved after %4d pseudo-time steps\n", istep); //} break; } maxtime = timer_read(1); /* //EasyCrash: candidates of critical data obj: u, rsd, frct, gs, rho\_i, rsdnm, a, b, c, d, au, bu, cu, du //EasyCrash: critical data objs: u //checkpointing: checkpoint(u, ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5*sizeof(double)); checkpoint(rsd, sizeof(double)*ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5); checkpoint(frct, sizeof(double)*ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5); checkpoint(qs, ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5*sizeof(double)); checkpoint(rho_i, ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5*sizeof(double)); checkpoint(rsdnm, 5*sizeof(double)); checkpoint(a, ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(b, ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(c, ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(d, ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(au,ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(bu,ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(cu,ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); checkpoint(du,ISIZ2*(ISIZ1/2*2+1)*5*5*sizeof(double)); */ // /* //EC: EC(u, ISIZ3*(ISIZ2/2*2+1)*(ISIZ1/2*2+1)*5*sizeof(double)); // */ } //kai //if (niter > 1) { // end_crash(); //} timer_stop(1); maxtime = timer_read(1); }
GB_unaryop__ainv_fp64_int16.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__ainv_fp64_int16 // op(A') function: GB_tran__ainv_fp64_int16 // C type: double // A type: int16_t // cast: double cij = (double) aij // unaryop: cij = -aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, 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_AINV || GxB_NO_FP64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_fp64_int16 ( double *Cx, // Cx and Ax may be aliased int16_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__ainv_fp64_int16 ( 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
mandel_par.c
/* ** PROGRAM: Mandelbrot area (solution) ** ** PURPOSE: Program to compute the area of a Mandelbrot set. ** The correct answer should be around 1.510659. ** ** USAGE: Program runs without input ... just run the executable ** ** ADDITIONAL EXERCISES: Experiment with the schedule clause to fix ** the load imbalance. Experiment with atomic vs. critical vs. ** reduction for numoutside. ** ** HISTORY: Written: (Mark Bull, August 2011). ** ** Changed "comples" to "d_comples" to avoid collsion with ** math.h complex type. Fixed data environment errors ** (Tim Mattson, September 2011) ** ** Changed "atomic" to "critical" to match Common Core ** (Helen He, November 2020) */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> # define NPOINTS 1000 # define MXITR 1000 struct d_complex { double r; double i; }; void testpoint(struct d_complex); struct d_complex c; int numoutside = 0; int main () { int i, j; double area, error, eps = 1.0e-5; // Loop over grid of points in the complex plane which contains the Mandelbrot set, // testing each point to see whether it is inside or outside the set. omp_set_num_threads(4); #pragma omp parallel for private(c,j) firstprivate(eps) for (i = 0; i < NPOINTS; i++) { for (j = 0; j < NPOINTS; j++) { c.r = -2.0 + 2.5 * (double)(i)/(double)(NPOINTS) + eps; c.i = 1.125 * (double)(j)/(double)(NPOINTS) + eps; testpoint(c); } } // Calculate area of set and error estimate and output the results area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS \ - numoutside)/(double)(NPOINTS * NPOINTS); error = area / (double)NPOINTS; printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n",area,error); printf("Correct answer should be around 1.510659\n"); } void testpoint(struct d_complex c) { // Does the iteration z=z*z+c, until |z| > 2 when point is known to be outside set // If loop count reaches MAXITER, point is considered to be inside the set struct d_complex z; int iter; double temp; z = c; for (iter = 0; iter < MXITR; iter++) { temp = (z.r * z.r) - (z.i * z.i) + c.r; z.i = z.r * z.i * 2 + c.i; z.r = temp; if ((z.r * z.r + z.i * z.i) > 4.0) { #pragma omp critical numoutside++; break; } } }
matmul.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ void matmul(level_type * level, double *C, int * id_A, int * id_B, int rows, int cols, int A_equals_B_transpose){ // *id_A = m vector_id's (conceptually pointers to the rows of a m x level->num_my_boxes*volume matrix) // *id_B = n vector_id's (conceptually pointers to the columns of a level->num_my_boxes*volume matrix x n) // *C is a mxn matrix where C[rows][cols] = dot(id_A[rows],id_B[cols]) // FIX, id_A and id_B are likely the same and thus C[][] will be symmetric (modulo missing row?) // if(A_equals_B_transpose && (cols>=rows)) then use id_B and only run for nn>=mm // common case for s-step Krylov methods // C_is_symmetric && cols< rows (use id_A) int mm,nn; uint64_t _timeStart = CycleTime(); // FIX... rather than performing an all_reduce on the essentially symmetric [G,g], do the all_reduce on the upper triangle and then duplicate (saves BW) #ifdef _OPENMP #pragma omp parallel for schedule(static,1) collapse(2) #endif for(mm=0;mm<rows;mm++){ for(nn=0;nn<cols;nn++){ if(nn>=mm){ // upper triangular int box; double a_dot_b_level = 0.0; for(box=0;box<level->num_my_boxes;box++){ int i,j,k; const int jStride = level->my_boxes[box].jStride; const int kStride = level->my_boxes[box].kStride; const int ghosts = level->my_boxes[box].ghosts; const int dim = level->my_boxes[box].dim; double * __restrict__ grid_a = level->my_boxes[box].vectors[id_A[mm]] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point double * __restrict__ grid_b = level->my_boxes[box].vectors[id_B[nn]] + ghosts*(1+jStride+kStride); double a_dot_b_box = 0.0; for(k=0;k<dim;k++){ for(j=0;j<dim;j++){ for(i=0;i<dim;i++){ int ijk = i + j*jStride + k*kStride; a_dot_b_box += grid_a[ijk]*grid_b[ijk]; }}} a_dot_b_level+=a_dot_b_box; } C[mm*cols + nn] = a_dot_b_level; // C[mm][nn] if((mm<cols)&&(nn<rows)){C[nn*cols + mm] = a_dot_b_level;}// C[nn][mm] } }} level->cycles.blas3 += (uint64_t)(CycleTime()-_timeStart); #ifdef USE_MPI double *send_buffer = (double*)malloc(rows*cols*sizeof(double)); for(mm=0;mm<rows;mm++){ for(nn=0;nn<cols;nn++){ send_buffer[mm*cols + nn] = C[mm*cols + nn]; }} uint64_t _timeStartAllReduce = CycleTime(); MPI_Allreduce(send_buffer,C,rows*cols,MPI_DOUBLE,MPI_SUM,level->MPI_COMM_ALLREDUCE); uint64_t _timeEndAllReduce = CycleTime(); level->cycles.collectives += (uint64_t)(_timeEndAllReduce-_timeStartAllReduce); free(send_buffer); #endif }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator( llvm::function_ref<void(const Designation &)> CodeCompleteCB); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype, SourceLocation SwiftNewtypeLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); void ParsePtrauthQualifier(ParsedAttributes &Attrs); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); /// Parse the given string as a type. /// /// This is a dangerous utility function currently employed only by API notes. /// It is not a general entry-point for safely parsing types from strings. /// /// \param typeStr The string to be parsed as a type. /// \param context The name of the context in which this string is being /// parsed, which will be used in diagnostics. /// \param includeLoc The location at which this parse was triggered. TypeResult parseTypeFromString(StringRef typeStr, StringRef context, SourceLocation includeLoc); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); ExprResult ParseBuiltinPtrauthTypeDiscriminator(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
GB_unop__identity_fc64_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fc64_fc32) // op(A') function: GB (_unop_tran__identity_fc64_fc32) // C type: GxB_FC64_t // A type: GxB_FC32_t // cast: GxB_FC64_t cij = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc64_fc32) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (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_fc64_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nested_task_creation.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <omp.h> #include "omp_my_sleep.h" /* * This test creates tasks that themselves create a new task. * The runtime has to take care that they are correctly freed. */ int main() { #pragma omp task { #pragma omp task { my_sleep( 0.1 ); } } #pragma omp parallel num_threads(2) { #pragma omp single #pragma omp task { #pragma omp task { my_sleep( 0.1 ); } } } printf("pass\n"); return 0; }
fill_int2e.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <math.h> #include "config.h" #include "cint.h" #define MAX(I,J) ((I) > (J) ? (I) : (J)) #define MIN(I,J) ((I) < (J) ? (I) : (J)) int GTOmax_shell_dim(const int *ao_loc, const int *shls_slice, int ncenter) { int i; int i0 = shls_slice[0]; int i1 = shls_slice[1]; int di = 0; for (i = 1; i < ncenter; i++) { i0 = MIN(i0, shls_slice[i*2 ]); i1 = MAX(i1, shls_slice[i*2+1]); } for (i = i0; i < i1; i++) { di = MAX(di, ao_loc[i+1]-ao_loc[i]); } return di; } int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env) { int i, n; int i0 = shls_slice[0]; int i1 = shls_slice[1]; for (i = 1; i < ncenter; i++) { i0 = MIN(i0, shls_slice[i*2 ]); i1 = MAX(i1, shls_slice[i*2+1]); } int shls[4]; int cache_size = 0; for (i = i0; i < i1; i++) { shls[0] = i; shls[1] = i; shls[2] = i; shls[3] = i; n = (*intor)(NULL, NULL, shls, atm, natm, bas, nbas, env, NULL, NULL); cache_size = MAX(cache_size, n); } return cache_size; } /* ************************************************* * 2e AO integrals in s4, s2ij, s2kl, s1 */ void GTOnr2e_fill_s1(int (*intor)(), int (*fprescreen)(), double *eri, double *buf, int comp, int ishp, int jshp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; int jsh1 = shls_slice[3]; int ksh0 = shls_slice[4]; int ksh1 = shls_slice[5]; int lsh0 = shls_slice[6]; int lsh1 = shls_slice[7]; int ni = ao_loc[ish1] - ao_loc[ish0]; int nj = ao_loc[jsh1] - ao_loc[jsh0]; int nk = ao_loc[ksh1] - ao_loc[ksh0]; int nl = ao_loc[lsh1] - ao_loc[lsh0]; size_t nij = ni * nj; size_t nkl = nk * nl; size_t neri = nij * nkl; int ish = ishp + ish0; int jsh = jshp + jsh0; int i0 = ao_loc[ish] - ao_loc[ish0]; int j0 = ao_loc[jsh] - ao_loc[jsh0]; eri += nkl * (i0 * nj + j0); int di = ao_loc[ish+1] - ao_loc[ish]; int dj = ao_loc[jsh+1] - ao_loc[jsh]; int dij = di * dj; int k0, l0, dk, dl, dijk, dijkl; int i, j, k, l, icomp; int ksh, lsh; int shls[4]; double *eri0, *peri, *buf0, *pbuf, *cache; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh < lsh1; lsh++) { shls[2] = ksh; shls[3] = lsh; k0 = ao_loc[ksh] - ao_loc[ksh0]; l0 = ao_loc[lsh] - ao_loc[lsh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; dl = ao_loc[lsh+1] - ao_loc[lsh]; dijk = dij * dk; dijkl = dijk * dl; cache = buf + dijkl * comp; if ((*fprescreen)(shls, atm, bas, env) && (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache)) { eri0 = eri + k0*nl+l0; buf0 = buf; for (icomp = 0; icomp < comp; icomp++) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[k*nl+l] = pbuf[l*dijk]; } } } } buf0 += dijkl; eri0 += neri; } } else { eri0 = eri + k0*nl+l0; for (icomp = 0; icomp < comp; icomp++) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++) { for (l = 0; l < dl; l++) { peri[k*nl+l] = 0; } } } } eri0 += neri; } } } } } void GTOnr2e_fill_s2ij(int (*intor)(), int (*fprescreen)(), double *eri, double *buf, int comp, int ishp, int jshp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { if (ishp < jshp) { return; } int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; //int jsh1 = shls_slice[3]; int ksh0 = shls_slice[4]; int ksh1 = shls_slice[5]; int lsh0 = shls_slice[6]; int lsh1 = shls_slice[7]; int ni = ao_loc[ish1] - ao_loc[ish0]; //int nj = ao_loc[jsh1] - ao_loc[jsh0]; int nk = ao_loc[ksh1] - ao_loc[ksh0]; int nl = ao_loc[lsh1] - ao_loc[lsh0]; size_t nij = ni * (ni+1) / 2; size_t nkl = nk * nl; size_t neri = nij * nkl; int ish = ishp + ish0; int jsh = jshp + jsh0; int i0 = ao_loc[ish] - ao_loc[ish0]; int j0 = ao_loc[jsh] - ao_loc[jsh0]; eri += nkl * (i0*(i0+1)/2 + j0); int di = ao_loc[ish+1] - ao_loc[ish]; int dj = ao_loc[jsh+1] - ao_loc[jsh]; int dij = di * dj; int k0, l0, dk, dl, dijk, dijkl; int i, j, k, l, icomp; int ksh, lsh; int shls[4]; double *eri0, *peri0, *peri, *buf0, *pbuf, *cache; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh < lsh1; lsh++) { shls[2] = ksh; shls[3] = lsh; k0 = ao_loc[ksh] - ao_loc[ksh0]; l0 = ao_loc[lsh] - ao_loc[lsh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; dl = ao_loc[lsh+1] - ao_loc[lsh]; dijk = dij * dk; dijkl = dijk * dl; cache = buf + dijkl * comp; if ((*fprescreen)(shls, atm, bas, env) && (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache)) { eri0 = eri + k0*nl+l0; buf0 = buf; for (icomp = 0; icomp < comp; icomp++) { peri0 = eri0; if (ishp > jshp) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[k*nl+l] = pbuf[l*dijk]; } } } } } else { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[k*nl+l] = pbuf[l*dijk]; } } } } } buf0 += dijkl; eri0 += neri; } } else { eri0 = eri + k0*nl+l0; for (icomp = 0; icomp < comp; icomp++) { peri0 = eri0; if (ishp > jshp) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++) { for (l = 0; l < dl; l++) { peri[k*nl+l] = 0; } } } } } else { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++) { for (l = 0; l < dl; l++) { peri[k*nl+l] = 0; } } } } } eri0 += neri; } } } } } void GTOnr2e_fill_s2kl(int (*intor)(), int (*fprescreen)(), double *eri, double *buf, int comp, int ishp, int jshp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; int jsh1 = shls_slice[3]; int ksh0 = shls_slice[4]; int ksh1 = shls_slice[5]; int lsh0 = shls_slice[6]; //int lsh1 = shls_slice[7]; int ni = ao_loc[ish1] - ao_loc[ish0]; int nj = ao_loc[jsh1] - ao_loc[jsh0]; int nk = ao_loc[ksh1] - ao_loc[ksh0]; //int nl = ao_loc[lsh1] - ao_loc[lsh0]; size_t nij = ni * nj; size_t nkl = nk * (nk+1) / 2; size_t neri = nij * nkl; int ish = ishp + ish0; int jsh = jshp + jsh0; int i0 = ao_loc[ish] - ao_loc[ish0]; int j0 = ao_loc[jsh] - ao_loc[jsh0]; eri += nkl * (i0 * nj + j0); int di = ao_loc[ish+1] - ao_loc[ish]; int dj = ao_loc[jsh+1] - ao_loc[jsh]; int dij = di * dj; int k0, l0, dk, dl, dijk, dijkl; int i, j, k, l, icomp; int ksh, lsh, kshp, lshp; int shls[4]; double *eri0, *peri, *buf0, *pbuf, *cache; shls[0] = ish; shls[1] = jsh; for (kshp = 0; kshp < ksh1-ksh0; kshp++) { for (lshp = 0; lshp <= kshp; lshp++) { ksh = kshp + ksh0; lsh = lshp + lsh0; shls[2] = ksh; shls[3] = lsh; k0 = ao_loc[ksh] - ao_loc[ksh0]; l0 = ao_loc[lsh] - ao_loc[lsh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; dl = ao_loc[lsh+1] - ao_loc[lsh]; dijk = dij * dk; dijkl = dijk * dl; cache = buf + dijkl * comp; if ((*fprescreen)(shls, atm, bas, env) && (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache)) { eri0 = eri + k0*(k0+1)/2+l0; buf0 = buf; for (icomp = 0; icomp < comp; icomp++) { if (kshp > lshp) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[l] = pbuf[l*dijk]; } } } } } else { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l <= k; l++) { peri[l] = pbuf[l*dijk]; } } } } } buf0 += dijkl; eri0 += neri; } } else { eri0 = eri + k0*(k0+1)/2+l0; for (icomp = 0; icomp < comp; icomp++) { if (kshp > lshp) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l < dl; l++) { peri[l] = 0; } } } } } else { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { peri = eri0 + nkl*(i*nj+j); for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l <= k; l++) { peri[l] = 0; } } } } } eri0 += neri; } } } } } void GTOnr2e_fill_s4(int (*intor)(), int (*fprescreen)(), double *eri, double *buf, int comp, int ishp, int jshp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { if (ishp < jshp) { return; } int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; //int jsh1 = shls_slice[3]; int ksh0 = shls_slice[4]; int ksh1 = shls_slice[5]; int lsh0 = shls_slice[6]; //int lsh1 = shls_slice[7]; int ni = ao_loc[ish1] - ao_loc[ish0]; //int nj = ao_loc[jsh1] - ao_loc[jsh0]; int nk = ao_loc[ksh1] - ao_loc[ksh0]; //int nl = ao_loc[lsh1] - ao_loc[lsh0]; size_t nij = ni * (ni+1) / 2; size_t nkl = nk * (nk+1) / 2; size_t neri = nij * nkl; int ish = ishp + ish0; int jsh = jshp + jsh0; int i0 = ao_loc[ish] - ao_loc[ish0]; int j0 = ao_loc[jsh] - ao_loc[jsh0]; eri += nkl * (i0*(i0+1)/2 + j0); int di = ao_loc[ish+1] - ao_loc[ish]; int dj = ao_loc[jsh+1] - ao_loc[jsh]; int dij = di * dj; int k0, l0, dk, dl, dijk, dijkl; int i, j, k, l, icomp; int ksh, lsh, kshp, lshp; int shls[4]; double *eri0, *peri0, *peri, *buf0, *pbuf, *cache; shls[0] = ish; shls[1] = jsh; for (kshp = 0; kshp < ksh1-ksh0; kshp++) { for (lshp = 0; lshp <= kshp; lshp++) { ksh = kshp + ksh0; lsh = lshp + lsh0; shls[2] = ksh; shls[3] = lsh; k0 = ao_loc[ksh] - ao_loc[ksh0]; l0 = ao_loc[lsh] - ao_loc[lsh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; dl = ao_loc[lsh+1] - ao_loc[lsh]; dijk = dij * dk; dijkl = dijk * dl; cache = buf + dijkl * comp; if ((*fprescreen)(shls, atm, bas, env) && (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache)) { eri0 = eri + k0*(k0+1)/2+l0; buf0 = buf; for (icomp = 0; icomp < comp; icomp++) { peri0 = eri0; if (kshp > lshp && ishp > jshp) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[l] = pbuf[l*dijk]; } } } } } else if (ish > jsh) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l <= k; l++) { peri[l] = pbuf[l*dijk]; } } } } } else if (ksh > lsh) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l < dl; l++) { peri[l] = pbuf[l*dijk]; } } } } } else { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (pbuf = buf0 + k*dij + j*di + i, l = 0; l <= k; l++) { peri[l] = pbuf[l*dijk]; } } } } } buf0 += dijkl; eri0 += neri; } } else { eri0 = eri + k0*(k0+1)/2+l0; buf0 = buf; for (icomp = 0; icomp < comp; icomp++) { peri0 = eri0; if (kshp > lshp && ishp > jshp) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l < dl; l++) { peri[l] = 0; } } } } } else if (ish > jsh) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j < dj; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l <= k; l++) { peri[l] = 0; } } } } } else if (ksh > lsh) { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l < dl; l++) { peri[l] = 0; } } } } } else { for (i = 0; i < di; i++, peri0+=nkl*(i0+i)) { for (j = 0; j <= i; j++) { peri = peri0 + nkl*j; for (k = 0; k < dk; k++, peri+=k0+k) { for (l = 0; l <= k; l++) { peri[l] = 0; } } } } } eri0 += neri; } } } } } static int no_prescreen() { return 1; } void GTOnr2e_fill_drv(int (*intor)(), void (*fill)(), int (*fprescreen)(), double *eri, int comp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { if (fprescreen == NULL) { fprescreen = no_prescreen; } const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const int di = GTOmax_shell_dim(ao_loc, shls_slice, 4); const int cache_size = GTOmax_cache_size(intor, shls_slice, 4, atm, natm, bas, nbas, env); #pragma omp parallel { int ij, i, j; double *buf = malloc(sizeof(double) * (di*di*di*di*comp + cache_size)); #pragma omp for nowait schedule(dynamic) for (ij = 0; ij < nish*njsh; ij++) { i = ij / njsh; j = ij % njsh; (*fill)(intor, fprescreen, eri, buf, comp, i, j, shls_slice, ao_loc, cintopt, atm, natm, bas, nbas, env); } free(buf); } }
deconvolution_4x4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void deconv4x4s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*16 + q*16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.data + out.w * i; float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j+3<w; j+=4) { float32x4_t _v = vld1q_f32(r0); // float32x4_t _out00 = vld1q_f32(outptr0 + 0); _out00 = vmlaq_lane_f32(_out00, _v, vget_low_f32(_k0), 0); vst1q_f32(outptr0 + 0, _out00); float32x4_t _out01 = vld1q_f32(outptr0 + 1); _out01 = vmlaq_lane_f32(_out01, _v, vget_low_f32(_k0), 1); vst1q_f32(outptr0 + 1, _out01); float32x4_t _out02 = vld1q_f32(outptr0 + 2); _out02 = vmlaq_lane_f32(_out02, _v, vget_high_f32(_k0), 0); vst1q_f32(outptr0 + 2, _out02); float32x4_t _out03 = vld1q_f32(outptr0 + 3); _out03 = vmlaq_lane_f32(_out03, _v, vget_high_f32(_k0), 1); vst1q_f32(outptr0 + 3, _out03); // float32x4_t _out10 = vld1q_f32(outptr1 + 0); _out10 = vmlaq_lane_f32(_out10, _v, vget_low_f32(_k1), 0); vst1q_f32(outptr1 + 0, _out10); float32x4_t _out11 = vld1q_f32(outptr1 + 1); _out11 = vmlaq_lane_f32(_out11, _v, vget_low_f32(_k1), 1); vst1q_f32(outptr1 + 1, _out11); float32x4_t _out12 = vld1q_f32(outptr1 + 2); _out12 = vmlaq_lane_f32(_out12, _v, vget_high_f32(_k1), 0); vst1q_f32(outptr1 + 2, _out12); float32x4_t _out13 = vld1q_f32(outptr1 + 3); _out13 = vmlaq_lane_f32(_out13, _v, vget_high_f32(_k1), 1); vst1q_f32(outptr1 + 3, _out13); // float32x4_t _out20 = vld1q_f32(outptr2 + 0); _out20 = vmlaq_lane_f32(_out20, _v, vget_low_f32(_k2), 0); vst1q_f32(outptr2 + 0, _out20); float32x4_t _out21 = vld1q_f32(outptr2 + 1); _out21 = vmlaq_lane_f32(_out21, _v, vget_low_f32(_k2), 1); vst1q_f32(outptr2 + 1, _out21); float32x4_t _out22 = vld1q_f32(outptr2 + 2); _out22 = vmlaq_lane_f32(_out22, _v, vget_high_f32(_k2), 0); vst1q_f32(outptr2 + 2, _out22); float32x4_t _out23 = vld1q_f32(outptr2 + 3); _out23 = vmlaq_lane_f32(_out23, _v, vget_high_f32(_k2), 1); vst1q_f32(outptr2 + 3, _out23); // float32x4_t _out30 = vld1q_f32(outptr3 + 0); _out30 = vmlaq_lane_f32(_out30, _v, vget_low_f32(_k3), 0); vst1q_f32(outptr3 + 0, _out30); float32x4_t _out31 = vld1q_f32(outptr3 + 1); _out31 = vmlaq_lane_f32(_out31, _v, vget_low_f32(_k3), 1); vst1q_f32(outptr3 + 1, _out31); float32x4_t _out32 = vld1q_f32(outptr3 + 2); _out32 = vmlaq_lane_f32(_out32, _v, vget_high_f32(_k3), 0); vst1q_f32(outptr3 + 2, _out32); float32x4_t _out33 = vld1q_f32(outptr3 + 3); _out33 = vmlaq_lane_f32(_out33, _v, vget_high_f32(_k3), 1); vst1q_f32(outptr3 + 3, _out33); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } } } static void deconv4x4s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*16 + q*16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.data + out.w * i*2; float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j+3<w; j+=4) { float32x4_t _v = vld1q_f32(r0); // row 0 float32x4x2_t _out0 = vld2q_f32(outptr0); // 0,2,4,6 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_low_f32(_k0), 0); // 1,3,5,7 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_low_f32(_k0), 1); vst2q_f32(outptr0, _out0); _out0 = vld2q_f32(outptr0 + 2); // 2,4,6,8 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_high_f32(_k0), 0); // 3,5,7,9 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_high_f32(_k0), 1); vst2q_f32(outptr0 + 2, _out0); // row 1 float32x4x2_t _out1 = vld2q_f32(outptr1); // 0,2,4,6 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_low_f32(_k1), 0); // 1,3,5,7 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_low_f32(_k1), 1); vst2q_f32(outptr1, _out1); _out1 = vld2q_f32(outptr1 + 2); // 2,4,6,8 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_high_f32(_k1), 0); // 3,5,7,9 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_high_f32(_k1), 1); vst2q_f32(outptr1 + 2, _out1); // row 2 float32x4x2_t _out2 = vld2q_f32(outptr2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_low_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_low_f32(_k2), 1); vst2q_f32(outptr2, _out2); _out2 = vld2q_f32(outptr1 + 2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_high_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_high_f32(_k2), 1); vst2q_f32(outptr2 + 2, _out2); // row 3 float32x4x2_t _out3 = vld2q_f32(outptr3); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_low_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_low_f32(_k3), 1); vst2q_f32(outptr3, _out3); _out3 = vld2q_f32(outptr3 + 2); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_high_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_high_f32(_k3), 1); vst2q_f32(outptr3 + 2, _out3); r0 += 4; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0 += 2; outptr1 += 2; outptr2 += 2; outptr3 += 2; } } } } }
residual_based_bdf_custom_scheme.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_RESIDUAL_BASED_BDF_CUSTOM_SCHEME ) #define KRATOS_RESIDUAL_BASED_BDF_CUSTOM_SCHEME /* System includes */ /* External includes */ /* Project includes */ #include "solving_strategies/schemes/residual_based_bdf_scheme.h" #include "includes/variables.h" #include "includes/kratos_parameters.h" #include "includes/checks.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedBDFCustomScheme * @ingroup KratosCore * @brief BDF integration scheme (for dynamic problems) * @details The second order Backward Differentiation Formula (BDF) method is a two step second order accurate method. * This scheme is a generalization of the only displacement scheme, where any list of variables and its derivatives can be considered instead * Look at the base class for more details * @see ResidualBasedBDFScheme * @author Vicente Mataix Ferrandiz */ template<class TSparseSpace, class TDenseSpace> class ResidualBasedBDFCustomScheme : public ResidualBasedBDFScheme<TSparseSpace, TDenseSpace> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedBDFCustomScheme ); typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef ResidualBasedImplicitTimeScheme<TSparseSpace,TDenseSpace> ImplicitBaseType; typedef ResidualBasedBDFScheme<TSparseSpace,TDenseSpace> BDFBaseType; typedef typename ImplicitBaseType::TDataType TDataType; typedef typename ImplicitBaseType::DofsArrayType DofsArrayType; typedef typename Element::DofsVectorType DofsVectorType; typedef typename ImplicitBaseType::TSystemMatrixType TSystemMatrixType; typedef typename ImplicitBaseType::TSystemVectorType TSystemVectorType; typedef typename ImplicitBaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename ImplicitBaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef typename BaseType::Pointer BaseTypePointer; typedef VectorComponentAdaptor< array_1d< double, 3 > > ComponentType; ///@} ///@name Life Cycle ///@{ /** * @brief Constructor. The BDF method * @param ThisParameters The parameters containing the list of variables to consider * @todo The ideal would be to use directly the dof or the variable itself to identify the type of variable and is derivatives */ explicit ResidualBasedBDFCustomScheme(Parameters ThisParameters) { // Getting default parameters Parameters default_parameters = GetDefaultParameters(); ThisParameters.ValidateAndAssignDefaults(default_parameters); // Now here call the base class constructor BDFBaseType( ThisParameters["integration_order"].GetInt()); // Creating variables list CreateVariablesList(ThisParameters); } /** * @brief Constructor. The BDF method * @param Order The integration order * @param ThisParameters The parameters containing the list of variables to consider * @todo The ideal would be to use directly the dof or the variable itself to identify the type of variable and is derivatives */ explicit ResidualBasedBDFCustomScheme( const std::size_t Order = 2, Parameters ThisParameters = Parameters(R"({})") ) :BDFBaseType(Order) { // Getting default parameters Parameters default_parameters = GetDefaultParameters(); ThisParameters.ValidateAndAssignDefaults(default_parameters); // Creating variables list CreateVariablesList(ThisParameters); } /** Copy Constructor. */ explicit ResidualBasedBDFCustomScheme(ResidualBasedBDFCustomScheme& rOther) :BDFBaseType(rOther) ,mDoubleVariable(rOther.mDoubleVariable) ,mFirstDoubleDerivatives(rOther.mFirstDoubleDerivatives) ,mSecondDoubleDerivatives(rOther.mSecondDoubleDerivatives) ,mArrayVariable(rOther.mArrayVariable) ,mFirstArrayDerivatives(rOther.mFirstArrayDerivatives) ,mSecondArrayDerivatives(rOther.mSecondArrayDerivatives) { } /** * Clone */ BaseTypePointer Clone() override { return BaseTypePointer( new ResidualBasedBDFCustomScheme(*this) ); } /** Destructor. */ ~ResidualBasedBDFCustomScheme () override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief This is the place to initialize the Scheme. * @details This is intended to be called just once when the strategy is initialized * @param rModelPart The model part of the problem to solve */ void Initialize(ModelPart& rModelPart) override { KRATOS_TRY BDFBaseType::Initialize(rModelPart); // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Getting dimension KRATOS_WARNING_IF("ResidualBasedBDFCustomScheme", !r_current_process_info.Has(DOMAIN_SIZE)) << "DOMAIN_SIZE not defined. Please define DOMAIN_SIZE. 3D case will be assumed" << std::endl; const std::size_t domain_size = r_current_process_info.Has(DOMAIN_SIZE) ? r_current_process_info.GetValue(DOMAIN_SIZE) : 3; if (domain_size != mDomainSize) { const std::size_t total_number_of_variables = mArrayVariable.size(); // We remove the third component if (domain_size == 2) { const std::size_t number_variables_added = total_number_of_variables/3; for (std::size_t i = 0; i < number_variables_added; ++i) { mArrayVariable.erase(mArrayVariable.begin() + (2 + 2 * i)); mFirstArrayDerivatives.erase(mArrayVariable.begin() + (2 + 2 * i)); mSecondArrayDerivatives.erase(mArrayVariable.begin() + (2 + 2 * i)); } } else if (domain_size == 3) { // We need to add the third component const std::size_t number_variables_added = total_number_of_variables/2; for (std::size_t i = 0; i < number_variables_added; ++i) { std::string variable_name = (*(mArrayVariable.begin() + 2 * i))->Name(); variable_name.substr(0, variable_name.size() - 2); std::string first_derivative_name = (*(mFirstArrayDerivatives.begin() + 2 * i))->Name(); first_derivative_name.substr(0, first_derivative_name.size() - 2); std::string second_derivative_name = (*(mSecondArrayDerivatives.begin() + 2 * i))->Name(); second_derivative_name.substr(0, second_derivative_name.size() - 2); mArrayVariable.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(variable_name + "_Z")); mFirstArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(first_derivative_name + "_Z")); mSecondArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(second_derivative_name + "_Z")); } } else { KRATOS_ERROR << "DOMAIN_SIZE can onbly be 2 or 3. It is: " << domain_size << std::endl; } mDomainSize = domain_size; } KRATOS_CATCH("") } /** * @brief It initializes time step solution. Only for reasons if the time step solution is restarted * @param rModelPart The model part of the problem to solve * @param rA LHS matrix * @param rDx Incremental update of primary variables * @param rb RHS Vector */ void InitializeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY; BDFBaseType::InitializeSolutionStep(rModelPart, rA, rDx, rb); // Updating time derivatives (nodally for efficiency) const int num_nodes = static_cast<int>( rModelPart.Nodes().size() ); const auto it_node_begin = rModelPart.Nodes().begin(); // Auxiliar fixed value bool fixed = false; #pragma omp parallel for private(fixed) for(int i = 0; i < num_nodes; ++i) { auto it_node = it_node_begin + i; std::size_t counter = 0; for (auto p_var : mDoubleVariable) { fixed = false; // Derivatives const auto& dvar = *mFirstDoubleDerivatives[counter]; const auto& d2var = *mSecondDoubleDerivatives[counter]; if (it_node->HasDofFor(d2var)) { if (it_node->IsFixed(d2var)) { it_node->Fix(*p_var); fixed = true; } } if (it_node->HasDofFor(dvar)) { if (it_node->IsFixed(dvar) && !fixed) { it_node->Fix(*p_var); } } counter++; } counter = 0; for (auto p_var : mArrayVariable) { fixed = false; // Derivatives const auto& dvar = *mFirstArrayDerivatives[counter]; const auto& d2var = *mSecondArrayDerivatives[counter]; if (it_node->HasDofFor(d2var)) { if (it_node->IsFixed(d2var)) { it_node->Fix(*p_var); fixed = true; } } if (it_node->HasDofFor(dvar)) { if (it_node->IsFixed(dvar) && !fixed) { it_node->Fix(*p_var); } } counter++; } } KRATOS_CATCH("ResidualBasedBDFCustomScheme.InitializeSolutionStep"); } /** * @brief Performing the prediction of the solution * @details It predicts the solution for the current step x = xold + vold * Dt * @param rModelPart The model of the problem to solve * @param rDofSet set of all primary variables * @param A LHS matrix * @param Dx Incremental update of primary variables * @param b RHS Vector */ void Predict( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY; // Getting process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Getting delta time const double delta_time = r_current_process_info[DELTA_TIME]; // Updating time derivatives (nodally for efficiency) const int num_nodes = static_cast<int>( rModelPart.Nodes().size() ); // Getting first node iterator const auto it_node_begin = rModelPart.Nodes().begin(); #pragma omp parallel for for(int i = 0; i< num_nodes; ++i) { auto it_node = it_node_begin + i; std::size_t counter = 0; for (auto p_var : mDoubleVariable) { // Derivatives const auto& dvar = *mFirstDoubleDerivatives[counter]; const auto& d2var = *mSecondDoubleDerivatives[counter]; ComputePredictComponent(it_node, *p_var, dvar, d2var, delta_time); counter++; } counter = 0; for (auto p_var : mArrayVariable) { // Derivatives const auto& dvar = *mFirstArrayDerivatives[counter]; const auto& d2var = *mSecondArrayDerivatives[counter]; ComputePredictComponent(it_node, *p_var, dvar, d2var, delta_time); counter++; } // Updating time derivatives UpdateFirstDerivative(it_node); UpdateSecondDerivative(it_node); } KRATOS_CATCH( "" ); } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. * @details Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model of the problem to solve * @return Zero means all ok */ int Check(ModelPart& rModelPart) override { KRATOS_TRY; const int err = BDFBaseType::Check(rModelPart); if(err!=0) return err; // Check for variables keys // Verify that the variables are correctly initialized for ( auto p_var : mDoubleVariable) KRATOS_CHECK_VARIABLE_KEY((*p_var)) for ( auto p_var : mFirstDoubleDerivatives) KRATOS_CHECK_VARIABLE_KEY((*p_var)) for ( auto p_var : mSecondDoubleDerivatives) KRATOS_CHECK_VARIABLE_KEY((*p_var)) for ( auto p_var : mArrayVariable) KRATOS_CHECK_VARIABLE_KEY((*p_var)) for ( auto p_var : mFirstArrayDerivatives) KRATOS_CHECK_VARIABLE_KEY((*p_var)) for ( auto p_var : mSecondArrayDerivatives) KRATOS_CHECK_VARIABLE_KEY((*p_var)) // Check that variables are correctly allocated for(auto& r_node : rModelPart.Nodes()) { for ( auto p_var : mDoubleVariable) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mFirstDoubleDerivatives) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mSecondDoubleDerivatives) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mArrayVariable) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mFirstArrayDerivatives) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mSecondArrayDerivatives) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA((*p_var), r_node) for ( auto p_var : mDoubleVariable) KRATOS_CHECK_DOF_IN_NODE((*p_var), r_node) for ( auto p_var : mArrayVariable) { KRATOS_CHECK_DOF_IN_NODE((*p_var), r_node) } } KRATOS_CATCH( "" ); return 0; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedBDFCustomScheme"; } /// 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 ///@{ std::vector<const Variable<double>*> mDoubleVariable; /// The double variables std::vector<const Variable<double>*> mFirstDoubleDerivatives; /// The first derivative double variable to compute std::vector<const Variable<double>*> mSecondDoubleDerivatives; /// The second derivative double variable to compute std::vector<const VariableComponent<ComponentType>*> mArrayVariable; /// The array variables to compute std::vector<const VariableComponent<ComponentType>*> mFirstArrayDerivatives; /// The first derivative array variable to compute std::vector<const VariableComponent<ComponentType>*> mSecondArrayDerivatives; /// The second derivative array variable to compute ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief Updating first time derivative (velocity) * @param itNode the node interator */ inline void UpdateFirstDerivative(NodesArrayType::iterator itNode) override { // DOUBLES std::size_t counter = 0; for (auto p_var : mDoubleVariable) { double& dotun0 = itNode->FastGetSolutionStepValue(*mFirstDoubleDerivatives[counter]); dotun0 = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(*p_var); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) dotun0 += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(*p_var, i_order); counter++; } // ARRAYS counter = 0; for (auto p_var : mArrayVariable) { double& dotun0 = itNode->FastGetSolutionStepValue(*mFirstArrayDerivatives[counter]); dotun0 = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(*p_var); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) dotun0 += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(*p_var, i_order); counter++; } } /** * @brief Updating second time derivative (acceleration) * @param itNode the node interator */ inline void UpdateSecondDerivative(NodesArrayType::iterator itNode) override { // DOUBLES std::size_t counter = 0; for (auto p_var : mFirstDoubleDerivatives) { double& dot2un0 = itNode->FastGetSolutionStepValue(*mSecondDoubleDerivatives[counter]); dot2un0 = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(*p_var); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) dot2un0 += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(*p_var, i_order); counter++; } // ARRAYS counter = 0; for (auto p_var : mFirstArrayDerivatives) { double& dot2un0 = itNode->FastGetSolutionStepValue(*mSecondArrayDerivatives[counter]); dot2un0 = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(*p_var); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) dot2un0 += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(*p_var, i_order); counter++; } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@{ private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ std::size_t mDomainSize = 3; /// This auxiliar variable is used to store the domain size of the problem ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ /** * @brief This method reduces the code duplication for each components when computing the prediction * @param itNode The node iterator of the node currently being computed * @param rVariable The variable currently being integrated * @param rDerivedVariable The first time derivative of the current variable * @param rDerived2Variable The second time derivative of the current variable * @param DeltaTime The increment of time for the time integration */ template<class TClassVar> void ComputePredictComponent( NodesArrayType::iterator itNode, const TClassVar& rVariable, const TClassVar& rDerivedVariable, const TClassVar& rDerived2Variable, const double DeltaTime ) { // Values const double dot2un1 = itNode->FastGetSolutionStepValue(rDerived2Variable, 1); const double dotun1 = itNode->FastGetSolutionStepValue(rDerivedVariable, 1); const double un1 = itNode->FastGetSolutionStepValue(rVariable, 1); const double dot2un0 = itNode->FastGetSolutionStepValue(rDerived2Variable); double& dotun0 = itNode->FastGetSolutionStepValue(rDerivedVariable); double& un0 = itNode->FastGetSolutionStepValue(rVariable); if (itNode->HasDofFor(rDerived2Variable) && itNode->IsFixed(rDerived2Variable)) { dotun0 = dot2un0; for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) dotun0 -= BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(rDerivedVariable, i_order); dotun0 /= BDFBaseType::mBDF[0]; un0 = dotun0; for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) un0 -= BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(rVariable, i_order); un0 /= BDFBaseType::mBDF[0]; } else if (itNode->HasDofFor(rDerivedVariable) && itNode->IsFixed(rDerivedVariable)) { un0 = dotun0; for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) un0 -= BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(rVariable, i_order); un0 /= BDFBaseType::mBDF[0]; } else if (!itNode->IsFixed(rVariable)) { un0 = un1 + DeltaTime * dotun1 + 0.5 * std::pow(DeltaTime, 2) * dot2un1; } } /** * @brief This method creates the list of variables * @param ThisParameters The configuration parameters */ void CreateVariablesList(Parameters ThisParameters) { const std::size_t n_variables = ThisParameters["variable"].size(); const std::size_t n_first_derivative = ThisParameters["first_derivative"].size(); const std::size_t n_second_derivative = ThisParameters["second_derivative"].size(); // Size check KRATOS_ERROR_IF(n_variables != n_first_derivative) << "Your list of variables is not the same size as the list of first derivatives variables" << std::endl; KRATOS_ERROR_IF(n_variables != n_second_derivative) << "Your list of variables is not the same size as the list of second derivatives variables" << std::endl; // The current dimension mDomainSize = ThisParameters["domain_size"].GetInt(); for (std::size_t p_var = 0; p_var < n_variables; ++p_var){ const std::string& variable_name = ThisParameters["variable"].GetArrayItem(p_var).GetString(); const std::string& first_derivative_name = ThisParameters["first_derivative"].GetArrayItem(p_var).GetString(); const std::string& second_derivative_name = ThisParameters["second_derivative"].GetArrayItem(p_var).GetString(); if(KratosComponents<Variable<double>>::Has(variable_name)){ mDoubleVariable.push_back(&KratosComponents<Variable<double>>::Get(variable_name)); mFirstDoubleDerivatives.push_back(&KratosComponents<Variable<double>>::Get(first_derivative_name)); mSecondDoubleDerivatives.push_back(&KratosComponents<Variable<double>>::Get(second_derivative_name)); } else if (KratosComponents< Variable< array_1d< double, 3> > >::Has(variable_name)) { // Components mArrayVariable.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(variable_name+"_X")); mArrayVariable.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(variable_name+"_Y")); if (mDomainSize == 3) mArrayVariable.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(variable_name+"_Z")); mFirstArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(first_derivative_name+"_X")); mFirstArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(first_derivative_name+"_Y")); if (mDomainSize == 3) mFirstArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(first_derivative_name+"_Z")); mSecondArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(second_derivative_name+"_X")); mSecondArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(second_derivative_name+"_Y")); if (mDomainSize == 3) mSecondArrayDerivatives.push_back(&KratosComponents< VariableComponent<ComponentType>>::Get(second_derivative_name+"_Z")); } else { KRATOS_ERROR << "Only double and vector variables are allowed in the variables list." ; } } } /** * @brief This method returns the defaulr parameters in order to avoid code duplication * @return Returns the default parameters */ Parameters GetDefaultParameters() { Parameters default_parameters = Parameters(R"( { "name" : "ResidualBasedBDFCustomScheme", "domain_size" : 3, "integration_order" : 2, "variable" : ["DISPLACEMENT"], "first_derivative" : ["VELOCITY"], "second_derivative" : ["ACCELERATION"] })" ); return default_parameters; } ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedBDFCustomScheme */ ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_BASED_BDF_CUSTOM_SCHEME defined */
pr35549.c
/* PR middle-end/35549 */ /* { dg-do run } */ #include <omp.h> #include <stdlib.h> int main (void) { int i = 6, n = 0; omp_set_dynamic (0); omp_set_nested (1); #pragma omp parallel shared (i) num_threads (3) { if (omp_get_num_threads () != 3) #pragma omp atomic n += 1; #pragma omp parallel shared (i) num_threads (4) { if (omp_get_num_threads () != 4) #pragma omp atomic n += 1; #pragma omp critical i += 1; } } if (n == 0 && i != 6 + 3 * 4) abort (); return 0; }
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/imperative.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/storage.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_ONEDNN == 1 #include "../operator/nn/dnnl/dnnl_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template <typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i + 1] < 0 || indptr[i + 1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template <typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i + 1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i + 1] - 1 && idx[j] >= idx[j + 1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template <typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i + 1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template <typename xpu> void CheckFormatWrapper(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template <typename xpu> void CheckFormatCSRImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu>* s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template <typename xpu> void CheckFormatRSPImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu>* s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template <typename xpu> void CheckFormatImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template <typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu>* s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template <typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool* has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool* has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } inline std::string attr_value_string(const nnvm::NodeAttrs& attrs, const std::string& attr_name, std::string default_val = "") { if (attrs.dict.find(attr_name) == attrs.dict.end()) { return default_val; } return attrs.dict.at(attr_name); } /*! \brief Seeks an attribute in a node and its subgraphs and invokes a function on each. */ template <typename Fn> inline void attr_foreach(const nnvm::NodeAttrs& attrs, const std::string& attr_name, const Fn& fn) { const auto& found_it = attrs.dict.find(attr_name); if (found_it != attrs.dict.end()) { fn(found_it->second); } for (const auto& subgraph : attrs.subgraphs) { DFSVisit(subgraph->outputs, [&](const nnvm::ObjectPtr& node) { attr_foreach(node->attrs, attr_name, fn); }); } } template <typename ValueType> inline ValueType flag_attr_accumulate(const nnvm::NodeAttrs& attrs, const std::string& attr_name) { static_assert(std::is_integral<ValueType>::value, "ValueType must be an integral type."); ValueType result = 0; attr_foreach(attrs, attr_name, [&](const std::string& attr_value) { std::istringstream ss(attr_value); ValueType temp; ss >> temp; result |= temp; if (ss.fail() || !ss.eof()) { LOG(WARNING) << "Incorrect value of an attribute: " << attr_name << ". Expected an integer, while got: " << attr_value; } }); return result; } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\n WARNING:\n" "Execution of the operator above will fallback to the generic implementation " #if MXNET_USE_ONEDNN == 1 "(not utilizing kernels from oneDNN library) " #endif "with default dense storage type. You are seeing this warning message because " #if MXNET_USE_ONEDNN == 1 "MXNET_ONEDNN_ENABLED flag is set to 0, in which case you can re-enable the default " "execution path by setting MXNET_ONEDNN_ENABLED back to 1, or " #endif "the operator above is unable to process the given ndarrays with specified storage types, " "context and/or parameter, in which case temporary dense ndarrays are generated in order to " "execute the operator. The fallback does not affect the correctness of the programme. Using " "default storage type performance degradation might be observed. \nYou can set environment " "variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to 0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_ONEDNN == 1 if (GetDNNLCacheSize() != -1) common::LogOnce( "MXNET_ONEDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template <typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+ : sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first + len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len / 2, grainsize, comp); ParallelSortHelper(first + len / 2, len - len / 2, grainsize, comp); thr.join(); std::inplace_merge(first, first + len / 2, first + len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024 * 16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort( first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template <typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max() : size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } template <> constexpr size_t MaxIntegerValue<mshadow::bfloat::bf16_t>() { return size_t(2) << 14; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape& shape, const Context& ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape& shape, const Context& ctx, const int dtype, std::vector<NDArray>* vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template <typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { #pragma GCC diagnostic push #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif std::memcpy(dst, src, sizeof(DType) * size); #pragma GCC diagnostic pop } } /*! * \breif parallelize add by OpenMP */ template <typename DType> inline void ParallelAdd(DType* dst, const DType* src, index_t size) { static index_t add_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= add_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } else { for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } void ExecuteMonInputCallback( const nnvm::IndexedGraph& idx, const std::vector<NDArray*>& state_arrays, size_t nid, const std::function<void(const char*, const char*, void*)>& monitor_callback); void ExecuteMonOutputCallback( const nnvm::IndexedGraph& idx, const std::vector<NDArray*>& state_arrays, size_t nid, const std::function<void(const char*, const char*, void*)>& monitor_callback); inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) { // convert negative axes to positive values const int ndim = src.ndim(); mxnet::TShape axes = src; for (int i = 0; i < ndim; ++i) { if (axes[i] < 0) { axes[i] += ndim; } CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")"; } return axes; } inline bool is_float(const int dtype) { return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16; } inline bool is_bfloat(const int dtype) { return dtype == mshadow::kBfloat16; } inline bool is_int(const int dtype) { return dtype == mshadow::kUint8 || dtype == mshadow::kInt8 || dtype == mshadow::kUint16 || dtype == mshadow::kInt16 || dtype == mshadow::kUint32 || dtype == mshadow::kInt32 || dtype == mshadow::kUint64 || dtype == mshadow::kInt64; } inline bool is_signed_int(const int dtype) { return dtype == mshadow::kInt8 || dtype == mshadow::kInt16 || dtype == mshadow::kInt32 || dtype == mshadow::kInt64; } inline bool is_unsigned_int(const int dtype) { return dtype == mshadow::kUint8 || dtype == mshadow::kUint16 || dtype == mshadow::kUint32 || dtype == mshadow::kUint64; } static int bits_of(const int type_flag) { switch (type_flag) { case mshadow::kFloat32: return sizeof(float) * CHAR_BIT; case mshadow::kFloat64: return sizeof(double) * CHAR_BIT; case mshadow::kUint8: return sizeof(uint8_t) * CHAR_BIT; case mshadow::kInt32: return sizeof(int32_t) * CHAR_BIT; case mshadow::kInt8: return sizeof(int8_t) * CHAR_BIT; case mshadow::kInt64: return sizeof(int64_t) * CHAR_BIT; case mshadow::kBool: return sizeof(bool) * CHAR_BIT; case mshadow::kInt16: return sizeof(int16_t) * CHAR_BIT; case mshadow::kUint16: return sizeof(uint16_t) * CHAR_BIT; case mshadow::kUint32: return sizeof(uint32_t) * CHAR_BIT; case mshadow::kUint64: return sizeof(uint64_t) * CHAR_BIT; default: { LOG(FATAL) << "Unknown type_flag=" << type_flag; return -1; } } } inline int type_promotion(const int type1, const int type2) { if (type1 == type2) return type1; if (is_float(type1) && is_float(type2)) { if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) { return mshadow::kFloat64; } if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) { return mshadow::kFloat32; } return mshadow::kFloat16; } else if (is_float(type1) || is_float(type2)) { return is_float(type1) ? type1 : type2; } if (is_signed_int(type1) && is_signed_int(type2)) { if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) { return mshadow::kInt64; } if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) { return mshadow::kInt32; } if (type1 == mshadow::kInt16 || type2 == mshadow::kInt16) { return mshadow::kInt16; } return mshadow::kInt8; } else if (is_unsigned_int(type1) && is_unsigned_int(type2)) { if (type1 == mshadow::kUint64 || type2 == mshadow::kUint64) { return mshadow::kUint64; } if (type1 == mshadow::kUint32 || type2 == mshadow::kUint32) { return mshadow::kUint32; } if (type1 == mshadow::kUint16 || type2 == mshadow::kUint16) { return mshadow::kUint16; } return mshadow::kUint8; } else if (type1 == mshadow::kBool) { return type2; } else if (type2 == mshadow::kBool) { return type1; } else if (is_unsigned_int(type1) || is_unsigned_int(type2)) { if (bits_of(type1) < bits_of(type2)) { if (type1 == mshadow::kInt8 && type2 == mshadow::kUint16) { return mshadow::kInt32; } else if (type1 == mshadow::kInt8 && type2 == mshadow::kUint32) { return mshadow::kInt64; } else if (type1 == mshadow::kInt16 && type2 == mshadow::kUint32) { return mshadow::kInt64; } else if (type2 == mshadow::kUint64) { LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); } else { return type2; } } else if (bits_of(type2) < bits_of(type1)) { if (type2 == mshadow::kInt8 && type1 == mshadow::kUint16) { return mshadow::kInt32; } else if (type2 == mshadow::kInt8 && type1 == mshadow::kUint32) { return mshadow::kInt64; } else if (type2 == mshadow::kInt16 && type1 == mshadow::kUint32) { return mshadow::kInt64; } else if (type1 == mshadow::kUint64) { LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); } else { return type1; } } else { if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) { return mshadow::kInt16; } if (type1 == mshadow::kUint16 || type2 == mshadow::kUint16) { return mshadow::kInt32; } if (type1 == mshadow::kUint32 || type2 == mshadow::kUint32) { return mshadow::kInt64; } } } LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); return -1; } inline const std::string NodeAttrsGetProfilerScope(const nnvm::NodeAttrs& attrs) { // obtain the profiler scope name, if assigned previously std::string profiler_scope = MXNET_STORAGE_DEFAULT_PROFILER_SCOPE_CSTR; const std::unordered_map<std::string, std::string>& node_attrs_dict = attrs.dict; const std::unordered_map<std::string, std::string>::const_iterator profiler_scope_iter = node_attrs_dict.find("__profiler_scope__"); if (profiler_scope_iter != node_attrs_dict.end()) { profiler_scope = profiler_scope_iter->second; } return profiler_scope; } inline int GetDefaultDtype() { return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } inline int GetDefaultDtype(int dtype) { if (dtype != -1) return dtype; return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } struct MShadowTypeInfo { std::string name; int size; int acc_size; MShadowTypeInfo(const std::string name, const int size, const int acc_size) : name(std::move(name)), size(size), acc_size(acc_size) {} MShadowTypeInfo(const std::string name, const int size) : MShadowTypeInfo(name, size, size) {} }; MShadowTypeInfo mshadow_type_info(const int type_flag); inline bool AlignedMemAlloc(void** ptr, size_t size, size_t alignment) { #if _MSC_VER *ptr = _aligned_malloc(size, alignment); if (*ptr == nullptr) return false; #else int res = posix_memalign(ptr, alignment, size); if (res != 0) return false; #endif return true; } inline void AlignedMemFree(void* ptr) { #if _MSC_VER _aligned_free(ptr); #else free(ptr); #endif } inline index_t div_round(const index_t a, const index_t b) { return (a + b - 1) / b; } inline bool IsPower2(size_t N) { return ((N & (N - 1)) == 0) && N != 0; } inline size_t RoundToPower2(size_t N) { size_t ret = 1; size_t copyN = N; while (N >= 2) { ret *= 2; N /= 2; } if (ret < copyN) { ret *= 2; } return ret; } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
ab-totient-omp-15.c
// Distributed and parallel technologies, Andrew Beveridge, 03/03/2014 // To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c // To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end #include <stdio.h> #include <omp.h> /* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1). If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */ long getTotient (long number) { long result = number; // Check every prime number below the square root for divisibility if(number % 2 == 0){ result -= result / 2; do number /= 2; while(number %2 == 0); } // Primitive replacement for a list of primes, looping through every odd number long prime; for(prime = 3; prime * prime <= number; prime += 2){ if(number %prime == 0){ result -= result / prime; do number /= prime; while(number % prime == 0); } } // Last common factor if(number > 1) result -= result / number; // Return the result. return result; } // Main method. int main(int argc, char ** argv) { // Load inputs long lower, upper; sscanf(argv[1], "%ld", &lower); sscanf(argv[2], "%ld", &upper); int i; long result = 0.0; // We know the answer if it's 1; no need to execute the function if(lower == 1) { result = 1.0; lower = 2; } #pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(15) // Sum all totients in the specified range for (i = lower; i <= upper; i++) { result = result + getTotient(i); } // Print the result printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result); // A-OK! return 0; }
mdp_vec.h
#pragma once #include "mdp.h" #include <omp.h> #include <unistd.h> /* Vectorized version of the MDPEnv_cpp env which uses OpenMP to run on multiple CPUs */ template <typename E, typename S = typename E::state_type, typename A = typename E::action_type, typename O = typename E::obs_type, typename I = typename E::info_type, typename Co = typename E::config_type> class MDPVectorEnv_cpp { public: /* Attributes */ using state_type = S; using action_type = A; using obs_type = O; using info_type = I; using config_type = Co; int num_envs, num_threads; std::vector<E> envs; /* Methods */ /* Class constructor INPUT: - num_envs = number of parallel environments - num_threads = number of openmp threads - config = configuration dictionary for each env */ MDPVectorEnv_cpp(const int num_envs, const int num_threads, const std::map<std::string,Co>& config) : num_envs{num_envs}, num_threads{num_threads}, envs(num_envs, E(config)) { // Set number of omp threads omp_set_num_threads(num_threads); //Seed the environments int i; #pragma omp parallel for for (i = 0; i < num_envs; i++) envs[i].seed(envs[i].prng_seed + i + 1); } /* Reset the environments OUTPUT: - obs_vec = vector of observations after reset */ std::vector<std::vector<O>> vector_reset() { std::vector<std::vector<O>> obs_vec(num_envs); int i; #pragma omp parallel for shared(obs_vec) for (i = 0; i < num_envs; i++) obs_vec[i] = envs[i].reset(); return obs_vec; } /* Reset a specific environment INPUT: - index = environment index OUTPUT: - obs = observation after reset */ const std::vector<O> reset_at(const int index) { return envs[index].reset(); } /* Step the environments INPUT: - actions = vector of actions OUTPUT: - observations, rewards, dones, infos */ std::tuple<std::vector<std::vector<O>>, std::vector<double>, std::vector<bool>, std::vector<std::map<std::string, std::map<std::string,std::vector<I>>>>> vector_step(const std::vector<std::vector<A>>& actions) { std::tuple<std::vector<std::vector<O>>, std::vector<double>, std::vector<bool>, std::vector<std::map<std::string, std::map<std::string,std::vector<I>>>>> all_data = std::make_tuple(std::vector<std::vector<O>>(num_envs), std::vector<double>(num_envs), std::vector<bool>(num_envs), std::vector<std::map<std::string, std::map<std::string,std::vector<I>>>>(num_envs) ); int i; #pragma omp parallel for shared(all_data) for (i = 0; i < num_envs; i++) { const std::tuple<std::vector<O>, double, bool, std::map<std::string, std::map<std::string, std::vector<I>>>> data_batch = envs[i].step(actions[i]); std::get<0>(all_data)[i] = std::get<0>(data_batch); std::get<1>(all_data)[i] = std::get<1>(data_batch); std::get<2>(all_data)[i] = std::get<2>(data_batch); std::get<3>(all_data)[i] = std::get<3>(data_batch); } return all_data; } /* Get the environments OUTPUT: - envs = vector of environments */ std::vector<E> get_sub_environments() { return envs; } };
pngquant.c
/* pngquant.c - quantize the colors in an alphamap down to a specified number ** ** Copyright (C) 1989, 1991 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** - - - - ** ** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. ** © 2009-2015 by Kornel Lesiński. ** ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** */ #define PNGQUANT_VERSION LIQ_VERSION_STRING " (April 2017)" #define PNGQUANT_USAGE "\ usage: pngquant [options] [ncolors] -- pngfile [pngfile ...]\n\ pngquant [options] [ncolors] - >stdout <stdin\n\n\ options:\n\ --force overwrite existing output files (synonym: -f)\n\ --skip-if-larger only save converted files if they're smaller than original\n\ --output file destination file path to use instead of --ext (synonym: -o)\n\ --ext new.png set custom suffix/extension for output filenames\n\ --quality min-max don't save below min, use fewer colors below max (0-100)\n\ --speed N speed/quality trade-off. 1=slow, 3=default, 11=fast & rough\n\ --nofs disable Floyd-Steinberg dithering\n\ --posterize N output lower-precision color (e.g. for ARGB4444 output)\n\ --strip remove optional metadata (default on Mac)\n\ --verbose print status messages (synonym: -v)\n\ \n\ Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette.\n\ The output filename is the same as the input name except that\n\ it ends in \"-fs8.png\", \"-or8.png\" or your custom extension (unless the\n\ input is stdin, in which case the quantized image will go to stdout).\n\ If you pass the special output path \"-\" and a single input file, that file\n\ will be processed and the quantized image will go to stdout.\n\ The default behavior if the output file exists is to skip the conversion;\n\ use --force to overwrite. See man page for full list of options.\n" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <getopt.h> #include <unistd.h> #include <math.h> extern char *optarg; extern int optind, opterr; #if defined(WIN32) || defined(__WIN32__) # include <fcntl.h> /* O_BINARY */ # include <io.h> /* setmode() */ #endif #ifdef _OPENMP #include <omp.h> #else #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #endif #include "rwpng.h" /* typedefs, common macros, public prototypes */ #include "lib/libimagequant.h" struct pngquant_options { liq_attr *liq; liq_image *fixed_palette_image; liq_log_callback_function *log_callback; void *log_callback_user_info; float floyd; bool using_stdin, using_stdout, force, fast_compression, ie_mode, min_quality_limit, skip_if_larger, strip, verbose; }; static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform tag, png8_image *output_image); static void set_palette(liq_result *result, png8_image *output_image); static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose); static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options); static char *add_filename_extension(const char *filename, const char *newext); static bool file_exists(const char *outname); static void verbose_printf(struct pngquant_options *context, const char *fmt, ...) { if (context->log_callback) { va_list va; va_start(va, fmt); int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0 va_end(va); char buf[required_space]; va_start(va, fmt); vsnprintf(buf, required_space, fmt, va); va_end(va); context->log_callback(context->liq, buf, context->log_callback_user_info); } } static void log_callback(const liq_attr *attr, const char *msg, void* user_info) { fprintf(stderr, "%s\n", msg); } #ifdef _OPENMP #define LOG_BUFFER_SIZE 1300 struct buffered_log { int buf_used; char buf[LOG_BUFFER_SIZE]; }; static void log_callback_buferred_flush(const liq_attr *attr, void *context) { struct buffered_log *log = context; if (log->buf_used) { fwrite(log->buf, 1, log->buf_used, stderr); fflush(stderr); log->buf_used = 0; } } static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context) { struct buffered_log *log = context; int len = strlen(msg); if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2; if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log); memcpy(&log->buf[log->buf_used], msg, len); log->buf_used += len+1; log->buf[log->buf_used-1] = '\n'; log->buf[log->buf_used] = '\0'; } #endif static void print_full_version(FILE *fd) { fprintf(fd, "pngquant, %s, by Kornel Lesinski, Greg Roelofs.\n" #ifndef NDEBUG " WARNING: this is a DEBUG (slow) version.\n" /* NDEBUG disables assert() */ #endif #if !USE_SSE && (defined(__SSE__) || defined(__amd64__) || defined(__X86_64__) || defined(__i386__)) " SSE acceleration disabled.\n" #endif #if _OPENMP " Compiled with OpenMP (multicore support).\n" #endif , PNGQUANT_VERSION); rwpng_version_info(fd); fputs("\n", fd); } static void print_usage(FILE *fd) { fputs(PNGQUANT_USAGE, fd); } /** * N = automatic quality, uses limit unless force is set (N-N or 0-N) * -N = no better than N (same as 0-N) * N-M = no worse than N, no better than M * N- = no worse than N, perfect if possible (same as N-100) * * where N,M are numbers between 0 (lousy) and 100 (perfect) */ static bool parse_quality(const char *quality, liq_attr *options, bool *min_quality_limit) { long limit, target; const char *str = quality; char *end; long t1 = strtol(str, &end, 10); if (str == end) return false; str = end; if ('\0' == end[0] && t1 < 0) { // quality="-%d" target = -t1; limit = 0; } else if ('\0' == end[0]) { // quality="%d" target = t1; limit = t1*9/10; } else if ('-' == end[0] && '\0' == end[1]) { // quality="%d-" target = 100; limit = t1; } else { // quality="%d-%d" long t2 = strtol(str, &end, 10); if (str == end || t2 > 0) return false; target = -t2; limit = t1; } *min_quality_limit = (limit > 0); return LIQ_OK == liq_set_quality(options, limit, target); } static const struct {const char *old; const char *newopt;} obsolete_options[] = { {"-fs","--floyd=1"}, {"-nofs", "--ordered"}, {"-floyd", "--floyd=1"}, {"-nofloyd", "--ordered"}, {"-ordered", "--ordered"}, {"-force", "--force"}, {"-noforce", "--no-force"}, {"-verbose", "--verbose"}, {"-quiet", "--quiet"}, {"-noverbose", "--quiet"}, {"-noquiet", "--verbose"}, {"-help", "--help"}, {"-version", "--version"}, {"-ext", "--ext"}, {"-speed", "--speed"}, }; static void fix_obsolete_options(const unsigned int argc, char *argv[]) { for(unsigned int argn=1; argn < argc; argn++) { if ('-' != argv[argn][0]) continue; if ('-' == argv[argn][1]) break; // stop on first --option or -- for(unsigned int i=0; i < sizeof(obsolete_options)/sizeof(obsolete_options[0]); i++) { if (0 == strcmp(obsolete_options[i].old, argv[argn])) { fprintf(stderr, " warning: option '%s' has been replaced with '%s'.\n", obsolete_options[i].old, obsolete_options[i].newopt); argv[argn] = (char*)obsolete_options[i].newopt; } } } } enum {arg_floyd=1, arg_ordered, arg_ext, arg_no_force, arg_iebug, arg_transbug, arg_map, arg_posterize, arg_skip_larger, arg_strip}; static const struct option long_options[] = { {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"force", no_argument, NULL, 'f'}, {"no-force", no_argument, NULL, arg_no_force}, {"floyd", optional_argument, NULL, arg_floyd}, {"ordered", no_argument, NULL, arg_ordered}, {"nofs", no_argument, NULL, arg_ordered}, {"iebug", no_argument, NULL, arg_iebug}, {"transbug", no_argument, NULL, arg_transbug}, {"ext", required_argument, NULL, arg_ext}, {"skip-if-larger", no_argument, NULL, arg_skip_larger}, {"output", required_argument, NULL, 'o'}, {"speed", required_argument, NULL, 's'}, {"quality", required_argument, NULL, 'Q'}, {"posterize", required_argument, NULL, arg_posterize}, {"strip", no_argument, NULL, arg_strip}, {"map", required_argument, NULL, arg_map}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0}, }; pngquant_error pngquant_file(const char *filename, const char *outname, struct pngquant_options *options); int main(int argc, char *argv[]) { struct pngquant_options options = { .floyd = 1.f, // floyd-steinberg dithering .strip = false, }; options.liq = liq_attr_create(); if (!options.liq) { fputs("SSE-capable CPU is required for this build.\n", stderr); return WRONG_ARCHITECTURE; } unsigned int error_count=0, skipped_count=0, file_count=0; pngquant_error latest_error=SUCCESS; const char *newext = NULL, *output_file_path = NULL; fix_obsolete_options(argc, argv); int opt; do { opt = getopt_long(argc, argv, "Vvqfhs:Q:o:", long_options, NULL); switch (opt) { case 'v': options.verbose = true; break; case 'q': options.verbose = false; break; case arg_floyd: options.floyd = optarg ? atof(optarg) : 1.f; if (options.floyd < 0 || options.floyd > 1.f) { fputs("--floyd argument must be in 0..1 range\n", stderr); return INVALID_ARGUMENT; } break; case arg_ordered: options.floyd = 0; break; case 'f': options.force = true; break; case arg_no_force: options.force = false; break; case arg_ext: newext = optarg; break; case 'o': if (output_file_path) { fputs("--output option can be used only once\n", stderr); return INVALID_ARGUMENT; } if (strcmp(optarg, "-") == 0) { options.using_stdout = true; break; } output_file_path = optarg; break; case arg_iebug: // opacities above 238 will be rounded up to 255, because IE6 truncates <255 to 0. liq_set_min_opacity(options.liq, 238); fputs(" warning: the workaround for IE6 is deprecated\n", stderr); break; case arg_transbug: liq_set_last_index_transparent(options.liq, true); break; case arg_skip_larger: options.skip_if_larger = true; break; case 's': { int speed = atoi(optarg); if (speed >= 10) { options.fast_compression = true; } if (speed == 11) { options.floyd = 0; speed = 10; } if (LIQ_OK != liq_set_speed(options.liq, speed)) { fputs("Speed should be between 1 (slow) and 11 (fast).\n", stderr); return INVALID_ARGUMENT; } } break; case 'Q': if (!parse_quality(optarg, options.liq, &options.min_quality_limit)) { fputs("Quality should be in format min-max where min and max are numbers in range 0-100.\n", stderr); return INVALID_ARGUMENT; } break; case arg_posterize: if (LIQ_OK != liq_set_min_posterization(options.liq, atoi(optarg))) { fputs("Posterization should be number of bits in range 0-4.\n", stderr); return INVALID_ARGUMENT; } break; case arg_strip: options.strip = true; break; case arg_map: { png24_image tmp = {}; if (SUCCESS != read_image(options.liq, optarg, false, &tmp, &options.fixed_palette_image, true, true, false)) { fprintf(stderr, " error: unable to load %s", optarg); return INVALID_ARGUMENT; } liq_result *tmp_quantize = liq_quantize_image(options.liq, options.fixed_palette_image); const liq_palette *pal = liq_get_palette(tmp_quantize); if (!pal) { fprintf(stderr, " error: unable to read colors from %s", optarg); return INVALID_ARGUMENT; } for(unsigned int i=0; i < pal->count; i++) { liq_image_add_fixed_color(options.fixed_palette_image, pal->entries[i]); } liq_result_destroy(tmp_quantize); } break; case 'h': print_full_version(stdout); print_usage(stdout); return SUCCESS; case 'V': puts(PNGQUANT_VERSION); return SUCCESS; case -1: break; default: return INVALID_ARGUMENT; } } while (opt != -1); int argn = optind; if (argn >= argc) { if (argn > 1) { fputs("No input files specified.\n", stderr); } else { print_full_version(stderr); } print_usage(stderr); return MISSING_ARGUMENT; } if (options.verbose) { liq_set_log_callback(options.liq, log_callback, NULL); options.log_callback = log_callback; } char *colors_end; unsigned long colors = strtoul(argv[argn], &colors_end, 10); if (colors_end != argv[argn] && '\0' == colors_end[0]) { if (LIQ_OK != liq_set_max_colors(options.liq, colors)) { fputs("Number of colors must be between 2 and 256.\n", stderr); return INVALID_ARGUMENT; } argn++; } if (newext && output_file_path) { fputs("--ext and --output options can't be used at the same time\n", stderr); return INVALID_ARGUMENT; } // new filename extension depends on options used. Typically basename-fs8.png if (newext == NULL) { newext = options.floyd > 0 ? "-ie-fs8.png" : "-ie-or8.png"; if (!options.ie_mode) { newext += 3; /* skip "-ie" */ } } if (argn == argc || (argn == argc-1 && 0==strcmp(argv[argn],"-"))) { options.using_stdin = true; options.using_stdout = !output_file_path; argn = argc-1; } const int num_files = argc-argn; if (output_file_path && num_files != 1) { fputs("Only one input file is allowed when --output is used\n", stderr); return INVALID_ARGUMENT; } if (options.using_stdout && !options.using_stdin && num_files != 1) { fputs("Only one input file is allowed when using the special output path \"-\" to write to stdout\n", stderr); return INVALID_ARGUMENT; } #ifdef _OPENMP // if there's a lot of files, coarse parallelism can be used if (num_files > 2*omp_get_max_threads()) { omp_set_nested(0); omp_set_dynamic(1); } else { omp_set_nested(1); } #endif #pragma omp parallel for \ schedule(static, 1) reduction(+:skipped_count) reduction(+:error_count) reduction(+:file_count) shared(latest_error) for(int i=0; i < num_files; i++) { struct pngquant_options opts = options; opts.liq = liq_attr_copy(options.liq); const char *filename = opts.using_stdin ? "stdin" : argv[argn+i]; #ifdef _OPENMP struct buffered_log buf = {}; if (opts.log_callback && omp_get_num_threads() > 1 && num_files > 1) { liq_set_log_callback(opts.liq, log_callback_buferred, &buf); liq_set_log_flush_callback(opts.liq, log_callback_buferred_flush, &buf); opts.log_callback = log_callback_buferred; opts.log_callback_user_info = &buf; } #endif pngquant_error retval = SUCCESS; const char *outname = output_file_path; char *outname_free = NULL; if (!opts.using_stdout) { if (!outname) { outname = outname_free = add_filename_extension(filename, newext); } if (!opts.force && file_exists(outname)) { fprintf(stderr, " error: '%s' exists; not overwriting\n", outname); retval = NOT_OVERWRITING_ERROR; } } if (SUCCESS == retval) { retval = pngquant_file(filename, outname, &opts); } free(outname_free); liq_attr_destroy(opts.liq); if (retval) { #pragma omp critical { latest_error = retval; } if (retval == TOO_LOW_QUALITY || retval == TOO_LARGE_FILE) { skipped_count++; } else { error_count++; } } ++file_count; } if (error_count) { verbose_printf(&options, "There were errors quantizing %d file%s out of a total of %d file%s.", error_count, (error_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (skipped_count) { verbose_printf(&options, "Skipped %d file%s out of a total of %d file%s.", skipped_count, (skipped_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (!skipped_count && !error_count) { verbose_printf(&options, "Quantized %d image%s.", file_count, (file_count == 1)? "" : "s"); } if (options.fixed_palette_image) liq_image_destroy(options.fixed_palette_image); liq_attr_destroy(options.liq); return latest_error; } pngquant_error pngquant_file(const char *filename, const char *outname, struct pngquant_options *options) { pngquant_error retval = SUCCESS; verbose_printf(options, "%s:", filename); liq_image *input_image = NULL; png24_image input_image_rwpng = {}; bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be output to stdout if (SUCCESS == retval) { retval = read_image(options->liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->strip, options->verbose); } int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap png8_image output_image = {}; if (SUCCESS == retval) { verbose_printf(options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL); if (RWPNG_ICCP == input_image_rwpng.input_color) { verbose_printf(options, " used embedded ICC profile to transform image to sRGB colorspace"); } else if (RWPNG_GAMA_CHRM == input_image_rwpng.input_color) { verbose_printf(options, " used gAMA and cHRM chunks to transform image to sRGB colorspace"); } else if (RWPNG_ICCP_WARN_GRAY == input_image_rwpng.input_color) { verbose_printf(options, " warning: ignored ICC profile in GRAY colorspace"); } else if (RWPNG_COCOA == input_image_rwpng.input_color) { // No comment } else if (RWPNG_SRGB == input_image_rwpng.input_color) { verbose_printf(options, " passing sRGB tag from the input"); } else if (input_image_rwpng.gamma != 0.45455) { verbose_printf(options, " converted image from gamma %2.1f to gamma 2.2", 1.0/input_image_rwpng.gamma); } // when using image as source of a fixed palette the palette is extracted using regular quantization liq_result *remap; liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, options->liq, &remap); if (LIQ_OK == remap_error) { // fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2 // NB: can't change gamma here, because output_color is allowed to be an sRGB tag liq_set_output_gamma(remap, 0.45455); liq_set_dithering_level(remap, options->floyd); retval = prepare_output_image(remap, input_image, input_image_rwpng.output_color, &output_image); if (SUCCESS == retval) { if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) { retval = OUT_OF_MEMORY_ERROR; } set_palette(remap, &output_image); double palette_error = liq_get_quantization_error(remap); if (palette_error >= 0) { quality_percent = liq_get_quantization_quality(remap); verbose_printf(options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent); } } liq_result_destroy(remap); } else if (LIQ_QUALITY_TOO_LOW == remap_error) { retval = TOO_LOW_QUALITY; } else { retval = INVALID_ARGUMENT; // dunno } } if (SUCCESS == retval) { if (options->skip_if_larger) { // this is very rough approximation, but generally avoid losing more quality than is gained in file size. // Quality is raised to 1.5, because even greater savings are needed to justify big quality loss. // but >50% savings are considered always worthwile in order to allow low quality conversions to work at all const double quality = quality_percent/100.0; const double expected_reduced_size = pow(quality, 1.5); output_image.maximum_file_size = (input_image_rwpng.file_size-1) * (expected_reduced_size < 0.5 ? 0.5 : expected_reduced_size); } output_image.fast_compression = options->fast_compression; output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL; retval = write_image(&output_image, NULL, outname, options); if (TOO_LARGE_FILE == retval) { verbose_printf(options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL); } if (SUCCESS == retval && output_image.metadata_size > 0) { verbose_printf(options, " copied %dKB of additional PNG metadata", (int)(output_image.metadata_size+999)/1000); } } if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) { // when outputting to stdout it'd be nasty to create 0-byte file // so if quality is too low, output 24-bit original pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options); if (write_retval) { retval = write_retval; } } if (input_image) liq_image_destroy(input_image); rwpng_free_image24(&input_image_rwpng); rwpng_free_image8(&output_image); return retval; } static void set_palette(liq_result *result, png8_image *output_image) { const liq_palette *palette = liq_get_palette(result); output_image->num_palette = palette->count; for(unsigned int i=0; i < palette->count; i++) { const liq_color px = palette->entries[i]; output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a}; } } static bool file_exists(const char *outname) { FILE *outfile = fopen(outname, "rb"); if ((outfile ) != NULL) { fclose(outfile); return true; } return false; } /* build the output filename from the input name by inserting "-fs8" or * "-or8" before the ".png" extension (or by appending that plus ".png" if * there isn't any extension), then make sure it doesn't exist already */ static char *add_filename_extension(const char *filename, const char *newext) { size_t x = strlen(filename); char* outname = malloc(x+4+strlen(newext)+1); if (!outname) return NULL; strncpy(outname, filename, x); if (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0) { strcpy(outname+x-4, newext); } else { strcpy(outname+x, newext); } return outname; } static char *temp_filename(const char *basename) { size_t x = strlen(basename); char *outname = malloc(x+1+4); if (!outname) return NULL; strcpy(outname, basename); strcpy(outname+x, ".tmp"); return outname; } static void set_binary_mode(FILE *fp) { #if defined(WIN32) || defined(__WIN32__) setmode(fp == stdout ? 1 : 0, O_BINARY); #endif } static const char *filename_part(const char *path) { const char *outfilename = strrchr(path, '/'); if (outfilename) { return outfilename+1; } else { return path; } } static bool replace_file(const char *from, const char *to, const bool force) { #if defined(WIN32) || defined(__WIN32__) if (force) { // On Windows rename doesn't replace unlink(to); } #endif return (0 == rename(from, to)); } static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options) { FILE *outfile; char *tempname = NULL; if (options->using_stdout) { set_binary_mode(stdout); outfile = stdout; if (output_image) { verbose_printf(options, " writing %d-color image to stdout", output_image->num_palette); } else { verbose_printf(options, " writing truecolor image to stdout"); } } else { tempname = temp_filename(outname); if (!tempname) return OUT_OF_MEMORY_ERROR; if ((outfile = fopen(tempname, "wb")) == NULL) { fprintf(stderr, " error: cannot open '%s' for writing\n", tempname); free(tempname); return CANT_WRITE_ERROR; } if (output_image) { verbose_printf(options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname)); } else { verbose_printf(options, " writing truecolor image as %s", filename_part(outname)); } } pngquant_error retval; #pragma omp critical (libpng) { if (output_image) { retval = rwpng_write_image8(outfile, output_image); } else { retval = rwpng_write_image24(outfile, output_image24); } } if (!options->using_stdout) { fclose(outfile); if (SUCCESS == retval) { // Image has been written to a temporary file and then moved over destination. // This makes replacement atomic and avoids damaging destination file on write error. if (!replace_file(tempname, outname, options->force)) { retval = CANT_WRITE_ERROR; } } if (retval) { unlink(tempname); } } free(tempname); if (retval && retval != TOO_LARGE_FILE) { fprintf(stderr, " error: failed writing image to %s (%d)\n", options->using_stdout ? "stdout" : outname, retval); } return retval; } static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose) { FILE *infile; if (using_stdin) { set_binary_mode(stdin); infile = stdin; } else if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, " error: cannot open %s for reading\n", filename); return READ_ERROR; } pngquant_error retval; #pragma omp critical (libpng) { retval = rwpng_read_image24(infile, input_image_p, strip, verbose); } if (!using_stdin) { fclose(infile); } if (retval) { fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename)); return retval; } *liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma); if (!*liq_image_p) { return OUT_OF_MEMORY_ERROR; } if (!keep_input_pixels) { if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) { return OUT_OF_MEMORY_ERROR; } input_image_p->row_pointers = NULL; input_image_p->rgba_data = NULL; } return SUCCESS; } static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform output_color, png8_image *output_image) { output_image->width = liq_image_get_width(input_image); output_image->height = liq_image_get_height(input_image); output_image->gamma = liq_get_output_gamma(result); output_image->output_color = output_color; /* ** Step 3.7 [GRR]: allocate memory for the entire indexed image */ output_image->indexed_data = malloc(output_image->height * output_image->width); output_image->row_pointers = malloc(output_image->height * sizeof(output_image->row_pointers[0])); if (!output_image->indexed_data || !output_image->row_pointers) { return OUT_OF_MEMORY_ERROR; } for(size_t row = 0; row < output_image->height; row++) { output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width; } const liq_palette *palette = liq_get_palette(result); // tRNS, etc. output_image->num_palette = palette->count; return SUCCESS; }
GB_unaryop__ainv_uint64_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_uint64_fp64 // op(A') function: GB_tran__ainv_uint64_fp64 // C type: uint64_t // A type: double // cast: uint64_t cij ; GB_CAST_UNSIGNED(cij,aij,64) // unaryop: cij = -aij #define GB_ATYPE \ double #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ uint64_t z ; GB_CAST_UNSIGNED(z,x,64) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT64 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint64_fp64 ( uint64_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_uint64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__isgt_uint16.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__isgt_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__isgt_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__isgt_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__isgt_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_uint16) // A*D function (colscale): GB (_AxD__isgt_uint16) // D*A function (rowscale): GB (_DxB__isgt_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__isgt_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__isgt_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_uint16) // C=scalar+B GB (_bind1st__isgt_uint16) // C=scalar+B' GB (_bind1st_tran__isgt_uint16) // C=A+scalar GB (_bind2nd__isgt_uint16) // C=A'+scalar GB (_bind2nd_tran__isgt_uint16) // C type: uint16_t // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = (aij > bij) #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 = (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_ISGT || GxB_NO_UINT16 || GxB_NO_ISGT_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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__isgt_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] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isgt_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] = (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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB (_bind1st_tran__isgt_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] = (aij > y) ; \ } GrB_Info GB (_bind2nd_tran__isgt_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
QuadtreePolarEuclid.h
/* * Quadtree.h * * Created on: 21.05.2014 * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu) */ #ifndef QUADTREEPOLAREUCLID_H_ #define QUADTREEPOLAREUCLID_H_ #include <vector> #include <memory> #include <cmath> #include <omp.h> #include <functional> #include "QuadNodePolarEuclid.h" namespace NetworKit { template <class T> class QuadtreePolarEuclid { friend class QuadTreePolarEuclidGTest; public: QuadtreePolarEuclid() { root = QuadNodePolarEuclid<T>(); this->maxRadius = 1; } /** * @param maxR Radius of the managed area. Must be smaller than 1. * @param theoreticalSplit If true, split cells to get the same area in each child cell. Default is false * @param alpha dispersion Parameter of the point distribution. Only has an effect if theoretical split is true * @param capacity How many points can inhabit a leaf cell before it is split up? * */ QuadtreePolarEuclid(double maxR,bool theoreticalSplit=false, double alpha=1, count capacity=1000, double balance = 0.5) { root = QuadNodePolarEuclid<T>(0, 0, 2*PI, maxR, capacity, 0,theoreticalSplit,alpha,balance); this->maxRadius = maxR; } QuadtreePolarEuclid(const vector<double> &angles, const vector<double> &radii, const vector<T> &content, bool theoreticalSplit=false, count capacity=1000, double balance = 0.5) { const count n = angles.size(); assert(angles.size() == radii.size()); assert(radii.size() == content.size()); maxRadius = 0; for (double radius : radii) { if (radius > maxRadius) maxRadius = radius; } maxRadius = std::nextafter(maxRadius, std::numeric_limits<double>::max()); root = QuadNodePolarEuclid<T>(0, 0, 2*PI, maxRadius, capacity, theoreticalSplit,balance); for (index i = 0; i < n; i++) { assert(content[i] < n); root.addContent(content[i], angles[i], radii[i]); } } /** * @param newcomer content to be added at point x * @param angle angular coordinate of x * @param R radial coordinate of x */ void addContent(T newcomer, double angle, double r) { root.addContent(newcomer, angle, r); } /** * @param newcomer content to be removed at point x * @param angle angular coordinate of x * @param R radial coordinate of x */ bool removeContent(T toRemove, double angle, double r) { return root.removeContent(toRemove, angle, r); } /** * Get all elements, regardless of position * * @return vector<T> of elements */ vector<T> getElements() const { return root.getElements(); } void extractCoordinates(vector<double> &anglesContainer, vector<double> &radiiContainer) const { root.getCoordinates(anglesContainer, radiiContainer); } void getElementsInEuclideanCircle(const Point2D<double> circleCenter, const double radius, vector<T> &circleDenizens) const { root.getElementsInEuclideanCircle(circleCenter, radius, false, circleDenizens); } count getElementsProbabilistically(Point2D<double> euQuery, std::function<double(double)> prob, vector<T> &circleDenizens) { return root.getElementsProbabilistically(euQuery, prob, false, circleDenizens); } count getElementsProbabilistically(Point2D<double> euQuery, std::function<double(double)> prob, bool suppressLeft, vector<T> &circleDenizens) { return root.getElementsProbabilistically(euQuery, prob, suppressLeft, circleDenizens); } void recount() { root.recount(); } count size() const { return root.size(); } count height() const { return root.height(); } count countLeaves() const { return root.countLeaves(); } index indexSubtree(index nextID) { return root.indexSubtree(nextID); } index getCellID(double phi, double r) const { return root.getCellID(phi, r); } double getMaxRadius() const { return maxRadius; } void reindex() { #pragma omp parallel { #pragma omp single nowait { root.reindex(0); } } } /** * trims the vectors used to hold the content in the leaf cells. Reduces memory usage, makes changes slower */ void trim() { root.trim(); } private: QuadNodePolarEuclid<T> root; double maxRadius; }; } #endif /* QUADTREE_H_ */
hybrid.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #ifdef USE_MPI #include <mpi.h> #endif /* USE_MPI */ #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #include <sim_api.h> int read_slab_info() { /* This should read info from a file or something, but we fake it */ return 16; } double process_slab(int snum) { int i, j; double x; for (i = 0; i < 20; i++) for (j = 0; j < 100; j++) x += sqrt((i-j)*(i-j) / (sqrt((i*i) + (j*j)) + 1)); return x; } void exit_on_error(char *message) { fprintf(stderr, "%s\n", message); #ifdef USE_MPI MPI_Finalize(); #endif exit(1); } int main(int argc, char **argv) { int i, j, p, me, nprocs, num_threads, num_slabs, spp; int *my_slabs, *count; double x, sum; #ifdef _OPENMP int np; #endif /* _OPENMP */ #ifdef USE_MPI int namelen; char processor_name[MPI_MAX_PROCESSOR_NAME]; #endif /* USE_MPI */ #ifdef USE_MPI MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &me); MPI_Get_processor_name(processor_name, &namelen); #else /* USE_MPI */ nprocs = 1; me = 0; #endif /* USE_MPI */ SimRoiStart(); #ifdef _OPENMP num_threads = omp_get_max_threads(); #else /* _OPENMP */ num_threads = 1; #endif /* _OPENMP */ printf("Process %d of %d", me, nprocs); #ifdef USE_MPI printf(" running on %s", processor_name); #endif /* USE_MPI */ #ifdef _OPENMP printf(" using OpenMP with %d threads", num_threads); #endif /* _OPENMP */ printf("\n"); /* Master process reads slab data */ if (!me) num_slabs = read_slab_info(); #ifdef USE_MPI if (MPI_Bcast(&num_slabs, 1, MPI_INT, 0, MPI_COMM_WORLD) != MPI_SUCCESS) exit_on_error("Error in MPI_Bcast()"); #endif /* USE_MPI */ if (num_slabs < nprocs) exit_on_error("Number of slabs may not exceed number of processes"); /* maximum number of slabs per process */ spp = (int)ceil((double)num_slabs / (double)nprocs); if (!me) printf("No more than %d slabs will assigned to each process\n", spp); /* allocate list and count of slabs for each process */ if (!(my_slabs = (int *)malloc(nprocs*spp* sizeof(int)))) { perror("my_slabs"); exit(2); } if (!(count = (int *)malloc(nprocs*sizeof(int)))) { perror("count"); exit(2); } /* initialize slab counts */ for (p = 0; p < nprocs; p++) count[p] = 0; /* round robin assignment of slabs to processes for better potential * load balancing */ for (i = j = p = 0; i < num_slabs; i++) { my_slabs[p*spp+j] = i; count[p]++; if (p == nprocs -1) p = 0, j++; else p++; } /* each process works on its own list of slabs, but OpenMP threads * divide up the slabs on each process because of OpenMP directive */ #pragma omp parallel for reduction(+: x) for (i = 0; i < count[me]; i++) { printf("%d: slab %d being processed", me, my_slabs[me*spp+i]); #ifdef _OPENMP printf(" by thread %d", omp_get_thread_num()); #endif /* _OPENMP */ printf("\n"); x += process_slab(my_slabs[me*spp+i]); } #ifdef USE_MPI if (MPI_Reduce(&x, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD) != MPI_SUCCESS) exit_on_error("Error in MPI_Reduce()"); #else /* USE_MPI */ sum = x; #endif /* USE_MPI */ if (!me) printf("Sum is %lg\n", sum); SimRoiEnd(); #ifdef USE_MPI printf("%d: Calling MPI_Finalize()\n", me); MPI_Finalize(); #endif /* USE_MPI */ exit(0); }
convolutiondepthwise_3x3_pack8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 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 convdw3x3s1_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const float* k0 = kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); __m256 _k00 = _mm256_loadu_ps(k0); __m256 _k01 = _mm256_loadu_ps(k0 + 8); __m256 _k02 = _mm256_loadu_ps(k0 + 16); __m256 _k10 = _mm256_loadu_ps(k0 + 24); __m256 _k11 = _mm256_loadu_ps(k0 + 32); __m256 _k12 = _mm256_loadu_ps(k0 + 40); __m256 _k20 = _mm256_loadu_ps(k0 + 48); __m256 _k21 = _mm256_loadu_ps(k0 + 56); __m256 _k22 = _mm256_loadu_ps(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1); __m256 _sum2 = _bias0; __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_fmadd_ps(_k00, _r02, _sum2); _sum2 = _mm256_fmadd_ps(_k01, _r03, _sum2); _sum2 = _mm256_fmadd_ps(_k02, _r04, _sum2); _sum2 = _mm256_fmadd_ps(_k10, _r12, _sum2); _sum2 = _mm256_fmadd_ps(_k11, _r13, _sum2); _sum2 = _mm256_fmadd_ps(_k12, _r14, _sum2); _sum2 = _mm256_fmadd_ps(_k20, _r22, _sum2); _sum2 = _mm256_fmadd_ps(_k21, _r23, _sum2); _sum2 = _mm256_fmadd_ps(_k22, _r24, _sum2); __m256 _sum3 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_fmadd_ps(_k00, _r03, _sum3); _sum3 = _mm256_fmadd_ps(_k01, _r04, _sum3); _sum3 = _mm256_fmadd_ps(_k02, _r05, _sum3); _sum3 = _mm256_fmadd_ps(_k10, _r13, _sum3); _sum3 = _mm256_fmadd_ps(_k11, _r14, _sum3); _sum3 = _mm256_fmadd_ps(_k12, _r15, _sum3); _sum3 = _mm256_fmadd_ps(_k20, _r23, _sum3); _sum3 = _mm256_fmadd_ps(_k21, _r24, _sum3); _sum3 = _mm256_fmadd_ps(_k22, _r25, _sum3); __m256 _sum4 = _bias0; __m256 _r06 = _mm256_loadu_ps(r0 + 48); __m256 _r16 = _mm256_loadu_ps(r1 + 48); __m256 _r26 = _mm256_loadu_ps(r2 + 48); _mm256_storeu_ps(outptr0 + 24, _sum3); _sum4 = _mm256_fmadd_ps(_k00, _r04, _sum4); _sum4 = _mm256_fmadd_ps(_k01, _r05, _sum4); _sum4 = _mm256_fmadd_ps(_k02, _r06, _sum4); _sum4 = _mm256_fmadd_ps(_k10, _r14, _sum4); _sum4 = _mm256_fmadd_ps(_k11, _r15, _sum4); _sum4 = _mm256_fmadd_ps(_k12, _r16, _sum4); _sum4 = _mm256_fmadd_ps(_k20, _r24, _sum4); _sum4 = _mm256_fmadd_ps(_k21, _r25, _sum4); _sum4 = _mm256_fmadd_ps(_k22, _r26, _sum4); __m256 _sum5 = _bias0; __m256 _r07 = _mm256_loadu_ps(r0 + 56); __m256 _r17 = _mm256_loadu_ps(r1 + 56); __m256 _r27 = _mm256_loadu_ps(r2 + 56); _mm256_storeu_ps(outptr0 + 32, _sum4); _sum5 = _mm256_fmadd_ps(_k00, _r05, _sum5); _sum5 = _mm256_fmadd_ps(_k01, _r06, _sum5); _sum5 = _mm256_fmadd_ps(_k02, _r07, _sum5); _sum5 = _mm256_fmadd_ps(_k10, _r15, _sum5); _sum5 = _mm256_fmadd_ps(_k11, _r16, _sum5); _sum5 = _mm256_fmadd_ps(_k12, _r17, _sum5); _sum5 = _mm256_fmadd_ps(_k20, _r25, _sum5); _sum5 = _mm256_fmadd_ps(_k21, _r26, _sum5); _sum5 = _mm256_fmadd_ps(_k22, _r27, _sum5); __m256 _sum6 = _bias0; __m256 _r08 = _mm256_loadu_ps(r0 + 64); __m256 _r18 = _mm256_loadu_ps(r1 + 64); __m256 _r28 = _mm256_loadu_ps(r2 + 64); _mm256_storeu_ps(outptr0 + 40, _sum5); _sum6 = _mm256_fmadd_ps(_k00, _r06, _sum6); _sum6 = _mm256_fmadd_ps(_k01, _r07, _sum6); _sum6 = _mm256_fmadd_ps(_k02, _r08, _sum6); _sum6 = _mm256_fmadd_ps(_k10, _r16, _sum6); _sum6 = _mm256_fmadd_ps(_k11, _r17, _sum6); _sum6 = _mm256_fmadd_ps(_k12, _r18, _sum6); _sum6 = _mm256_fmadd_ps(_k20, _r26, _sum6); _sum6 = _mm256_fmadd_ps(_k21, _r27, _sum6); _sum6 = _mm256_fmadd_ps(_k22, _r28, _sum6); __m256 _sum7 = _bias0; __m256 _r09 = _mm256_loadu_ps(r0 + 72); __m256 _r19 = _mm256_loadu_ps(r1 + 72); __m256 _r29 = _mm256_loadu_ps(r2 + 72); _mm256_storeu_ps(outptr0 + 48, _sum6); _sum7 = _mm256_fmadd_ps(_k00, _r07, _sum7); _sum7 = _mm256_fmadd_ps(_k01, _r08, _sum7); _sum7 = _mm256_fmadd_ps(_k02, _r09, _sum7); _sum7 = _mm256_fmadd_ps(_k10, _r17, _sum7); _sum7 = _mm256_fmadd_ps(_k11, _r18, _sum7); _sum7 = _mm256_fmadd_ps(_k12, _r19, _sum7); _sum7 = _mm256_fmadd_ps(_k20, _r27, _sum7); _sum7 = _mm256_fmadd_ps(_k21, _r28, _sum7); _sum7 = _mm256_fmadd_ps(_k22, _r29, _sum7); _mm256_storeu_ps(outptr0 + 56, _sum7); r0 += 64; r1 += 64; r2 += 64; outptr0 += 64; } for (; j + 3 < outw; j += 4) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1); __m256 _sum2 = _bias0; __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_fmadd_ps(_k00, _r02, _sum2); _sum2 = _mm256_fmadd_ps(_k01, _r03, _sum2); _sum2 = _mm256_fmadd_ps(_k02, _r04, _sum2); _sum2 = _mm256_fmadd_ps(_k10, _r12, _sum2); _sum2 = _mm256_fmadd_ps(_k11, _r13, _sum2); _sum2 = _mm256_fmadd_ps(_k12, _r14, _sum2); _sum2 = _mm256_fmadd_ps(_k20, _r22, _sum2); _sum2 = _mm256_fmadd_ps(_k21, _r23, _sum2); _sum2 = _mm256_fmadd_ps(_k22, _r24, _sum2); __m256 _sum3 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_fmadd_ps(_k00, _r03, _sum3); _sum3 = _mm256_fmadd_ps(_k01, _r04, _sum3); _sum3 = _mm256_fmadd_ps(_k02, _r05, _sum3); _sum3 = _mm256_fmadd_ps(_k10, _r13, _sum3); _sum3 = _mm256_fmadd_ps(_k11, _r14, _sum3); _sum3 = _mm256_fmadd_ps(_k12, _r15, _sum3); _sum3 = _mm256_fmadd_ps(_k20, _r23, _sum3); _sum3 = _mm256_fmadd_ps(_k21, _r24, _sum3); _sum3 = _mm256_fmadd_ps(_k22, _r25, _sum3); _mm256_storeu_ps(outptr0 + 24, _sum3); r0 += 32; r1 += 32; r2 += 32; outptr0 += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1); _mm256_storeu_ps(outptr0 + 8, _sum1); r0 += 16; r1 += 16; r2 += 16; outptr0 += 16; } for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 8; r1 += 8; r2 += 8; outptr0 += 8; } r0 += 2 * 8; r1 += 2 * 8; r2 += 2 * 8; } } } static void convdw3x3s2_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = (w - 2 * outw + w) * 8; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const float* k0 = kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); __m256 _k00 = _mm256_loadu_ps(k0); __m256 _k01 = _mm256_loadu_ps(k0 + 8); __m256 _k02 = _mm256_loadu_ps(k0 + 16); __m256 _k10 = _mm256_loadu_ps(k0 + 24); __m256 _k11 = _mm256_loadu_ps(k0 + 32); __m256 _k12 = _mm256_loadu_ps(k0 + 40); __m256 _k20 = _mm256_loadu_ps(k0 + 48); __m256 _k21 = _mm256_loadu_ps(k0 + 56); __m256 _k22 = _mm256_loadu_ps(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_fmadd_ps(_k00, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r04, _sum1); _sum1 = _mm256_fmadd_ps(_k10, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r14, _sum1); _sum1 = _mm256_fmadd_ps(_k20, _r22, _sum1); _sum1 = _mm256_fmadd_ps(_k21, _r23, _sum1); _sum1 = _mm256_fmadd_ps(_k22, _r24, _sum1); __m256 _sum2 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); __m256 _r06 = _mm256_loadu_ps(r0 + 48); __m256 _r16 = _mm256_loadu_ps(r1 + 48); __m256 _r26 = _mm256_loadu_ps(r2 + 48); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_fmadd_ps(_k00, _r04, _sum2); _sum2 = _mm256_fmadd_ps(_k01, _r05, _sum2); _sum2 = _mm256_fmadd_ps(_k02, _r06, _sum2); _sum2 = _mm256_fmadd_ps(_k10, _r14, _sum2); _sum2 = _mm256_fmadd_ps(_k11, _r15, _sum2); _sum2 = _mm256_fmadd_ps(_k12, _r16, _sum2); _sum2 = _mm256_fmadd_ps(_k20, _r24, _sum2); _sum2 = _mm256_fmadd_ps(_k21, _r25, _sum2); _sum2 = _mm256_fmadd_ps(_k22, _r26, _sum2); __m256 _sum3 = _bias0; __m256 _r07 = _mm256_loadu_ps(r0 + 56); __m256 _r17 = _mm256_loadu_ps(r1 + 56); __m256 _r27 = _mm256_loadu_ps(r2 + 56); __m256 _r08 = _mm256_loadu_ps(r0 + 64); __m256 _r18 = _mm256_loadu_ps(r1 + 64); __m256 _r28 = _mm256_loadu_ps(r2 + 64); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_fmadd_ps(_k00, _r06, _sum3); _sum3 = _mm256_fmadd_ps(_k01, _r07, _sum3); _sum3 = _mm256_fmadd_ps(_k02, _r08, _sum3); _sum3 = _mm256_fmadd_ps(_k10, _r16, _sum3); _sum3 = _mm256_fmadd_ps(_k11, _r17, _sum3); _sum3 = _mm256_fmadd_ps(_k12, _r18, _sum3); _sum3 = _mm256_fmadd_ps(_k20, _r26, _sum3); _sum3 = _mm256_fmadd_ps(_k21, _r27, _sum3); _sum3 = _mm256_fmadd_ps(_k22, _r28, _sum3); _mm256_storeu_ps(outptr0 + 24, _sum3); r0 += 2 * 32; r1 += 2 * 32; r2 += 2 * 32; outptr0 += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_fmadd_ps(_k00, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r04, _sum1); _sum1 = _mm256_fmadd_ps(_k10, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r14, _sum1); _sum1 = _mm256_fmadd_ps(_k20, _r22, _sum1); _sum1 = _mm256_fmadd_ps(_k21, _r23, _sum1); _sum1 = _mm256_fmadd_ps(_k22, _r24, _sum1); _mm256_storeu_ps(outptr0 + 8, _sum1); r0 += 2 * 16; r1 += 2 * 16; r2 += 2 * 16; outptr0 += 16; } for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 2 * 8; r1 += 2 * 8; r2 += 2 * 8; outptr0 += 8; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
compression.h
// // Created by Bangtian Liu on 6/30/19. // #ifndef PROJECT_COMPRESSION_H #define PROJECT_COMPRESSION_H #include <vector> #include <algorithm> #include <random> #include <cstring> #include "../sympiler/HMatrix.h" #include "HTree.h" #include "../sympiler/HTree.h" using namespace Sympiler::Internal; using namespace Sympiler; struct cretvalue { int *skels; int skels_length; double *proj; int proj_column; }; struct DDcost { int index; unsigned long cost; }; bool fcompare(DDcost lhs, DDcost rhs) { return lhs.cost > rhs.cost; } typedef cretvalue ret; using namespace std; void Fsubmatrix(std::vector<int> &amap, std::vector<int> &bmap, double *submatrix, double *X, int n, int d, Internal::Ktype ktype, double h) { switch (ktype) { case Internal::KS_GAUSSIAN: { double *source = (double *) mkl_malloc(sizeof(double) * bmap.size() * d, 64); double *target = (double *) mkl_malloc(sizeof(double) * amap.size() * d, 64); #pragma omp parallel for for (int i = 0; i < bmap.size(); i++) { for (int j = 0; j < d; j++) { source[i * d + j] = X[bmap[i] * d + j]; } } #pragma omp parallel for for (int i = 0; i < amap.size(); i++) { for (int j = 0; j < d; j++) { target[i * d + j] = X[amap[i] * d + j]; } } cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, amap.size(), bmap.size(), d, -2.0, target, d, source, d, 0.0, submatrix, amap.size()); double *target_sqnorms = (double *) mkl_malloc(sizeof(double) * amap.size(), 64); double *source_sqnorms = (double *) mkl_malloc(sizeof(double) * bmap.size(), 64); #pragma omp parallel for for (int i = 0; i < amap.size(); i++) { target_sqnorms[i] = cblas_ddot(d, target + i * d, 1, target + i * d, 1); } for (int i = 0; i < bmap.size(); i++) { source_sqnorms[i] = cblas_ddot(d, source + i * d, 1, source + i * d, 1); } #pragma omp parallel for for (int j = 0; j < bmap.size(); j++) { for (int i = 0; i < amap.size(); i++) submatrix[j * amap.size() + i] += target_sqnorms[i] + source_sqnorms[j]; } double kscal = -0.5 / (h * h); #pragma omp parallel for for (int i = 0; i < amap.size() * bmap.size(); i++) { submatrix[i] = std::exp(kscal * submatrix[i]); } break; } case Internal::KS_LOG: { //#pragma omp parallel for // for (int i = 0; i < amap.size() * bmap.size(); i++) { // submatrix[i] = -0.5 * log(submatrix[i]); // } break; } case Internal::KS_EXPONENTIAL: { //#pragma omp parallel for // for (int i = 0; i < amap.size() * bmap.size(); i++) { // submatrix[i] = exp(-sqrt(submatrix[i]));; // } break; } case Internal::KS_NEWTON: { #pragma omp parallel for for (int j = 0; j < bmap.size(); j++) { for (int i = 0; i < amap.size(); i++) { auto Kij = 0.0; for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } if(Kij==0)Kij=1; submatrix[j * amap.size() + i] = 1/sqrt(Kij); } } //#pragma omp parallel for // for (int i = 0; i < amap.size() * bmap.size(); i++) { // if(submatrix[i]==0) submatrix[i] = 1; // else submatrix[i] = 1/std::sqrt(submatrix[i]); // } break; } default: { printf("invalid kernel type\n"); exit(1); break; } } } // //void DDDFsubmatrix(std::vector<int> &amap, std::vector<int> &bmap, double *submatrix, double *X, int n, int d, Internal::Ktype ktype, // double h) //{ // // double *source = (double *)mkl_malloc(sizeof(double)*bmap.size()*d, 64); // double *target = (double *)mkl_malloc(sizeof(double)*amap.size()*d, 64); // //#pragma omp parallel for // for(int i=0; i<bmap.size(); i++) // { // for(int j=0; j<d; j++) // { // source[i*d + j] = X[bmap[i]*d+j]; // } // } // //#pragma omp parallel for // for(int i=0; i<amap.size(); i++) { // for (int j = 0; j < d; j++) { // target[i*d + j] = X[amap[i]*d+j]; // } // } // // cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, // amap.size(), bmap.size(), d, -2.0, // target, d, // source, d, 0.0, // submatrix, amap.size()); // // double *target_sqnorms = (double *)mkl_malloc(sizeof(double)*amap.size(), 64); // double *source_sqnorms = (double *)mkl_malloc(sizeof(double)*bmap.size(), 64); // //#pragma omp parallel for // for(int i=0; i<amap.size(); i++) // { // target_sqnorms[i] = cblas_ddot(d, // target+i*d, 1, // target+i*d, 1); // } // // for(int i=0; i<bmap.size(); i++) // { // source_sqnorms[i] = cblas_ddot(d, // source+i*d,1, // source+i*d,1); // } //#pragma omp parallel for // for(int j=0; j<bmap.size(); j++) // { // for(int i=0; i<amap.size(); i++) // submatrix[j*amap.size() + i] += target_sqnorms[i] + source_sqnorms[j]; // } // // switch (ktype) { // case Internal::KS_GAUSSIAN: { // // double kscal = -0.5/(h * h); //#pragma omp parallel for // for(int i=0; i<amap.size()*bmap.size(); i++) // { // submatrix[i] = 1.0; // } // // break; // } // // case Internal::KS_LOG: { //#pragma omp parallel for // for(int i=0; i<amap.size()*bmap.size(); i++) // { // submatrix[i] = -0.5 * log(submatrix[i]); // } // // break; // } // // case Internal::KS_EXPONENTIAL: { //#pragma omp parallel for // for(int i=0; i<amap.size()*bmap.size(); i++) // { // submatrix[i] = exp(-sqrt(submatrix[i]));; // } // break; // } // // case Internal::KS_NEWTON: { // //#pragma omp parallel for // for(int i=0; i<amap.size()*bmap.size(); i++) // { // submatrix[i] = std::sqrt(submatrix[i]); // } // // break; // } // // default: { // printf("invalid kernel type\n"); // exit(1); // break; // } // } // //} void Fsubmatrix(int *amap, int lena, int *bmap, int lenb, double *submatrix, Internal::Ktype ktype, double *X, int d, double h) { switch (ktype) { case Internal::KS_GAUSSIAN: { double *source = (double *) mkl_malloc(sizeof(double) * lenb * d, 64); double *target = (double *) mkl_malloc(sizeof(double) * lena * d, 64); #pragma omp parallel for for (int i = 0; i < lenb; i++) { for (int j = 0; j < d; j++) { source[i * d + j] = X[bmap[i] * d + j]; } } #pragma omp parallel for for (int i = 0; i < lena; i++) { for (int j = 0; j < d; j++) { target[i * d + j] = X[amap[i] * d + j]; } } cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, lena, lenb, d, -2.0, target, d, source, d, 0.0, submatrix, lena); double *target_sqnorms = (double *) mkl_malloc(sizeof(double) * lena, 64); double *source_sqnorms = (double *) mkl_malloc(sizeof(double) * lenb, 64); #pragma omp parallel for for (int i = 0; i < lena; i++) { target_sqnorms[i] = cblas_ddot(d, target + i * d, 1, target + i * d, 1); } #pragma omp parallel for for (int i = 0; i < lenb; i++) { source_sqnorms[i] = cblas_ddot(d, source + i * d, 1, source + i * d, 1); } #pragma omp parallel for for (int j = 0; j < lenb; j++) { for (int i = 0; i < lena; i++) submatrix[j * lena + i] += target_sqnorms[i] + source_sqnorms[j]; } double kscal = -0.5 / (h * h); #pragma omp parallel for for (int i = 0; i < lena * lenb; i++) { submatrix[i] = std::exp(kscal * submatrix[i]); } break; } case Internal::KS_LOG: { //#pragma omp parallel for // for (int i = 0; i < lena * lenb; i++) { // submatrix[i] = -0.5 * log(submatrix[i]); // } break; } case Internal::KS_EXPONENTIAL: { //#pragma omp parallel for // for (int i = 0; i < lena * lenb; i++) { // submatrix[i] = exp(-sqrt(submatrix[i]));; // } // break; } case Internal::KS_NEWTON: { #pragma omp parallel for for (int j = 0; j < lenb; j++) { for (int i = 0; i < lena; i++) { auto Kij = 0.0; for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } if(Kij==0)Kij=1; submatrix[j * lena + i] = 1/sqrt(Kij); } } break; } default: { printf("invalid kernel type\n"); exit(1); break; } } } void BuildNeighBorsLeaf(HTree &tree, int idx, int nsamples) { auto &pnids = tree.pnids[idx]; auto &snids = tree.snids[idx]; int k = 32; auto &NN = tree.NN; auto lids = tree.lids + tree.lidsoffset[idx]; int n = tree.lidslen[idx]; // printf("len=%d\n",n); pnids = std::unordered_set<int>(); // will modify for (int ii = 0; ii < k / 2; ii++) { for (int jj = 0; jj < n; jj++) { auto idx = NN[lids[jj] * k + ii].second; pnids.insert(idx); // printf("%lu;",NN[ lids[jj] * k + ii].second); } } for (int i = 0; i < n; i++) { pnids.erase(lids[i]); } // printf("Leaf Size of pruning neighbor set: %lu \n", pnids.size()); snids = std::map<int, double>(); std::vector<std::pair<double, int>> tmp(k / 2 * n); std::set<int> nodeIdx(lids, lids + n); // Allocate array for sorting for (int ii = (k + 1) / 2; ii < k; ii++) { for (int jj = 0; jj < n; jj++) { tmp[(ii - (k + 1) / 2) * n + jj] = NN[lids[jj] * k + ii]; } } std::sort(tmp.begin(), tmp.end()); int i = 0; while (snids.size() < nsamples && i < (k - 1) * n / 2) { if (!pnids.count(tmp[i].second) && !nodeIdx.count(tmp[i].second)) { snids.insert(std::pair<int, double>(tmp[i].second, tmp[i].first)); } i++; } } void BuildNeighBorsInternal(HTree &tree, int idx, int nsamples) { auto &pnids = tree.pnids[idx]; auto &snids = tree.snids[idx]; int k = 32; auto &NN = tree.NN; auto lids = tree.lids + tree.lidsoffset[idx]; int n = tree.lidslen[idx]; auto &lsnids = tree.snids[tree.tlchildren[idx]]; auto &rsnids = tree.snids[tree.trchildren[idx]]; auto &lpnids = tree.pnids[tree.tlchildren[idx]]; auto &rpnids = tree.pnids[tree.trchildren[idx]]; snids = lsnids; for (auto cur = rsnids.begin(); cur != rsnids.end(); cur++) { auto ret = snids.insert(*cur); if (ret.second == false) { // Update distance? if (ret.first->second > (*cur).first) { ret.first->second = (*cur).first; } } } // Remove "own" points for (int i = 0; i < n; i++) { snids.erase(lids[i]); } // Remove pruning neighbors from left and right for (auto cur = lpnids.begin(); cur != lpnids.end(); cur++) { snids.erase(*cur); } for (auto cur = rpnids.begin(); cur != rpnids.end(); cur++) { snids.erase(*cur); } } int decomposition(double *A, int nRows, int nCols, double tolerance, int **skels, double **proj, int **jpvt) { assert(nRows > nCols); int s; int maxRank = 256; // printf("maxRank=%d\n",maxRank); *jpvt = (int *) malloc(sizeof(int) * nCols); memset(*jpvt, 0, sizeof(int) * nCols); // T *tau = GenMatrix<T>(std::min(nRows,nCols),1); double *tau = (double *) mkl_malloc(sizeof(double) * std::min(nRows, nCols), 64); auto info = LAPACKE_dgeqp3(LAPACK_COL_MAJOR, nRows, nCols, A, nRows, *jpvt, tau); if (info != 0) { printf("%d-th parameter had an illegal value", -info); } #pragma omp parallel for for (int i = 0; i < nCols; ++i) { (*jpvt)[i] = (*jpvt)[i] - 1; } for (s = 1; s < nCols; ++s) { // printf("s=%d, a=%e, error=%e nCOls=%d\n",s, A[s*nRows+s],tolerance,nCols); if (s > maxRank || std::abs(A[s * nRows + s]/A[0]) < tolerance) break; } // if(!setup.adaptive) // { // s = std::min(maxRank, nCols); // } if (s > maxRank) s = maxRank; *skels = (int *) malloc(sizeof(int) * s); memcpy(*skels, *jpvt, sizeof(int) * s); // memcpy(*skels,*proj, sizeof(int)*s); // *proj = GenMatrix<T>(s,nCols); *proj = (double *) mkl_malloc(sizeof(double) * s * nCols, 64); memset(*proj, 0, sizeof(double) * s * nCols); //#pragma omp parallel for for (int j = 0; j < nCols; j++) { for (int i = 0; i < s; i++) { if (j < s) { if (j >= i) (*proj)[j * s + i] = A[j * nRows + i]; else (*proj)[j * s + i] = 0.0; } else { (*proj)[j * s + i] = A[j * nRows + i]; } } } if ((*proj)[0] == 0) return s; // put on here double *R1 = (double *) mkl_malloc(sizeof(double) * s * s, 64); memset(R1, 0, sizeof(double) * s * s); // todo check the segment fault bug here //#pragma omp parallel for for (int j = 0; j < s; j++) { for (int i = 0; i < s; i++) { if (i <= j) R1[j * s + i] = (*proj)[j * s + i]; // if((*proj)[j*s+i]!=(*proj)[j*s+i])printf("NAN FOUND1!!!\n"); } } // T *tmp = GenMatrix<T>(s,nCols); double *tmp = (double *) mkl_malloc(sizeof(double) * s * nCols, 64); memcpy(tmp, *proj, sizeof(double) * s * nCols); cblas_dtrsm(CblasColMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, s, nCols, 1.0, R1, s, tmp, s); /** Fill in proj */ for (int j = 0; j < nCols; j++) { for (int i = 0; i < s; i++) { (*proj)[(*jpvt)[j] * s + i] = tmp[j * s + i]; } } return s; } void skeletonize_leaf(int idx, int *lids, int *lidslen, int *lidsoffset, ret *rtmp, int *sid, int *sidlen, int *sidoffset, int *lc, int *rc, int m, int n, double *X, Internal::Ktype ktype, int dim, double h, double acc) { std::vector<int> bmap; bmap.insert(bmap.end(), lids + lidsoffset[idx], lids + lidsoffset[idx] + lidslen[idx]); auto nsamples = 2 * bmap.size(); auto numpoints = lidslen[idx]; auto clids = lids + lidsoffset[idx]; nsamples = (nsamples < 2 * m) ? 2 * m : nsamples; int slen = sidlen[idx]; int offset = sidoffset[idx]; // printf("idx =%d slen=%d\n", idx, slen); // add sampling points std::vector<int> amap; // (sid+offset, sid+offset+slen); mt19937 generator(idx); uniform_int_distribution<> uniform_distribution(0, n - 1); if (nsamples < (n - numpoints)) { amap.assign(sid + offset, sid + offset + slen); while (amap.size() < nsamples) { // auto sample = rand() % setup.n; auto sample = uniform_distribution(generator); if (std::find(amap.begin(), amap.end(), sample) == amap.end() && std::find(clids, clids + numpoints, sample) == (clids + numpoints)) { amap.push_back(sample); } } } else { for (int sample = 0; sample < n; sample++) // TODO: may can be improved here { if (std::find(amap.begin(), amap.end(), sample) == amap.end()) { amap.push_back(sample); } } } auto Kab = (double *) malloc(sizeof(double) * amap.size() * bmap.size()); memset(Kab, 0, sizeof(double) * amap.size() * bmap.size()); Fsubmatrix(amap, bmap, Kab, X, n, dim, ktype, h); auto N = n; auto m1 = amap.size(); auto n1 = bmap.size(); auto q = numpoints; // std::sqrt((m1 * n1 * 1.0) / (1.0 * N * (N - q))) * auto tolerance = acc; int *skels; double *proj; int *jpvt; int s = decomposition(Kab, m1, n1, tolerance, &skels, &proj, &jpvt); for (int i = 0; i < s; ++i) { // need to check it skels[i] = bmap[skels[i]]; } rtmp[idx].skels = skels; rtmp[idx].skels_length = s; rtmp[idx].proj = proj; rtmp[idx].proj_column = (int) bmap.size(); free(Kab); } void skeletonize_leaf(int idx, HTree &tree, ret *rtmp, int m, int n, double *X, Internal::Ktype ktype, int dim, double h, double acc) { auto lc = tree.tlchildren; auto rc = tree.trchildren; auto lids = tree.lids; auto lidslen = tree.lidslen; auto lidsoffset = tree.lidsoffset; std::vector<int> bmap; bmap.insert(bmap.end(), lids + lidsoffset[idx], lids + lidsoffset[idx] + lidslen[idx]); auto nsamples = 2 * bmap.size(); auto numpoints = lidslen[idx]; auto clids = lids + lidsoffset[idx]; nsamples = (nsamples < 2 * m) ? 2 * m : nsamples; BuildNeighBorsLeaf(tree, idx, nsamples); auto &snids = tree.snids[idx]; auto &pnids = tree.pnids[idx]; std::multimap<double, int> ordered_snids = flip_map(snids); // add sampling points std::vector<int> amap; // (sid+offset, sid+offset+slen); // mt19937 generator(idx); // uniform_int_distribution<> uniform_distribution(0, n - 1); // printf("idx =%d, len=%ld %ld\n", idx, ordered_snids.size(), nsamples); if (nsamples < (n - numpoints)) { amap.reserve(nsamples); for (auto cur = ordered_snids.begin(); cur != ordered_snids.end(); cur++) { amap.push_back(cur->second); } while (amap.size() < nsamples) { auto sample = rand() % n; // auto sample = uniform_distribution(generator); if (std::find(amap.begin(), amap.end(), sample) == amap.end() && std::find(clids, clids + numpoints, sample) == (clids + numpoints)) { amap.push_back(sample); } } } else { for (int sample = 0; sample < n; sample++) // TODO: may can be improved here { if (std::find(amap.begin(), amap.end(), sample) == amap.end()) { amap.push_back(sample); } } } auto Kab = (double *) malloc(sizeof(double) * amap.size() * bmap.size()); memset(Kab, 0, sizeof(double) * amap.size() * bmap.size()); Fsubmatrix(amap, bmap, Kab, X, n, dim, ktype, h); auto N = n; auto m1 = amap.size(); auto n1 = bmap.size(); auto q = numpoints; // double scal_tol = std::sqrt((double)n1/q) *std::sqrt((double)m1/(N-q)) * acc; // auto tolerance = std::sqrt((double)q/N) * scal_tol; auto tolerance = acc; int *skels; double *proj; int *jpvt; int s = decomposition(Kab, m1, n1, tolerance, &skels, &proj, &jpvt); for (int i = 0; i < s; ++i) { // need to check it skels[i] = bmap[skels[i]]; } pnids.clear(); auto &NN = tree.NN; for (int ii = 0; ii < s; ii++) { for (int jj = 0; jj < 32 / 2; jj++) { pnids.insert(NN.data()[skels[ii] * 32 + jj].second); } } rtmp[idx].skels = skels; rtmp[idx].skels_length = s; rtmp[idx].proj = proj; rtmp[idx].proj_column = (int) bmap.size(); free(Kab); } void skeletonize_internal(int idx, HTree &tree, ret *rtmp, int m, int n, double *X, Internal::Ktype ktype, int dim, double h, double acc) { auto lc = tree.tlchildren; auto rc = tree.trchildren; auto lids = tree.lids; auto lidslen = tree.lidslen; auto lidsoffset = tree.lidsoffset; std::vector<int> bmap; auto v = lc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); v = rc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); auto nsamples = 2 * bmap.size(); auto numpoints = lidslen[idx]; auto clids = lids + lidsoffset[idx]; nsamples = (nsamples < 2 * m) ? 2 * m : nsamples; BuildNeighBorsInternal(tree, idx, nsamples); auto &snids = tree.snids[idx]; auto &pnids = tree.pnids[idx]; std::multimap<double, int> ordered_snids = flip_map(snids); std::vector<int> amap; // (sid+offset, sid+offset+slen); // mt19937 generator(idx); // uniform_int_distribution<> uniform_distribution(0, n - 1); // printf("idx=%d len=%ld %ld\n", idx, ordered_snids.size(), nsamples); if (nsamples < (n - numpoints)) { // printf("idx=%d, len=%d nsamples=%d\n", idx, ordered_snids.size(), nsamples); amap.reserve(nsamples); if(ordered_snids.size()>nsamples){ auto cur = ordered_snids.begin(); for(int k=0; k<nsamples; k++) { amap.push_back(cur->second); cur++; } } else { for (auto cur = ordered_snids.begin(); cur != ordered_snids.end(); cur++) { amap.push_back(cur->second);} } while (amap.size() < nsamples) { auto sample = rand() % n; // auto sample = uniform_distribution(generator); if (std::find(amap.begin(), amap.end(), sample) == amap.end() && std::find(clids, clids + numpoints, sample) == (clids + numpoints)) { amap.push_back(sample); } } } else { for (int sample = 0; sample < n; sample++) // TODO: may can be improved here { if (std::find(amap.begin(), amap.end(), sample) == amap.end()) { amap.push_back(sample); } } } auto Kab = (double *) malloc(sizeof(double) * amap.size() * bmap.size()); memset(Kab, 0, sizeof(double) * amap.size() * bmap.size()); Fsubmatrix(amap, bmap, Kab, X, n, dim, ktype, h); auto N = n; auto m1 = amap.size(); auto n1 = bmap.size(); auto q = numpoints; // double scal_tol = std::sqrt((double)n1/q) *std::sqrt((double)m1/(N-q)) * acc; // // auto tolerance = std::sqrt((double)q/N) * scal_tol; auto tolerance = acc; int *skels; double *proj; int *jpvt; int s = decomposition(Kab, m1, n1, tolerance, &skels, &proj, &jpvt); for (int i = 0; i < s; ++i) { // need to check it skels[i] = bmap[skels[i]]; } pnids.clear(); auto &NN = tree.NN; for (int ii = 0; ii < s; ii++) { for (int jj = 0; jj < 32 / 2; jj++) { pnids.insert(NN.data()[skels[ii] * 32 + jj].second); } } rtmp[idx].skels = skels; rtmp[idx].skels_length = s; rtmp[idx].proj = proj; rtmp[idx].proj_column = (int) bmap.size(); // free(Kab); } void skeletonize_internal(int idx, int *lids, int *lidslen, int *lidsoffset, ret *rtmp, int *sid, int *sidlen, int *sidoffset, int *lc, int *rc, int m, int n, double *X, Internal::Ktype ktype, int dim, double h, double acc) { std::vector<int> bmap; auto v = lc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); v = rc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); auto nsamples = 2 * bmap.size(); auto numpoints = lidslen[idx]; auto clids = lids + lidsoffset[idx]; nsamples = (nsamples < 2 * m) ? 2 * m : nsamples; int slen = sidlen[idx]; int offset = sidoffset[idx]; std::vector<int> amap; mt19937 generator(idx); uniform_int_distribution<> uniform_distribution(0, n - 1); if (nsamples < (n - numpoints)) { // printf("idx=%d, len=%d nsamples=%d\n", idx, slen, nsamples); amap.assign(sid + offset, sid + offset + slen); while (amap.size() < nsamples) { // auto sample = rand() % setup.n; auto sample = uniform_distribution(generator); if (std::find(amap.begin(), amap.end(), sample) == amap.end() && std::find(clids, clids + numpoints, sample) == (clids + numpoints)) { amap.push_back(sample); } } } else { for (int sample = 0; sample < n; sample++) // TODO: may can be improved here { if (std::find(amap.begin(), amap.end(), sample) == amap.end()) { amap.push_back(sample); } } } auto Kab = (double *) malloc(sizeof(double) * amap.size() * bmap.size()); memset(Kab, 0, sizeof(double) * amap.size() * bmap.size()); Fsubmatrix(amap, bmap, Kab, X, n, dim, ktype, h); auto N = n; auto m1 = amap.size(); auto n1 = bmap.size(); auto q = numpoints; auto tolerance = std::sqrt((m1 * n1 * 1.0) / (1.0 * N * (N - q))) * acc; int *skels; double *proj; int *jpvt; int s = decomposition(Kab, m1, n1, tolerance, &skels, &proj, &jpvt); for (int i = 0; i < s; ++i) { // need to check it skels[i] = bmap[skels[i]]; } rtmp[idx].skels = skels; rtmp[idx].skels_length = s; rtmp[idx].proj = proj; rtmp[idx].proj_column = (int) bmap.size(); free(Kab); } void skeletonize(int idx, int *lids, int *lidslen, int *lidsoffset, ret *rtmp, int *sid, int *sidlen, int *sidoffset, int *lc, int *rc, int m, int n, double *X, Internal::Ktype ktype, int dim, double h) { // if(idx==0){ // return; // } std::vector<int> bmap; if (lc[idx] == -1) { // leaf node bmap.insert(bmap.end(), lids + lidsoffset[idx], lids + lidsoffset[idx] + lidslen[idx]); } else { auto v = lc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); v = rc[idx]; bmap.insert(bmap.end(), rtmp[v].skels, rtmp[v].skels + rtmp[v].skels_length); } // printf("bmap size=%d len=%d\n",bmap.size(), lidslen[idx]); auto nsamples = 2 * bmap.size(); auto numpoints = lidslen[idx]; auto clids = lids + lidsoffset[idx]; nsamples = (nsamples < 2 * m) ? 2 * m : nsamples; int slen = sidlen[idx]; int offset = sidoffset[idx]; // add sampling points std::vector<int> amap(sid + offset, sid + offset + slen); mt19937 generator(idx); uniform_int_distribution<> uniform_distribution(0, n - 1); if (nsamples < (n - numpoints)) { while (amap.size() < nsamples) { // auto sample = rand() % setup.n; auto sample = uniform_distribution(generator); if (std::find(amap.begin(), amap.end(), sample) == amap.end() && std::find(clids, clids + numpoints, sample) == (clids + numpoints)) { amap.push_back(sample); } } } else { for (int sample = 0; sample < n; sample++) // TODO: may can be improved here { if (std::find(amap.begin(), amap.end(), sample) == amap.end()) { amap.push_back(sample); } } } auto Kab = (double *) malloc(sizeof(double) * amap.size() * bmap.size()); memset(Kab, 0, sizeof(double) * amap.size() * bmap.size()); Fsubmatrix(amap, bmap, Kab, X, n, dim, ktype, h); auto N = n; auto m1 = amap.size(); auto n1 = bmap.size(); auto q = numpoints; double error = 1e-5; // printf("m1=%d, n1=%d N=%d q=%d\n", m1, n1, N, q); auto tolerance = std::sqrt((m1 * n1 * 1.0) / (1.0 * N * (N - q))) * error; // printf("error=%lf\n", std::sqrt((m1*n1*1.0)/(1.0*N*(N-q)))); // auto tolerance = 1E-5; int *skels; double *proj; int *jpvt; int s = decomposition(Kab, m1, n1, tolerance, &skels, &proj, &jpvt); // printf("s=%d\n",s); for (int i = 0; i < s; ++i) { // need to check it skels[i] = bmap[skels[i]]; } rtmp[idx].skels = skels; rtmp[idx].skels_length = s; rtmp[idx].proj = proj; rtmp[idx].proj_column = (int) bmap.size(); free(Kab); } void binpacking(std::vector<std::vector<int>> &wpartitions, std::vector<std::vector<int>> &owpartitions, int numofbins, clustertree &ctree, HTree &tree, ret *rtmp) { DDcost *ccost = new DDcost[wpartitions.size()]; for (auto i = 0; i < wpartitions.size(); i++) { ccost[i].cost = 0; ccost[i].index = i; for (auto j = 0; j < wpartitions[i].size(); j++) { auto idx = wpartitions[i][j]; unsigned long cost = 0; if (tree.tlchildren[idx] == -1) { cost += 2 * rtmp[idx].skels_length * rtmp[idx].proj_column; // leafdim[leafmap.at(idx)] * setup.nrhs; } else { auto lc = tree.tlchildren[idx]; auto rc = tree.trchildren[idx]; cost += 2 * rtmp[idx].skels_length * rtmp[lc].skels_length; cost += 2 * rtmp[idx].skels_length * rtmp[rc].skels_length; // // for(auto &v : children[idx]) // { // cost += 2*tmpresult[idx].skels_length*tmpresult[v].skels_length*setup.nrhs; // } } ccost[i].cost += cost; } } std::sort(ccost, ccost + wpartitions.size(), fcompare); uint64_t *ocost = new uint64_t[numofbins]; memset(ocost, 0, sizeof(uint64_t) * numofbins); int partNo = wpartitions.size(); int minBin = 0; for (int i = 0; i < partNo; i++) { minBin = findMin(ocost, numofbins); ocost[minBin] += ccost[i].cost; int index = ccost[i].index; //owpartition owpartitions[minBin].insert(owpartitions[minBin].end(), wpartitions[index].begin(), wpartitions[index].end()); } } void BalanceCoarLevelSet(clustertree &ctree, HTree &tree, ret *rtmp) { auto &postw = ctree.postw; auto &opostw = ctree.opostw; auto len = postw.size(); opostw.resize(len); // auto &pow=tree->postw; // auto &opow=tree->opostw; for (int i = 0; i < postw.size(); i++) { auto &lpow = postw[i]; int nw = lpow.size(); int nparts; int nthreads = omp_get_max_threads(); if (nw >= nthreads) { nparts = nthreads; } else { nparts = nw / 2; } if (nparts == 0)nparts = 1; opostw[i].resize(nparts); binpacking(lpow, opostw[i], nparts, ctree, tree, rtmp); } len = opostw.size(); len = 0; int index = 0; for (auto &v:postw) { tree.clevelset[index++] = len; len += v.size(); } tree.clevelset[index] = len; len = 0; index = 0; int tidx = 0; for (auto &v:postw) { for (auto &w:v) { tree.wpart[index++] = len; len += w.size(); for (auto &t:w) { tree.idx[tidx++] = t; } } } tree.wpart[index] = len; } void compression(clustertree &ctree, HTree &tree, ret *rtmp, double *X, int m, int n, Internal::Ktype ktype, int dim, double h, bool coarsening, double acc = 1e-5) { #pragma omp parallel for for (int j = tree.levelset[tree.depth - 1]; j < tree.levelset[tree.depth]; j++) { auto id = tree.idx[j]; skeletonize_leaf(id, tree, rtmp, m, n, X, ktype, dim, h, acc); } for (int i = tree.depth - 2; i > -1; i--) { #pragma omp parallel for for (int j = tree.levelset[i]; j < tree.levelset[i + 1]; j++) { auto id = tree.idx[j]; skeletonize_internal(id, tree, rtmp, m, n, X, ktype, dim, h, acc); } } if(coarsening)BalanceCoarLevelSet(ctree,tree,rtmp); } unsigned long computeFlops(HTree &tree, ret *rtmp, int m, int nrhs) { unsigned long flops = 0; unsigned long tflops = 0; unsigned long inflops = 0; for (int j = tree.levelset[tree.depth - 1]; j < tree.levelset[tree.depth]; j++) { auto id = tree.idx[j]; flops+=2*rtmp[id].skels_length * nrhs*tree.Dim[tree.lm[id]]; } for (int i = tree.depth - 2; i > -1; i--) { for (int j = tree.levelset[i]; j < tree.levelset[i + 1]; j++) { auto id = tree.idx[j]; auto lc = tree.tlchildren[id]; auto rc = tree.trchildren[id]; flops += 2 * rtmp[id].skels_length * (rtmp[lc].skels_length+rtmp[rc].skels_length)*nrhs; } } flops = 2*flops; tflops += flops; // printf("tree flops is %lu\n", tflops); for(int k=0; k<tree.ncount; k++) { auto nx = tree.nxval[k]; auto ny = tree.nyval[k]; auto dimx = tree.Dim[nx]; auto dimy = tree.Dim[ny]; flops += 2*dimx*dimy*nrhs; } // printf("number of near nodes is %d\n", tree.ncount); for(int k = 0; k<tree.fcount; k++) { auto fx = tree.fxval[k]; auto fy = tree.fyval[k]; auto dimx = rtmp[fx].skels_length; auto dimy = rtmp[fy].skels_length; flops += 2*dimx*dimy*nrhs; } // printf("number of far nodes is %d\n", tree.fcount); // printf("interaction flops is %lu\n", flops-tflops); return flops; } unsigned long computeRanks(HTree &tree, ret *rtmp, int m, int nrhs) { unsigned long rank = 0; int count=0; for (int j = tree.levelset[tree.depth - 1]; j < tree.levelset[tree.depth]; j++) { auto id = tree.idx[j]; rank +=rtmp[id].skels_length; ++count; // flops+=2*rtmp[id].skels_length * nrhs*tree.Dim[tree.lm[id]]; } for (int i = tree.depth - 2; i > -1; i--) { for (int j = tree.levelset[i]; j < tree.levelset[i + 1]; j++) { auto id = tree.idx[j]; rank +=rtmp[id].skels_length; ++count; // auto lc = tree.tlchildren[id]; // auto rc = tree.trchildren[id]; // flops += 2 * rtmp[id].skels_length * (rtmp[lc].skels_length+rtmp[rc].skels_length)*nrhs; } } return rank/count; } void coarcompression(HTree &tree, ret *rtmp, double *X, int m, int n, Internal::Ktype ktype, int dim, int h, double acc) { #pragma omp parallel for for (int k = tree.clevelset[0]; k < tree.clevelset[1]; k++) { for (int j = tree.wpart[k]; j < tree.wpart[k + 1]; j++) { auto id = tree.cidx[j]; if (tree.tlchildren[id] == -1) { skeletonize_leaf(id, tree.lids, tree.lidslen, tree.lidsoffset, rtmp, tree.sids, tree.sidlen, tree.sidoffset, tree.tlchildren, tree.trchildren, m, n, X, ktype, dim, h, acc); } else { skeletonize_internal(id, tree.lids, tree.lidslen, tree.lidsoffset, rtmp, tree.sids, tree.sidlen, tree.sidoffset, tree.tlchildren, tree.trchildren, m, n, X, ktype, dim, h, acc); } // skeletonize(id, tree.lids, tree.lidslen, tree.lidsoffset, rtmp, tree.sids, tree.sidlen, tree.sidoffset, tree.tlchildren, // tree.trchildren, m, n, X, ktype, dim, h); } } for (int i = 1; i < tree.cdepth; i++) { #pragma omp parallel for for (int k = tree.clevelset[i]; k < tree.clevelset[i + 1]; k++) { //#pragma omp parallel for for (int j = tree.wpart[k]; j < tree.wpart[k + 1]; j++) { auto id = tree.cidx[j]; skeletonize_internal(id, tree.lids, tree.lidslen, tree.lidsoffset, rtmp, tree.sids, tree.sidlen, tree.sidoffset, tree.tlchildren, tree.trchildren, m, n, X, ktype, dim, h, acc); } } } } #endif //PROJECT_COMPRESSION_H
singleModificado2.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #define omp_get_num_threads() 1 #endif int main(int argc, char ** argv) { int n = 9, i, a, b[n]; for (i=0; i<n; i++) b[i] = -1; #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP #pragma omp single #endif { printf("Introduce valor de inicialización a: "); scanf("%d", &a ); printf("Single ejecutada por el thread %d\n",omp_get_thread_num()); } #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) b[i] = a; #ifdef _OPENMP #pragma omp barrier #pragma omp master #endif { printf("Dentro del parallel en la thread %d:\n",omp_get_thread_num()); for (i=0; i<n; i++) printf("b[%d] = %d\t",i,b[i]); printf("\n"); } } return 0; }
utils.h
#pragma once #include <iostream> #include <vector> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #ifdef _WIN32 #include <filesystem> #else #include <dirent.h> #include <sys/types.h> #endif namespace PaddleSolution { namespace utils { inline std::string path_join(const std::string& dir, const std::string& path) { std::string seperator = "/"; #ifdef _WIN32 seperator = "\\"; #endif return dir + seperator + path; } #ifndef _WIN32 // scan a directory and get all files with input extensions inline std::vector<std::string> get_directory_images(const std::string& path, const std::string& exts) { std::vector<std::string> imgs; struct dirent *entry; DIR *dir = opendir(path.c_str()); if (dir == NULL) { closedir(dir); return imgs; } while ((entry = readdir(dir)) != NULL) { std::string item = entry->d_name; auto ext = strrchr(entry->d_name, '.'); if (!ext || std::string(ext) == "." || std::string(ext) == "..") { continue; } if (exts.find(ext) != std::string::npos) { imgs.push_back(path_join(path, entry->d_name)); } } return imgs; } #else // scan a directory and get all files with input extensions inline std::vector<std::string> get_directory_images(const std::string& path, const std::string& exts) { std::vector<std::string> imgs; for (const auto& item : std::experimental::filesystem::directory_iterator(path)) { auto suffix = item.path().extension().string(); if (exts.find(suffix) != std::string::npos && suffix.size() > 0) { auto fullname = path_join(path, item.path().filename().string()); imgs.push_back(item.path().string()); } } return imgs; } #endif // normalize and HWC_BGR -> CHW_RGB inline void normalize(cv::Mat& im, float* data, std::vector<float>& fmean, std::vector<float>& fstd) { int rh = im.rows; int rw = im.cols; int rc = im.channels(); double normf = (double)1.0 / 255.0; #pragma omp parallel for for (int h = 0; h < rh; ++h) { const uchar* ptr = im.ptr<uchar>(h); int im_index = 0; for (int w = 0; w < rw; ++w) { for (int c = 0; c < rc; ++c) { int top_index = (c * rh + h) * rw + w; float pixel = static_cast<float>(ptr[im_index++]); pixel = (pixel * normf - fmean[c]) / fstd[c]; data[top_index] = pixel; } } } } // argmax inline void argmax(float* out, std::vector<int>& shape, std::vector<uchar>& mask, std::vector<uchar>& scoremap) { int out_img_len = shape[1] * shape[2]; int blob_out_len = out_img_len * shape[0]; /* Eigen::TensorMap<Eigen::Tensor<float, 3>> out_3d(out, shape[0], shape[1], shape[2]); Eigen::Tensor<Eigen::DenseIndex, 2> argmax = out_3d.argmax(0); */ float max_value = -1; int label = 0; #pragma omp parallel private(label) for (int i = 0; i < out_img_len; ++i) { max_value = -1; label = 0; #pragma omp for reduction(max : max_value) for (int j = 0; j < shape[0]; ++j) { int index = i + j * out_img_len; if (index >= blob_out_len) { continue; } float value = out[index]; if (value > max_value) { max_value = value; label = j; } } if (label == 0) max_value = 0; mask[i] = uchar(label); scoremap[i] = uchar(max_value * 255); } } } }
graphCSR.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : graphCSR.c // Create : 2019-06-29 12:31:24 // Revise : 2019-09-28 15:36:13 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <err.h> #include <string.h> #include "myMalloc.h" #include "timer.h" #include "graphConfig.h" #include "edgeList.h" #include "sortRun.h" #include "vertex.h" #include "graphCSR.h" #include "reorder.h" //edgelist prerpcessing // #include "countsort.h" // #include "radixsort.h" void graphCSRFree (struct GraphCSR *graphCSR) { if(graphCSR) { if(graphCSR->vertices) freeVertexArray(graphCSR->vertices); if(graphCSR->sorted_edges_array) freeEdgeList(graphCSR->sorted_edges_array); #if DIRECTED if(graphCSR->inverse_vertices) freeVertexArray(graphCSR->inverse_vertices); if(graphCSR->inverse_sorted_edges_array) freeEdgeList(graphCSR->inverse_sorted_edges_array); #endif free(graphCSR); } } void graphCSRPrint(struct GraphCSR *graphCSR) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "GraphCSR Properties"); printf(" -----------------------------------------------------\n"); #if WEIGHTED printf("| %-51s | \n", "WEIGHTED"); printf("| %-51s | \n", "MAX WEIGHT"); printf("| %-51f | \n", graphCSR->max_weight); #else printf("| %-51s | \n", "UN-WEIGHTED"); #endif #if DIRECTED printf("| %-51s | \n", "DIRECTED"); #else printf("| %-51s | \n", "UN-DIRECTED"); #endif printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Average Degree (D)"); printf("| %-51u | \n", graphCSR->avg_degree); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Number of Vertices (V)"); printf("| %-51u | \n", graphCSR->num_vertices); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Number of Edges (E)"); printf("| %-51u | \n", graphCSR->num_edges); printf(" -----------------------------------------------------\n"); vertexArrayMaxOutdegree(graphCSR->vertices, graphCSR->num_vertices); #if DIRECTED vertexArrayMaxInDegree(graphCSR->inverse_vertices, graphCSR->num_vertices); #endif } struct GraphCSR *graphCSRNew(uint32_t V, uint32_t E, uint8_t inverse) { struct GraphCSR *graphCSR = (struct GraphCSR *) my_malloc( sizeof(struct GraphCSR)); graphCSR->num_vertices = V; graphCSR->num_edges = E; graphCSR->avg_degree = E / V; graphCSR->sorted_edges_array = NULL; // sorted edge array #if DIRECTED graphCSR->inverse_sorted_edges_array = NULL; // sorted edge array #endif #if WEIGHTED graphCSR->max_weight = 0; #endif graphCSR->vertices = newVertexArray(V); #if DIRECTED if (inverse) { graphCSR->inverse_vertices = newVertexArray(V); } #endif return graphCSR; } struct GraphCSR *graphCSRAssignEdgeList (struct GraphCSR *graphCSR, struct EdgeList *edgeList, uint8_t inverse) { #if DIRECTED if(inverse) graphCSR->inverse_sorted_edges_array = edgeList; else graphCSR->sorted_edges_array = edgeList; #else graphCSR->sorted_edges_array = edgeList; #endif #if WEIGHTED graphCSR->max_weight = edgeList->max_weight; #endif return mapVerticesWithInOutDegree (graphCSR, inverse); } struct GraphCSR *graphCSRPreProcessingStep (struct Arguments *arguments) { struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); Start(timer); struct EdgeList *edgeList = readEdgeListsbin(arguments->fnameb, 0, arguments->symmetric, arguments->weighted); // read edglist from binary file Stop(timer); // edgeListPrint(edgeList); graphCSRPrintMessageWithtime("Read Edge List From File (Seconds)", Seconds(timer)); edgeList = sortRunAlgorithms(edgeList, arguments->sort); if(arguments->dflag) { Start(timer); edgeList = removeDulpicatesSelfLoopEdges(edgeList); Stop(timer); graphCSRPrintMessageWithtime("Removing duplicate edges (Seconds)", Seconds(timer)); } if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } arguments->lmode = arguments->lmode_l3; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } if(arguments->mmode) edgeList = maskGraphProcess(edgeList, arguments); #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 0); #endif // edgeListPrint(edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, edgeList, 0); Stop(timer); graphCSRPrintMessageWithtime("Mappign Vertices to CSR (Seconds)", Seconds(timer)); #if DIRECTED Start(timer); struct EdgeList *inverse_edgeList = readEdgeListsMem(edgeList, 1, 0, 0); // read edglist from memory since we pre loaded it Stop(timer); graphCSRPrintMessageWithtime("Read Inverse Edge List From Memory (Seconds)", Seconds(timer)); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, inverse_edgeList, 1); Stop(timer); graphCSRPrintMessageWithtime("Process In/Out degrees of Inverse Nodes (Seconds)", Seconds(timer)); #endif graphCSRPrint(graphCSR); free(timer); return graphCSR; } struct GraphCSR *graphCSRPreProcessingStepDualOrder (struct Arguments *arguments) { struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); Start(timer); struct EdgeList *edgeList = readEdgeListsbin(arguments->fnameb, 0, arguments->symmetric, arguments->weighted); // read edglist from binary file Stop(timer); // edgeListPrint(edgeList); graphCSRPrintMessageWithtime("Read Edge List From File (Seconds)", Seconds(timer)); edgeList = sortRunAlgorithms(edgeList, arguments->sort); if(arguments->dflag) { Start(timer); edgeList = removeDulpicatesSelfLoopEdges(edgeList); Stop(timer); graphCSRPrintMessageWithtime("Removing duplicate edges (Seconds)", Seconds(timer)); } if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 0); #endif #if DIRECTED Start(timer); struct EdgeList *inverse_edgeList = readEdgeListsMem(edgeList, 1, 0, 0); // read edglist from memory since we pre loaded it Stop(timer); graphCSRPrintMessageWithtime("Read Inverse Edge List From Memory (Seconds)", Seconds(timer)); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { inverse_edgeList = reorderGraphProcess(inverse_edgeList, arguments); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); } // edgeListPrint(inverse_edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, inverse_edgeList, 1); Stop(timer); graphCSRPrintMessageWithtime("Process In/Out degrees of Inverse Nodes (Seconds)", Seconds(timer)); #endif // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } // edgeListPrint(edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, edgeList, 0); graphCSRVertexLabelRemappingDualOrder (graphCSR); Stop(timer); graphCSRPrintMessageWithtime("Mappign Vertices to CSR (Seconds)", Seconds(timer)); // edgeListPrint(edgeList); graphCSRPrint(graphCSR); free(timer); return graphCSR; } void graphCSRVertexLabelRemappingDualOrder (struct GraphCSR *graphCSR) { uint32_t *label_array_el = NULL; uint32_t *label_array_iel = NULL; uint32_t *inverse_label_array_el = NULL; uint32_t *inverse_label_array_iel = NULL; uint32_t num_vertices = graphCSR->num_vertices; uint32_t v; #if DIRECTED inverse_label_array_iel = graphCSR->inverse_sorted_edges_array->inverse_label_array; label_array_iel = graphCSR->inverse_sorted_edges_array->label_array; #else inverse_label_array_iel = graphCSR->sorted_edges_array->inverse_label_array; label_array_iel = graphCSR->sorted_edges_array->label_array; #endif inverse_label_array_el = graphCSR->sorted_edges_array->inverse_label_array; label_array_el = graphCSR->sorted_edges_array->label_array; #pragma omp parallel for for (v = 0; v < num_vertices; ++v) { uint32_t u = label_array_el[v]; uint32_t t = label_array_iel[v]; inverse_label_array_el[u] = t; } #if DIRECTED #pragma omp parallel for for (v = 0; v < num_vertices; ++v) { uint32_t u = label_array_el[v]; uint32_t t = label_array_iel[v]; inverse_label_array_iel[t] = u; } #endif } void writeToBinFileGraphCSR (const char *fname, struct GraphCSR *graphCSR) { FILE *pBinary; uint32_t vertex_id; char *fname_txt = (char *) malloc((strlen(fname) + 10) * sizeof(char)); char *fname_bin = (char *) malloc((strlen(fname) + 10) * sizeof(char)); fname_txt = strcpy (fname_txt, fname); fname_bin = strcat (fname_txt, ".csr"); pBinary = fopen(fname_bin, "wb"); if (pBinary == NULL) { err(1, "open: %s", fname_bin); return ; } fwrite(&(graphCSR->num_edges), sizeof (graphCSR->num_edges), 1, pBinary); fwrite(&(graphCSR->num_vertices), sizeof (graphCSR->num_vertices), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->max_weight), sizeof (graphCSR->max_weight), 1, pBinary); #endif for(vertex_id = 0; vertex_id < graphCSR->num_vertices ; vertex_id++) { fwrite(&(graphCSR->vertices->out_degree[vertex_id]), sizeof (graphCSR->vertices->out_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->vertices->in_degree[vertex_id]), sizeof (graphCSR->vertices->in_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->vertices->edges_idx[vertex_id]), sizeof (graphCSR->vertices->edges_idx[vertex_id]), 1, pBinary); #if DIRECTED if(graphCSR->inverse_vertices) { fwrite(&(graphCSR->inverse_vertices->out_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->out_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_vertices->in_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->in_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_vertices->edges_idx[vertex_id]), sizeof (graphCSR->inverse_vertices->edges_idx[vertex_id]), 1, pBinary); } #endif } for(vertex_id = 0; vertex_id < graphCSR->num_edges ; vertex_id++) { fwrite(&(graphCSR->sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); fwrite(&(graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif #if DIRECTED if(graphCSR->inverse_vertices) { fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif } #endif } fclose(pBinary); } struct GraphCSR *readFromBinFileGraphCSR (const char *fname) { FILE *pBinary; uint32_t vertex_id; uint32_t num_vertices; uint32_t num_edges; #if WEIGHTED float max_weight; #endif size_t ret; pBinary = fopen(fname, "rb"); if (pBinary == NULL) { err(1, "open: %s", fname); return NULL; } ret = fread(&num_edges, sizeof(num_edges), 1, pBinary); ret = fread(&num_vertices, sizeof(num_vertices), 1, pBinary); #if WEIGHTED ret = fread(&max_weight, sizeof(max_weight), 1, pBinary); #endif #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(num_vertices, num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(num_vertices, num_edges, 0); #endif #if WEIGHTED graphCSR->max_weight = max_weight; #endif struct EdgeList *sorted_edges_array = newEdgeList(num_edges); sorted_edges_array->num_vertices = num_vertices; #if WEIGHTED sorted_edges_array->max_weight = max_weight; #endif graphCSR->sorted_edges_array = sorted_edges_array; #if DIRECTED struct EdgeList *inverse_sorted_edges_array = newEdgeList(num_edges); inverse_sorted_edges_array->num_vertices = num_vertices; #if WEIGHTED inverse_sorted_edges_array->max_weight = max_weight; #endif graphCSR->inverse_sorted_edges_array = inverse_sorted_edges_array; #endif for(vertex_id = 0; vertex_id < graphCSR->num_vertices ; vertex_id++) { ret = fread(&(graphCSR->vertices->out_degree[vertex_id]), sizeof (graphCSR->vertices->out_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->vertices->in_degree[vertex_id]), sizeof (graphCSR->vertices->in_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->vertices->edges_idx[vertex_id]), sizeof (graphCSR->vertices->edges_idx[vertex_id]), 1, pBinary); #if DIRECTED if(graphCSR->inverse_vertices) { ret = fread(&(graphCSR->inverse_vertices->out_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->out_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_vertices->in_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->in_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_vertices->edges_idx[vertex_id]), sizeof (graphCSR->inverse_vertices->edges_idx[vertex_id]), 1, pBinary); } #endif } for(vertex_id = 0; vertex_id < graphCSR->num_edges ; vertex_id++) { ret = fread(&(graphCSR->sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED ret = fread(&(graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif #if DIRECTED if(graphCSR->inverse_vertices) { ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif } #endif } if(ret) { graphCSRPrint(graphCSR); } fclose(pBinary); return graphCSR; } void graphCSRPrintMessageWithtime(const char *msg, double time) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", msg); printf(" -----------------------------------------------------\n"); printf("| %-51f | \n", time); printf(" -----------------------------------------------------\n"); }
hermm_c_dia_u_lo_col.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> alphasparse_status_t ONAME(const ALPHA_Complex alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Complex *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Complex beta, ALPHA_Complex *y, const ALPHA_INT ldy) { ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT c = 0; c < columns; c++) for (ALPHA_INT r = 0; r < mat->rows; r++){ alpha_mul(y[index2(c,r,ldy)],y[index2(c,r,ldy)],beta); alpha_madde(y[index2(c,r,ldy)],x[index2(c,r,ldx)],alpha); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT cc = 0; cc < columns; ++cc) { ALPHA_Complex* Y = &y[index2(cc,0,ldy)]; const ALPHA_Complex* X = &x[index2(cc,0,ldx)]; for(ALPHA_INT di = 0; di < mat->ndiag;++di){ ALPHA_INT d = mat->distance[di]; if(d < 0){ ALPHA_INT ars = alpha_max(0,-d); ALPHA_INT acs = alpha_max(0,d); ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs); for(ALPHA_INT i = 0; i < an; ++i){ ALPHA_INT ar = ars + i; ALPHA_INT ac = acs + i; ALPHA_Complex val,val_c; alpha_mul(val,mat->values[index2(di,ar,mat->lval)],alpha); alpha_mul_2c(val_c,mat->values[index2(di,ar,mat->lval)],alpha); alpha_madde(Y[ar],val,X[ac]); alpha_madde(Y[ac],val_c,X[ar]); } } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
AI_model4.c
#include"AI.h" #include <omp.h> #include <time.h> #include <stdio.h> //#define CHECK_SCORE #define MAX_STEP 4 #define MAX_NODES_2_COMPUTE 4000000 #define MAX_TASK_SIZE 6 //This is for model4 int computed_nodes; //computed_task_size=-resized_x+8 int linear_rearrange(int score, float range, int minScore){ int computed_task_size=-(score-minScore)/range*MAX_TASK_SIZE+MAX_TASK_SIZE; return MIN(MAX(computed_task_size,1),MAX_TASK_SIZE); } //the simulation function for the branches in the searching tree int ai_model4_simulate(GameState *gameState, Player *player, int task_size, int depth) { #pragma omp critical computed_nodes++; if(computed_nodes>=MAX_NODES_2_COMPUTE||depth<=0) return ai_sum_scores(gameState,player); int MaxScore=-60000,MinScore=60000; int playerTurn=gameState->playerTurn; int total_num_moves=0; vector MovesStart,MovesEnd; vector_init(&MovesStart); vector_init(&MovesEnd); int cnt=0; for(int i=0;i<64;i++) { vector CurLegalMoves=env_get_legal_moves(gameState,player,i); cnt=CurLegalMoves.count; if(cnt>0){ vector_cat(&MovesEnd,&CurLegalMoves); for(int j=0;j<cnt;j++) vector_add(&MovesStart,i); } vector_free(&CurLegalMoves); total_num_moves+=cnt; } assert(MovesStart.count==MovesEnd.count); int *Scores=malloc(sizeof(int)*total_num_moves); GameState *simulation=malloc(sizeof(GameState)*total_num_moves); int num_blocks=total_num_moves/task_size; for(int i=0;i<num_blocks;i++){ #pragma omp task shared(Scores,playerTurn) { int id=i*task_size; for(int j=0;j<task_size;j++) { if(id+j>=total_num_moves)break; simulation[id+j]=env_copy_State(gameState); env_play(&simulation[id+j],player,vector_get(&MovesStart,id+j),vector_get(&MovesEnd,id+j)); Scores[id+j]=player->color*ai_sum_scores(&simulation[id+j],player); } } } #pragma omp taskwait for(int i=0;i<total_num_moves;i++){ MaxScore=MAX(MaxScore,Scores[i]); MinScore=MIN(MinScore,Scores[i]); } float range=MaxScore-MinScore; for(int i=0;i<num_blocks;i++){ #pragma omp task shared(Scores) { int id=i*task_size; for(int j=0;j<task_size;j++) { if(id+j>=total_num_moves)break; int score=playerTurn*ai_model4_simulate(&simulation[i],player, linear_rearrange(Scores[i],range,MinScore),depth-1); Scores[i]=score; env_free_state(&simulation[i]); } } } #pragma omp taskwait free(simulation); for(int i=0;i<total_num_moves;i++){ MaxScore=MAX(MaxScore,Scores[i]); } vector_free(&MovesStart); vector_free(&MovesEnd); free(Scores); return MaxScore*playerTurn; } //the play function for the root in the searching tree, return the quit from check_end int ai_model4_play(GameState *gameState, Player *player, int maxStep) { computed_nodes=0; int check_end=env_check_end(gameState,player); if(check_end!=0) { env_free_container(gameState); return check_end; } int MaxScore=-60000; int score; // vector MovesStart,MovesEnd,Scores; // vector_init(&BestMovesID); // vector_init(&MovesStart); // vector_init(&MovesEnd); // vector_init(&Scores); int container_size=gameState->moves_vector_cnt; int total_num_moves=0; int *accu_container_size_arr=malloc(sizeof(int)*gameState->moves_vector_cnt); for(int i=0;i<container_size;i++){ total_num_moves+=gameState->container[i].legal_moves.count; if(i==0)accu_container_size_arr[0]=0; else accu_container_size_arr[i]=accu_container_size_arr[i-1]+gameState->container[i-1].legal_moves.count; } int *MovesStart=malloc(sizeof(int)*total_num_moves); int *MovesEnd=malloc(sizeof(int)*total_num_moves); int *Scores=malloc(sizeof(int)*total_num_moves); omp_set_nested(1); omp_set_num_threads(16); for(int i=0;i<container_size;i++) { vector CurLegalMoves=gameState->container[i].legal_moves; int cnt=CurLegalMoves.count; int pos=gameState->container[i].pos; for(int j=0;j<cnt;j++){ MovesStart[accu_container_size_arr[i]+j]=pos; MovesEnd[accu_container_size_arr[i]+j]=vector_get(&CurLegalMoves,j); } } // assert(MovesStart.count==MovesEnd.count); int playerTurn=gameState->playerTurn; #pragma omp parallel for shared(gameState,player,MovesStart,MovesEnd,Scores,playerTurn) for(int i=0;i<total_num_moves;i++) { GameState simulation=env_copy_State(gameState); env_play(&simulation,player,MovesStart[i],MovesEnd[i]); score=playerTurn*ai_model4_simulate(&simulation,player, 2,maxStep); Scores[i]=score; env_free_state(&simulation); } // printf("Computed Nodes:%d\n",computed_nodes); int BestMovesCnt=0; vector BestMovesID; vector_init(&BestMovesID); if(stack_check_repeated_move(gameState->moves_stack)){ int MaxScoresArr[6]; for(int i=0;i<6;i++)MaxScoresArr[i]=-60000; int MinScoreID,MinScoreArrValue; for(int i=0;i<total_num_moves;i++){ MinScoreArrValue=MaxScoresArr[0]; MinScoreID=0; for(int j=1;j<6;j++){ if(MaxScoresArr[j]<MinScoreArrValue){ MinScoreArrValue=MaxScoresArr[j]; MinScoreID=j; } } MaxScoresArr[MinScoreID]=MAX(MaxScoresArr[MinScoreID],Scores[i]); } for(int i=0;i<total_num_moves;i++){ for(int j=0;j<6;j++){ if(Scores[i]==MaxScoresArr[j]){ vector_add(&BestMovesID,i); BestMovesCnt++; } } } } else{ for(int i=0;i<total_num_moves;i++)MaxScore=MAX(MaxScore,Scores[i]); for(int i=0;i<total_num_moves;i++){ if(Scores[i]==MaxScore){ vector_add(&BestMovesID,i); BestMovesCnt++; } } } int id=vector_get(&BestMovesID,rand()%BestMovesCnt); #ifdef CHECK_SCORE printf("It is %d playing\n",gameState->playerTurn); ai_print_board(gameState); printf("Current Score is %d\n",ai_sum_scores(gameState,player)); #endif env_play(gameState,player,MovesStart[id],MovesEnd[id]); #ifdef CHECK_SCORE printf("The player has decided to move from %d to %d\n",vector_get(&MovesStart,id),vector_get(&MovesEnd,id)); ai_print_board(gameState); printf("After making the move, the score is %d\n",ai_sum_scores(gameState,player)); #endif vector_free(&BestMovesID); free(MovesStart); free(MovesEnd); free(Scores); env_free_container(gameState); return 0; }
GB_binop__times_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__times_fp32 // A.*B function (eWiseMult): GB_AemultB__times_fp32 // A*D function (colscale): GB_AxD__times_fp32 // D*A function (rowscale): GB_DxB__times_fp32 // C+=B function (dense accum): GB_Cdense_accumB__times_fp32 // C+=b function (dense accum): GB_Cdense_accumb__times_fp32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__times_fp32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__times_fp32 // C=scalar+B GB_bind1st__times_fp32 // C=scalar+B' GB_bind1st_tran__times_fp32 // C=A+scalar GB_bind2nd__times_fp32 // C=A'+scalar GB_bind2nd_tran__times_fp32 // C type: float // A type: float // B,b type: float // 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) \ 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 * y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TIMES || GxB_NO_FP32 || GxB_NO_TIMES_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__times_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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 * bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__times_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 * y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (x * aij) ; \ } GrB_Info GB_bind1st_tran__times_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 * y) ; \ } GrB_Info GB_bind2nd_tran__times_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