source
stringlengths
3
92
c
stringlengths
26
2.25M
local_stereo.h
/**@copyright 2016 Horizon-Robotics Inc. All Rights Reserved. * @author Degang Yang (degang.yang@horizon-robotics.com) * * @file local_stereo.h * @brief multi-scale + multi box agggre + disparity propagation */ #ifndef DEEPROB_CV_LOCAL_STEREO_H_ #define DEEPROB_CV_LOCAL_STEREO_H_ #include <nmmintrin.h> #include <vector> #include "utility.h" #include "ctmf.h" #include "geodesic_filtering.h" typedef unsigned char COSTTYPE; typedef unsigned char DISPARITYTYPE; typedef float GUIDANCETYPE; #define RADIUS_CENSUS 4 //#define THRES_CENSUS 20 //#define THRES_AD 20 //#define P_SMOTHNESS 15 #define THRES_ERR_CROSS_CHECK 1 #define DELTA_DISPARITY_RATIO (0.05f) #define DELTA_DISPARITY_MAXIMUM (3) #define RADIUS_MEDIAN 2 #define SIGMA_S (30.f) #define SIGMA_R (18.f) #define WEIGHT_VERTICAL 0.85 //0.85f~1, trick for running KITTI data sets #define BASE_SPECKLESIZE 70 #define BASE_WIDTH 320 //#define PROFILE_RUNTIME /*V1: fuse two proposals*/ const int radius_x_boxfilter[2] = { 3, 1}; const int radius_y_boxfilter[2] = { 1, 3}; namespace deeprob { namespace cv { class LocalStereo { public: static const int _nr_buffer_int = 4; static const int _downsample_factor = 2; /*default*/ LocalStereo(int width, int height, int nr_planes, int c_guidance, int c_input) : _width(width), _height(height), _nr_planes(nr_planes) , _c_guidance(c_guidance), _c_input(c_input) { _disparity_output = new DISPARITYTYPE[_width*_height]; memset(_disparity_output, 0, sizeof(DISPARITYTYPE)*_width*_height); _disparity_output_buffer = new DISPARITYTYPE[_width*_height]; memset(_disparity_output_buffer, 0, sizeof(DISPARITYTYPE)*_width*_height); _width_high = _width; _height_high = _height; _width /= _downsample_factor; _height /= _downsample_factor; _nr_planes /= _downsample_factor; _cost_vol_buffer = alloc_4<COSTTYPE>(3, _height, _width, _nr_planes, 0); _cost_vol = _cost_vol_buffer[0]; _cost_vol_right = _cost_vol_buffer[1]; _cost_vol_backup = _cost_vol_buffer[2]; //_cost_vol_backup_2 = _cost_vol_buffer[3]; _disparity_buffer = alloc_3<DISPARITYTYPE>(4, _height, _width, 0); _disparity = _disparity_buffer[0]; _disparity_r = _disparity_buffer[1]; _disparity_backup = _disparity_buffer[2]; _disparity_backup_2 = _disparity_buffer[3]; int size = _width *_height; _gray_left = new unsigned char[size]; _gray_right = new unsigned char[size]; _buffer_int = new int[_nr_buffer_int * size]; _buffer_int_0 = _buffer_int; _buffer_int_1 = _buffer_int_0 + size; _buffer_int_2 = _buffer_int_1 + size; _buffer_int_3 = _buffer_int_2 + size; _gf.initialize(SIGMA_S, SIGMA_R, (size_t)_width, (size_t)_height, WEIGHT_VERTICAL); _vol_buffer_f = new GUIDANCETYPE[nr_planes*size]; _d_buffer = new DISPARITYTYPE[size * (_downsample_factor *_downsample_factor + 1)]; #ifdef PROFILE_RUNTIME _timecost_cost = _timecost_proposal = _timecost_propogation = _timecost_upsampling = 0; #endif //_guidance_left = new GUIDANCETYPE[_width*_height]; //_guidance_right = new GUIDANCETYPE[_width*_height]; } ~LocalStereo() { free_4<COSTTYPE>(_cost_vol_buffer); free_3<DISPARITYTYPE>(_disparity_buffer); delete[]_disparity_output; delete[]_disparity_output_buffer; delete[]_gray_left; delete[]_gray_right; delete[]_buffer_int; delete[]_vol_buffer_f; delete[]_d_buffer; //if (_guidance_left != NULL) delete[]_guidance_left; //if (_guidance_right != NULL) delete[]_guidance_right; } /*size should be the same as in constructor function, in low resolution!*/ void setImage(const unsigned char* left, const unsigned char* right, int c) { _left_input = left; _right_input = right; _c_input = c; } void setGuidance(const GUIDANCETYPE* guidance_left, const GUIDANCETYPE* guidance_left_high, const GUIDANCETYPE* guidance_right, int c) { //memcpy(_guidance_left, guidance_left, c*_width*_height); //memcpy(_guidance_right, guidance_right, c*_width*_height); _guidance_left = guidance_left; _guidance_right = guidance_right; _c_guidance = c; _guidance_left_high = guidance_left_high;/*used for upsampling*/ } public: DISPARITYTYPE*** _disparity_buffer, ** _disparity, **_disparity_r, **_disparity_backup, **_disparity_backup_2; DISPARITYTYPE*_disparity_output, *_disparity_output_buffer; /*timecost analysis*/ double _timecost_cost, _timecost_proposal, _timecost_propogation, _timecost_upsampling; private: int _nr_planes, _width, _height, _width_high, _height_high; COSTTYPE**** _cost_vol_buffer, ***_cost_vol, ***_cost_vol_right, ***_cost_vol_backup; const GUIDANCETYPE* _guidance_left, *_guidance_right; const GUIDANCETYPE* _guidance_left_high;/*used for upsampling*/ const unsigned char* _left_input, *_right_input; /*assigned from outside*/ int _c_guidance, _c_input; unsigned char* _gray_left, *_gray_right; int* _buffer_int, *_buffer_int_0, *_buffer_int_1, *_buffer_int_2, *_buffer_int_3; GeodesicFiltering<GUIDANCETYPE> _gf; GUIDANCETYPE* _vol_buffer_f; DISPARITYTYPE* _d_buffer;/*used when upsampling*/ public: void calDisparity();/*on the reference(left) view*/ private: void calMatchingCost(const unsigned char* left, const unsigned char*right, COSTTYPE***cost_vol, int nr_planes, int width, int height); void stereo_flip_cost_vol(COSTTYPE***&cost_vol_right, COSTTYPE***cost_vol, int height, int width, int nr_planes); void calGradient_sobel(int*gradient, unsigned char*gray, int width, int height); void wta(DISPARITYTYPE** disparity, COSTTYPE*** cost_vol); void wta(DISPARITYTYPE** disparity, COSTTYPE*** cost_vol, COSTTYPE* cost_min); void fillHoles(unsigned char* disparity, int width, int height); void speckleFilter(unsigned char* image, int width, int height, const int maxSpeckleSize, const int maxDifference = 3); void boxfilter(COSTTYPE* pSrc, COSTTYPE* pDst, int radius_x, int radius_y, int w, int h, int c); void calCensusTransform(unsigned char* gray, int* census, int width, int height, int r_x, int r_y) { #pragma omp parallel for for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { int census_code = 0, gray_center = gray[y*width + x]; int y_min = y - r_y, y_max = y + r_y, x_min = x - r_x, x_max = x + r_x; for (int y_ = y_min; y_ <= y_max; y_ += 2) for (int x_ = x_min; x_ <= x_max; x_ += 2) /*sparsely sampling*/ //for (int y_ = y_min; y_ <= y_max; ++y_) for (int x_ = x_min; x_ <= x_max; ++x_) { if (y_ >= 0 && y_ < height&&x_ >= 0 && x_ < width&&gray[y_*width + x_] >= gray_center) { census_code += 1; } census_code = (census_code << 1); } census[y*width + x] = census_code; } } } inline int calHammingDistance(int leftCencusCode, int rightCensusCode) { return static_cast<int>(_mm_popcnt_u32(static_cast<size_t>(leftCencusCode^rightCensusCode))); } void genProposalLR(DISPARITYTYPE** disparity_left, DISPARITYTYPE** disparity_right); void fuseProposals(std::vector<DISPARITYTYPE**>& proposals, DISPARITYTYPE** disparity); void fuseProposals(std::vector<DISPARITYTYPE**>& proposals, DISPARITYTYPE** disparity, COSTTYPE* cost_min); void buildNewVol(DISPARITYTYPE** disparity, int nr_planes, COSTTYPE***cost_vol); public: void upsamplingDisparity(DISPARITYTYPE** disparity, DISPARITYTYPE* disparity_result/*allocated from outside*/, int width_high, int height_high, int upsamling_factor, const GUIDANCETYPE* guidance, int c_guidance/*, int step = 5, int n = 5*/); }; } // namespace cv } // namespace deeprob #endif // DEEPROB_CV_LOCAL_STEREO_H_
Renderer.h
#pragma once #include <iostream> #include <cstdint> #include "Scene.h" #include "File.h" //class RenderTarget //{ //public: // RenderTarget(uint32_t width, uint32_t height) // : width(width) // , height(height) // { // image = new Color[width * height]; // } // // ~RenderTarget() // { // delete[] image; // } // //private: // Color* image; // uint32_t width; // uint32_t height; //}; class Renderer { public: Renderer(int width, int height, int subPixelSampleNum, int superSampleNum) : width(width) , height(height) , subPixelSampleNum(subPixelSampleNum) , superSampleNum(superSampleNum) { } void SetScene(ScenePtr scene) { this->scene = scene; } void Render() { auto camera = scene->GetCamera(); const double aspectRatio = double(width) / double(height); // イメージセンサー // ワールド座標系上にスクリーンを配置 const double screenWidth = camera->GetFocalPlane() * aspectRatio; const double screenHeight = camera->GetFocalPlane(); const Vector3 screenX = camera->GetRightDirection() * screenWidth; const Vector3 screenY = camera->GetUpDirection() * screenHeight; const Vector3 screenCenter = camera->GetPosition() + camera->GetDirection() * camera->GetFocalLength(); Color *image = new Color[width * height]; std::cout << width << "x" << height << " " << subPixelSampleNum * (superSampleNum * superSampleNum) << " spp" << std::endl; #pragma omp parallel for schedule(dynamic, 1) num_threads(8) for (auto y = 0; y < height; ++y) { std::cerr << "Rendering (y = " << y << ") " << (100.0 * y / (height - 1)) << "%" << std::endl; Random random(y + 1); for (auto x = 0; x < width; ++x) { const int image_index = (height - y - 1) * width + x; Color accumlator = Color(); for (auto sy = 0; sy < superSampleNum; ++sy) { for (auto sx = 0; sx < superSampleNum; ++sx) { // 一つのサブピクセルあたり複数回サンプリングする for (int s = 0; s < subPixelSampleNum; s++) { const double ratio = (1.0 / superSampleNum); const double rx = sx * ratio + ratio / 2.0; // (サブピクセル位置) + (サブピクセル中心へのオフセット) const double ry = sy * ratio + ratio / 2.0; // -0.5は中心基準になっているため Vector3 screenPos = screenCenter + (screenX * ((x + rx) / width - 0.5)) + (screenY * ((y + ry) / height - 0.5)); Vector3 rayDir = Normalize(screenPos - camera->GetPosition()); Ray ray = Ray(camera->GetPosition(), rayDir); //Color col = radiance(ray, scene, random, 0); Color col = radiance(ray, random, 0); accumlator += (col / subPixelSampleNum / (superSampleNum * superSampleNum)); } } } image[image_index] += accumlator; } } File::Save(std::string("result"), image, width, height); delete[] image; } private: Color radiance(Ray& ray, Random& rand, uint32_t depth) { HitPoint hitpoint; if (!scene->Intersect(ray, hitpoint)) { auto& iblTexture = scene->GetIblTexture(); if (iblTexture == nullptr) return Color(); double phi = atan2(ray.direction.z, ray.direction.x); //double phi = atan2(ray.direction.x, ray.direction.z); double theta = asin(ray.direction.y); double u = 1.0 - (phi + kPI) / kPI2; double v = (theta + kPI / 2.0) / kPI; return iblTexture->value(u, v, hitpoint.normal); //float t = 0.5 * (-ray.direction.y + 1.0); //return Color(1.0, 1.0, 1.0) * (1.0 - t) + Color(0.5, 0.7, 1.0) * t; //return Color(); } const Vector3 normal = Dot(hitpoint.normal, ray.direction) < 0.0 ? hitpoint.normal : (-hitpoint.normal); // 交差位置の法線(物体からのレイの入出を考慮) HitablePtr hitObject = hitpoint.object; // 色の反射率最大のものを得る。ロシアンルーレットで使う。 // ロシアンルーレットの閾値は任意だが色の反射率等を使うとより良い。 auto& albedo = hitObject->GetMaterial()->albedo->value(hitpoint.u, hitpoint.v, hitpoint.position); double russianRouletteProb = std::max(albedo.x, std::max(albedo.y, albedo.z)); // 反射回数が一定以上になったらロシアンルーレットの確率を急上昇させる。(スタックオーバーフロー対策) if (depth > kDepthLimit) { russianRouletteProb *= pow(0.5, depth - kDepthLimit); } // ロシアンルーレットを実行し追跡を打ち切るかどうかを判断する。 // ただしDepth回の追跡は保障する。 if (depth > kDepth) { if (rand.Next() >= russianRouletteProb) { return hitObject->GetMaterial()->emission; //float t = 0.5 * (-ray.direction.y + 1.0); //return Color(1.0, 1.0, 1.0) * (1.0 - t) + Color(0.5, 0.7, 1.0) * t; } } else { russianRouletteProb = 1.0; } return hitObject->GetMaterial()->GetRadiance(ray, hitpoint, rand, depth, russianRouletteProb, [&](Vector3 dir, Color weight) { Color incomingRadiance = radiance(Ray(hitpoint.position, dir), rand, depth + 1); //Color weight = now_object->material->albedo / russianRouletteProb; return hitObject->GetMaterial()->emission + weight * incomingRadiance; }); //Color incomingRadiance = color(Ray(hitpoint.position, dir), objectList, rand, depth + 1) ; //Color weight = now_object->material->albedo / russianRouletteProb; // レンダリング方程式に対するモンテカルロ積分を考えると、outgoing_radiance = weight * incoming_radiance。 // ここで、weight = (ρ/π) * cosθ / pdf(ω) / R になる。 // ρ/πは完全拡散面のBRDFでρは反射率、cosθはレンダリング方程式におけるコサイン項、pdf(ω)はサンプリング方向についての確率密度関数。 // Rはロシアンルーレットの確率。 // 今、コサイン項に比例した確率密度関数によるサンプリングを行っているため、pdf(ω) = cosθ/π // よって、weight = ρ/ R。 //return now_object->material->emission + weight * incomingRadiance; } private: int width; int height; int subPixelSampleNum; int superSampleNum; ScenePtr scene; };
kernels.c
#include "trace.h" #include "common.h" #include <math.h> #include <omp.h> #include <stdlib.h> void panel(double *P, int k, info_type info){ int m, ld, err, np, i; i = k*info.B; np = info.B; m = info.N-i; ld = info.N; #if defined(DBG) printf("%2d -- panel : %d\n",omp_get_thread_num(),k); #endif trace_event_start(PNL); dgetrf_(&m, &np, P+i, &ld, info.ipiv+i, &err); trace_event_stop(PNL); } void update(double *P, double *U, int k, int j, info_type info){ int m, mu, nu, np, ld, err, i; char NoTran = 'N', Lower='L', Unit='U', Left='L'; int IONE=1, IMONE=-1, IZERO=0; double DONE=(double)1.0, DMONE=-1.0, DZERO=0.0; i = k*info.B; np = info.B; nu = info.B; m = info.N-i; mu = m-np; ld = info.N; #if defined(DBG) printf("%2d -- update: %d %d\n",omp_get_thread_num(),k,j); #endif trace_event_start(UPD); dlaswp_(&nu, U+i, &ld, &IONE, &np, info.ipiv+i, &IONE); dtrsm_ (&Left, &Lower, &NoTran, &Unit, &np, &nu, &DONE, P+i, &ld, U+i, &ld); dgemm_ (&NoTran, &NoTran, &mu, &nu, &np, &DMONE, P+i+np, &ld, U+i, &ld, &DONE, U+i+np, &ld); trace_event_stop(UPD); return; } void backperm(Matrix A, info_type info){ int i, j, ld, ipb, ipo; int IONE=1; ld = info.N; trace_event_start(END); for(i=info.B; i<info.N; i+=info.B){ for(j=i; j<info.N; j++) info.ipiv[j]+=info.B; ipo = i+1; ipb = i+info.B; #pragma omp parallel for for(j=0; j<i/info.B; j+=1) dlaswp_(&info.B, A[j], &ld, &ipo, &ipb, info.ipiv, &IONE); } trace_event_stop(END); return; } void checkres(double *A, double *Acpy, info_type info){ int ISEED[4] = {0,0,0,3}; int IONE=1; char NoTran = 'N'; double DONE=1.0, DMONE=-1.0; double *x, *b; int err; double flops, nrm2, nrmf; x = (double *)malloc(info.N*sizeof(double)); b = (double *)malloc(info.N*sizeof(double)); dlarnv_(&IONE, ISEED, &info.N, b); memcpy( x, b, info.N*sizeof(double) ); dgetrs_(&NoTran, &(info.N), &IONE, A, &(info.N), info.ipiv, x, &(info.N), &err); dgemv_(&NoTran, &info.N, &info.N, &DONE, Acpy, &info.N, x, &IONE, &DMONE, b, &IONE); nrm2 = dnrm2_c(info.N, b, IONE); nrmf = dnrmf_c(info.N, info.N, Acpy, info.N); printf("Residual norm: %e\n",sqrt(info.N)*nrm2/nrmf); free(x); free(b); return; }
thdat105.c
/* * 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 this list * of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce this * list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include <config.h> #include <stdlib.h> #include <thtk/thtk.h> #include "thcrypt105.h" #include "thdat.h" #include "util.h" typedef struct { uint16_t entry_count; uint32_t size; } th105_archive_header_t; static int th105_open( thdat_t* thdat, thtk_error_t** error) { th105_archive_header_t header; uint16_t entry_count; uint32_t header_size; if (thtk_io_read(thdat->stream, &entry_count, 2, error) == -1) return 0; if (thtk_io_read(thdat->stream, &header_size, 4, error) == -1) return 0; header.entry_count = entry_count; header.size = header_size; unsigned char* header_buf = malloc(header_size); if (thtk_io_read(thdat->stream, header_buf, header_size, error) != header_size) return 0; th_crypt105_list(header_buf, header_size, 0xc5, 0x83, 0x53); thdat->entry_count = entry_count; thdat->entries = calloc(entry_count, sizeof(thdat_entry_t)); if (header.entry_count) { unsigned char* ptr = header_buf; for (uint16_t i = 0; i < entry_count; ++i) { thdat_entry_t* entry = thdat->entries + i; thdat_entry_init(entry); entry->offset = *((uint32_t*)ptr); ptr += 4; entry->size = *((uint32_t*)ptr); ptr += 4; // zsize and extra are not used. unsigned char name_length = *(ptr++); strncpy(entry->name, (char*)ptr, name_length); ptr += name_length; } } free(header_buf); return 1; } static void th105_decrypt_data( thdat_t* archive, thdat_entry_t* entry, unsigned char* data) { th_crypt105_file(data, entry->size, entry->offset); } static ssize_t th105_read( thdat_t* thdat, int entry_index, thtk_io_t* output, thtk_error_t** error) { thdat_entry_t* entry = thdat->entries + entry_index; unsigned char* data = malloc(entry->size); int failed = 0; #pragma omp critical { failed = (thtk_io_seek(thdat->stream, entry->offset, SEEK_SET, error) == -1) || (thtk_io_read(thdat->stream, data, entry->size, error) != entry->size); } if (failed) return -1; th105_decrypt_data(thdat, entry, data); if (thtk_io_write(output, data, entry->size, error) == -1) return -1; free(data); return 1; } static int th105_create( thdat_t* thdat, thtk_error_t** error) { // entry list is given off_t size = 6; unsigned int i; for (i = 0; i < thdat->entry_count; ++i) { const thdat_entry_t* entry = thdat->entries + i; const size_t namelen = strlen(entry->name); size += 8; // for offset and size size += (1 + namelen); // for name } thdat->offset = size; if (thtk_io_seek(thdat->stream, thdat->offset, SEEK_SET, error) == -1) return 0; return 1; } static void th105_encrypt_data( thdat_t* archive, thdat_entry_t* entry, unsigned char* data) { th_crypt105_file(data, entry->size, archive->offset); } static ssize_t th105_write( thdat_t* thdat, int entry_index, thtk_io_t* input, size_t input_length, thtk_error_t** error) { thdat_entry_t* entry = thdat->entries + entry_index; unsigned char* data; entry->size = input_length; data = malloc(entry->size); if (thtk_io_seek(input, 0, SEEK_SET, error) == -1) return -1; int ret = thtk_io_read(input, data, entry->size, error); if (ret != entry->size) return -1; th105_encrypt_data(thdat, entry, data); int failed = 0; #pragma omp critical { failed = (thtk_io_write(thdat->stream, data, entry->size, error) != entry->size); if (!failed) { entry->offset = thdat->offset; thdat->offset += entry->size; } } free(data); if (failed) return -1; return entry->size; } static int th105_close( thdat_t* thdat, thtk_error_t** error) { unsigned char* buffer; unsigned int i; uint16_t entry_count = thdat->entry_count; uint32_t header_size = 0; for (int i = 0; i < entry_count; ++i) { const size_t namelen = strlen(thdat->entries[i].name); header_size += 9 + namelen; } if (header_size == 0) { thtk_error_new(error, "no entries"); return 0; } buffer = malloc(header_size); unsigned char* buffer_ptr = buffer; for (int i = 0; i < entry_count; i++) { uint32_t* buffer_ptr_32 = (uint32_t*) buffer_ptr; const thdat_entry_t* entry = thdat->entries + i; const uint8_t namelen = strlen(entry->name); *(buffer_ptr_32++) = entry->offset; *(buffer_ptr_32++) = entry->size; buffer_ptr = (unsigned char*) buffer_ptr_32; *(buffer_ptr++) = namelen; buffer_ptr = MEMPCPY(buffer_ptr, entry->name, namelen); } th_crypt105_list(buffer, header_size, 0xc5, 0x83, 0x53); if (thtk_io_seek(thdat->stream, 0, SEEK_SET, error) == -1) return 0; if (thtk_io_write(thdat->stream, &entry_count, 2, error) == -1) return 0; if (thtk_io_write(thdat->stream, &header_size, 4, error) == -1) return 0; if (thtk_io_write(thdat->stream, buffer, header_size, error) == -1) return 0; free(buffer); return 1; } const thdat_module_t archive_th105 = { 0, th105_open, th105_create, th105_close, th105_read, th105_write };
GB_binop__remainder_fp64.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__remainder_fp64) // A.*B function (eWiseMult): GB (_AemultB_01__remainder_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__remainder_fp64) // A.*B function (eWiseMult): GB (_AemultB_03__remainder_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__remainder_fp64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__remainder_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__remainder_fp64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__remainder_fp64) // C=scalar+B GB (_bind1st__remainder_fp64) // C=scalar+B' GB (_bind1st_tran__remainder_fp64) // C=A+scalar GB (_bind2nd__remainder_fp64) // C=A'+scalar GB (_bind2nd_tran__remainder_fp64) // C type: double // A type: double // B,b type: double // BinaryOp: cij = remainder (aij, bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ double bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double 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 = remainder (x, y) ; // 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_REMAINDER || GxB_NO_FP64 || GxB_NO_REMAINDER_FP64) //------------------------------------------------------------------------------ // 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__remainder_fp64) ( 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__remainder_fp64) ( 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__remainder_fp64) ( 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 double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__remainder_fp64) ( 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__remainder_fp64) ( 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__remainder_fp64) ( 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__remainder_fp64) ( 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__remainder_fp64) ( 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__remainder_fp64) ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) 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 ; double bij = GBX (Bx, p, false) ; Cx [p] = remainder (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__remainder_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; Cx [p] = remainder (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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = remainder (x, aij) ; \ } GrB_Info GB (_bind1st_tran__remainder_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = remainder (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__remainder_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
collapse-1.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ int i, j, k; extern int foo (void); void f1 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) ; /* { dg-error "not enough perfectly nested" } */ { for (j = 0; j < 5; j++) ; } } void f2 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) { { { for (j = 0; j < 5; j++) { } } } } } void f3 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) { int k = foo (); /* { dg-error "not enough perfectly nested" } */ { { for (j = 0; j < 5; j++) { } } } } } void f4 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) { { for (j = 0; j < 5; j++) ; foo (); /* { dg-error "collapsed loops not perfectly nested before" } */ } } } void f5 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) { { for (j = 0; j < 5; j++) ; } foo (); /* { dg-error "collapsed loops not perfectly nested before" } */ } } void f6 (void) { #pragma omp for collapse (2) for (i = 0; i < 5; i++) { { for (j = 0; j < 5; j++) ; } } foo (); }
FunctorsOpenMP.h
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #ifndef vtk_m_cont_openmp_internal_FunctorsOpenMP_h #define vtk_m_cont_openmp_internal_FunctorsOpenMP_h #include <vtkm/cont/openmp/internal/DeviceAdapterTagOpenMP.h> #include <vtkm/cont/internal/FunctorsGeneral.h> #include <vtkm/BinaryOperators.h> #include <vtkm/BinaryPredicates.h> #include <vtkm/Pair.h> #include <vtkm/Types.h> #include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ErrorExecution.h> #include <omp.h> #include <algorithm> #include <type_traits> #include <vector> // Wrap all '#pragma omp ...' calls in this macro so we can disable them in // non-omp builds and avoid a multitude of 'ignoring pragma..." warnings. #ifdef _OPENMP #define VTKM_OPENMP_DIRECTIVE_IMPL(fullDir) _Pragma(#fullDir) #define VTKM_OPENMP_DIRECTIVE(dir) VTKM_OPENMP_DIRECTIVE_IMPL(omp dir) #else // _OPENMP #define VTKM_OPENMP_DIRECTIVE(directive) #endif // _OPENMP // See "OpenMP data sharing" section of // https://www.gnu.org/software/gcc/gcc-9/porting_to.html. OpenMP broke // backwards compatibility regarding const variable handling. // tl;dr, put all const variables accessed from openmp blocks in a // VTKM_OPENMP_SHARED_CONST(var1, var2, ...) macro. This will do The Right Thing // on all gcc. #if defined(__GNUC__) && __GNUC__ >= 9 #define VTKM_OPENMP_SHARED_CONST(...) shared(__VA_ARGS__) #else #define VTKM_OPENMP_SHARED_CONST(...) #endif // When defined, supported type / operator combinations will use the OpenMP // reduction(...) clause. Otherwise, all reductions use the general // implementation with a manual reduction once the threads complete. // I don't know how, but the benchmarks currently perform better without the // specializations. //#define VTKM_OPENMP_USE_NATIVE_REDUCTION namespace vtkm { namespace cont { namespace openmp { constexpr static vtkm::Id CACHE_LINE_SIZE = 64; constexpr static vtkm::Id PAGE_SIZE = 4096; // Returns ceil(num/den) for integral types template <typename T> static constexpr T CeilDivide(const T& numerator, const T& denominator) { return (numerator + denominator - 1) / denominator; } // Computes the number of values per chunk. Note that numChunks + chunkSize may // exceed numVals, so be sure to check upper limits. static void ComputeChunkSize(const vtkm::Id numVals, const vtkm::Id numThreads, const vtkm::Id chunksPerThread, const vtkm::Id bytesPerValue, vtkm::Id& numChunks, vtkm::Id& valuesPerChunk) { // try to evenly distribute pages across chunks: const vtkm::Id bytesIn = numVals * bytesPerValue; const vtkm::Id pagesIn = CeilDivide(bytesIn, PAGE_SIZE); // If we don't have enough pages to honor chunksPerThread, ignore it: numChunks = (pagesIn > numThreads * chunksPerThread) ? numThreads * chunksPerThread : numThreads; const vtkm::Id pagesPerChunk = CeilDivide(pagesIn, numChunks); valuesPerChunk = CeilDivide(pagesPerChunk * PAGE_SIZE, bytesPerValue); } template <typename T, typename U> static void DoCopy(T src, U dst, vtkm::Id numVals, std::true_type) { if (numVals) { std::copy(src, src + numVals, dst); } } // Don't use std::copy when type conversion is required because MSVC. template <typename InIterT, typename OutIterT> static void DoCopy(InIterT inIter, OutIterT outIter, vtkm::Id numVals, std::false_type) { using ValueType = typename std::iterator_traits<OutIterT>::value_type; for (vtkm::Id i = 0; i < numVals; ++i) { *(outIter++) = static_cast<ValueType>(*(inIter++)); } } template <typename InIterT, typename OutIterT> static void DoCopy(InIterT inIter, OutIterT outIter, vtkm::Id numVals) { using InValueType = typename std::iterator_traits<InIterT>::value_type; using OutValueType = typename std::iterator_traits<OutIterT>::value_type; DoCopy(inIter, outIter, numVals, std::is_same<InValueType, OutValueType>()); } template <typename InPortalT, typename OutPortalT> static void CopyHelper(InPortalT inPortal, OutPortalT outPortal, vtkm::Id inStart, vtkm::Id outStart, vtkm::Id numVals) { using InValueT = typename InPortalT::ValueType; using OutValueT = typename OutPortalT::ValueType; constexpr auto isSame = std::is_same<InValueT, OutValueT>(); auto inIter = vtkm::cont::ArrayPortalToIteratorBegin(inPortal) + inStart; auto outIter = vtkm::cont::ArrayPortalToIteratorBegin(outPortal) + outStart; vtkm::Id valuesPerChunk; VTKM_OPENMP_DIRECTIVE(parallel default(none) shared(inIter, outIter, valuesPerChunk, numVals)) { VTKM_OPENMP_DIRECTIVE(single) { // Evenly distribute full pages to all threads. We manually chunk the // data here so that we can exploit std::copy's memmove optimizations. vtkm::Id numChunks; ComputeChunkSize( numVals, omp_get_num_threads(), 8, sizeof(InValueT), numChunks, valuesPerChunk); } VTKM_OPENMP_DIRECTIVE(for schedule(static)) for (vtkm::Id i = 0; i < numVals; i += valuesPerChunk) { vtkm::Id chunkSize = std::min(numVals - i, valuesPerChunk); DoCopy(inIter + i, outIter + i, chunkSize, isSame); } } } struct CopyIfHelper { vtkm::Id NumValues; vtkm::Id NumThreads; vtkm::Id ValueSize; vtkm::Id NumChunks; vtkm::Id ChunkSize; std::vector<vtkm::Id> EndIds; CopyIfHelper() = default; void Initialize(vtkm::Id numValues, vtkm::Id valueSize) { this->NumValues = numValues; this->NumThreads = static_cast<vtkm::Id>(omp_get_num_threads()); this->ValueSize = valueSize; // Evenly distribute pages across the threads. We manually chunk the // data here so that we can exploit std::copy's memmove optimizations. ComputeChunkSize( this->NumValues, this->NumThreads, 8, valueSize, this->NumChunks, this->ChunkSize); this->EndIds.resize(static_cast<std::size_t>(this->NumChunks)); } template <typename InIterT, typename StencilIterT, typename OutIterT, typename PredicateT> void CopyIf(InIterT inIter, StencilIterT stencilIter, OutIterT outIter, PredicateT pred, vtkm::Id chunk) { vtkm::Id startPos = std::min(chunk * this->ChunkSize, this->NumValues); vtkm::Id endPos = std::min((chunk + 1) * this->ChunkSize, this->NumValues); vtkm::Id outPos = startPos; for (vtkm::Id inPos = startPos; inPos < endPos; ++inPos) { if (pred(stencilIter[inPos])) { outIter[outPos++] = inIter[inPos]; } } this->EndIds[static_cast<std::size_t>(chunk)] = outPos; } template <typename OutIterT> vtkm::Id Reduce(OutIterT data) { vtkm::Id endPos = this->EndIds.front(); for (vtkm::Id i = 1; i < this->NumChunks; ++i) { vtkm::Id chunkStart = std::min(i * this->ChunkSize, this->NumValues); vtkm::Id chunkEnd = this->EndIds[static_cast<std::size_t>(i)]; vtkm::Id numValuesToCopy = chunkEnd - chunkStart; if (numValuesToCopy > 0 && chunkStart != endPos) { std::copy(data + chunkStart, data + chunkEnd, data + endPos); } endPos += numValuesToCopy; } return endPos; } }; #ifdef VTKM_OPENMP_USE_NATIVE_REDUCTION // OpenMP only declares reduction operations for primitive types. This utility // detects if a type T is supported. template <typename T> struct OpenMPReductionSupported : std::false_type { }; template <> struct OpenMPReductionSupported<Int8> : std::true_type { }; template <> struct OpenMPReductionSupported<UInt8> : std::true_type { }; template <> struct OpenMPReductionSupported<Int16> : std::true_type { }; template <> struct OpenMPReductionSupported<UInt16> : std::true_type { }; template <> struct OpenMPReductionSupported<Int32> : std::true_type { }; template <> struct OpenMPReductionSupported<UInt32> : std::true_type { }; template <> struct OpenMPReductionSupported<Int64> : std::true_type { }; template <> struct OpenMPReductionSupported<UInt64> : std::true_type { }; template <> struct OpenMPReductionSupported<Float32> : std::true_type { }; template <> struct OpenMPReductionSupported<Float64> : std::true_type { }; #else template <typename T> using OpenMPReductionSupported = std::false_type; #endif // VTKM_OPENMP_USE_NATIVE_REDUCTION struct ReduceHelper { // std::is_integral, but adapted to see through vecs and pairs. template <typename T> struct IsIntegral : public std::is_integral<T> { }; template <typename T, vtkm::IdComponent Size> struct IsIntegral<vtkm::Vec<T, Size>> : public std::is_integral<T> { }; template <typename T, typename U> struct IsIntegral<vtkm::Pair<T, U>> : public std::integral_constant<bool, std::is_integral<T>::value && std::is_integral<U>::value> { }; // Generic implementation: template <typename PortalT, typename ReturnType, typename Functor> static ReturnType Execute(PortalT portal, ReturnType init, Functor functorIn, std::false_type) { internal::WrappedBinaryOperator<ReturnType, Functor> f(functorIn); const vtkm::Id numVals = portal.GetNumberOfValues(); auto data = vtkm::cont::ArrayPortalToIteratorBegin(portal); bool doParallel = false; int numThreads = 0; std::unique_ptr<ReturnType[]> threadData; VTKM_OPENMP_DIRECTIVE(parallel default(none) firstprivate(f) shared( data, doParallel, numThreads, threadData) VTKM_OPENMP_SHARED_CONST(numVals)) { int tid = omp_get_thread_num(); VTKM_OPENMP_DIRECTIVE(single) { numThreads = omp_get_num_threads(); if (numVals >= numThreads * 2) { doParallel = true; threadData.reset(new ReturnType[static_cast<std::size_t>(numThreads)]); } } if (doParallel) { // Static dispatch to unroll non-integral types: const ReturnType localResult = ReduceHelper::DoParallelReduction<ReturnType>( data, numVals, tid, numThreads, f, IsIntegral<ReturnType>{}); threadData[static_cast<std::size_t>(tid)] = localResult; } } // end parallel if (doParallel) { // do the final reduction serially: for (size_t i = 0; i < static_cast<size_t>(numThreads); ++i) { init = f(init, threadData[i]); } } else { // Not enough threads. Do the entire reduction in serial: for (vtkm::Id i = 0; i < numVals; ++i) { init = f(init, data[i]); } } return init; } // non-integer reduction: unroll loop manually. // This gives faster code for floats and non-trivial types. template <typename ReturnType, typename IterType, typename FunctorType> static ReturnType DoParallelReduction(IterType data, vtkm::Id numVals, int tid, int numThreads, FunctorType f, std::false_type /* isIntegral */) { // Use the first (numThreads*2) values for initializing: ReturnType accum = f(data[2 * tid], data[2 * tid + 1]); vtkm::Id i = numThreads * 2; const vtkm::Id unrollEnd = ((numVals / 4) * 4) - 4; VTKM_OPENMP_DIRECTIVE(for schedule(static)) for (i = numThreads * 2; i < unrollEnd; i += 4) { const auto t1 = f(data[i], data[i + 1]); const auto t2 = f(data[i + 2], data[i + 3]); accum = f(accum, t1); accum = f(accum, t2); } // Let the last thread mop up any remaining values as it would // have just accessed the adjacent data if (tid == numThreads - 1) { for (i = unrollEnd; i < numVals; ++i) { accum = f(accum, data[i]); } } return accum; } // Integer reduction: no unrolling. Ints vectorize easily and unrolling can // hurt performance. template <typename ReturnType, typename IterType, typename FunctorType> static ReturnType DoParallelReduction(IterType data, vtkm::Id numVals, int tid, int numThreads, FunctorType f, std::true_type /* isIntegral */) { // Use the first (numThreads*2) values for initializing: ReturnType accum = f(data[2 * tid], data[2 * tid + 1]); // Assign each thread chunks of the remaining values for local reduction VTKM_OPENMP_DIRECTIVE(for schedule(static)) for (vtkm::Id i = numThreads * 2; i < numVals; i++) { accum = f(accum, data[i]); } return accum; } #ifdef VTKM_OPENMP_USE_NATIVE_REDUCTION // Specialize for vtkm functors with OpenMP special cases: #define VTKM_OPENMP_SPECIALIZE_REDUCE1(FunctorType, PragmaString) \ template <typename PortalT, typename ReturnType> \ static ReturnType Execute( \ PortalT portal, ReturnType value, FunctorType functorIn, std::true_type) \ { \ const vtkm::Id numValues = portal.GetNumberOfValues(); \ internal::WrappedBinaryOperator<ReturnType, FunctorType> f(functorIn); \ _Pragma(#PragmaString) for (vtkm::Id i = 0; i < numValues; ++i) \ { \ value = f(value, portal.Get(i)); \ } \ return value; \ } // Constructing the pragma string inside the _Pragma call doesn't work so // we jump through a hoop: #define VTKM_OPENMP_SPECIALIZE_REDUCE(FunctorType, Operator) \ VTKM_OPENMP_SPECIALIZE_REDUCE1(FunctorType, "omp parallel for reduction(" #Operator ":value)") // + (Add, Sum) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Add, +) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Sum, +) // * (Multiply, Product) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Multiply, *) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Product, *) // - (Subtract) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Subtract, -) // & (BitwiseAnd) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::BitwiseAnd, &) // | (BitwiseOr) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::BitwiseOr, |) // ^ (BitwiseXor) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::BitwiseXor, ^) // && (LogicalAnd) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::LogicalAnd, &&) // || (LogicalOr) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::LogicalOr, ||) // min (Minimum) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Minimum, min) // max (Maximum) VTKM_OPENMP_SPECIALIZE_REDUCE(vtkm::Maximum, max) #undef VTKM_OPENMP_SPECIALIZE_REDUCE #undef VTKM_OPENMP_SPECIALIZE_REDUCE1 #endif // VTKM_OPENMP_USE_NATIVE_REDUCTION }; template <typename KeysInArray, typename ValuesInArray, typename KeysOutArray, typename ValuesOutArray, typename BinaryFunctor> void ReduceByKeyHelper(KeysInArray keysInArray, ValuesInArray valuesInArray, KeysOutArray keysOutArray, ValuesOutArray valuesOutArray, BinaryFunctor functor) { using KeyType = typename KeysInArray::ValueType; using ValueType = typename ValuesInArray::ValueType; const vtkm::Id numValues = keysInArray.GetNumberOfValues(); auto keysInPortal = keysInArray.PrepareForInput(DeviceAdapterTagOpenMP()); auto valuesInPortal = valuesInArray.PrepareForInput(DeviceAdapterTagOpenMP()); auto keysIn = vtkm::cont::ArrayPortalToIteratorBegin(keysInPortal); auto valuesIn = vtkm::cont::ArrayPortalToIteratorBegin(valuesInPortal); auto keysOutPortal = keysOutArray.PrepareForOutput(numValues, DeviceAdapterTagOpenMP()); auto valuesOutPortal = valuesOutArray.PrepareForOutput(numValues, DeviceAdapterTagOpenMP()); auto keysOut = vtkm::cont::ArrayPortalToIteratorBegin(keysOutPortal); auto valuesOut = vtkm::cont::ArrayPortalToIteratorBegin(valuesOutPortal); internal::WrappedBinaryOperator<ValueType, BinaryFunctor> f(functor); vtkm::Id outIdx = 0; VTKM_OPENMP_DIRECTIVE(parallel default(none) firstprivate(keysIn, valuesIn, keysOut, valuesOut, f) shared(outIdx) VTKM_OPENMP_SHARED_CONST(numValues)) { int tid = omp_get_thread_num(); int numThreads = omp_get_num_threads(); // Determine bounds for this thread's scan operation: vtkm::Id chunkSize = (numValues + numThreads - 1) / numThreads; vtkm::Id scanIdx = std::min(tid * chunkSize, numValues); vtkm::Id scanEnd = std::min(scanIdx + chunkSize, numValues); auto threadKeysBegin = keysOut + scanIdx; auto threadValuesBegin = valuesOut + scanIdx; auto threadKey = threadKeysBegin; auto threadValue = threadValuesBegin; // Reduce each thread's partition: KeyType rangeKey; ValueType rangeValue; for (;;) { if (scanIdx < scanEnd) { rangeKey = keysIn[scanIdx]; rangeValue = valuesIn[scanIdx]; ++scanIdx; // Locate end of current range: while (scanIdx < scanEnd && static_cast<KeyType>(keysIn[scanIdx]) == rangeKey) { rangeValue = f(rangeValue, valuesIn[scanIdx]); ++scanIdx; } *threadKey = rangeKey; *threadValue = rangeValue; ++threadKey; ++threadValue; } else { break; } } if (tid == 0) { outIdx = static_cast<vtkm::Id>(threadKey - threadKeysBegin); } // Combine the reduction results. Skip tid == 0, since it's already in // the correct location: for (int i = 1; i < numThreads; ++i) { // This barrier ensures that: // 1) Threads remain synchronized through this final reduction loop. // 2) The outIdx variable is initialized by thread 0. // 3) All threads have reduced their partitions. VTKM_OPENMP_DIRECTIVE(barrier) if (tid == i) { // Check if the previous thread's last key matches our first: if (outIdx > 0 && threadKeysBegin < threadKey && keysOut[outIdx - 1] == *threadKeysBegin) { valuesOut[outIdx - 1] = f(valuesOut[outIdx - 1], *threadValuesBegin); ++threadKeysBegin; ++threadValuesBegin; } // Copy reduced partition to final location (if needed) if (threadKeysBegin < threadKey && threadKeysBegin != keysOut + outIdx) { std::copy(threadKeysBegin, threadKey, keysOut + outIdx); std::copy(threadValuesBegin, threadValue, valuesOut + outIdx); } outIdx += static_cast<vtkm::Id>(threadKey - threadKeysBegin); } // end tid == i } // end combine reduction } // end parallel keysOutArray.Shrink(outIdx); valuesOutArray.Shrink(outIdx); } template <typename IterT, typename RawPredicateT> struct UniqueHelper { using ValueType = typename std::iterator_traits<IterT>::value_type; using PredicateT = internal::WrappedBinaryOperator<bool, RawPredicateT>; struct Node { vtkm::Id2 InputRange{ -1, -1 }; vtkm::Id2 OutputRange{ -1, -1 }; // Pad the node out to the size of a cache line to prevent false sharing: static constexpr size_t DataSize = 2 * sizeof(vtkm::Id2); static constexpr size_t NumCacheLines = CeilDivide<size_t>(DataSize, CACHE_LINE_SIZE); static constexpr size_t PaddingSize = NumCacheLines * CACHE_LINE_SIZE - DataSize; unsigned char Padding[PaddingSize]; }; IterT Data; vtkm::Id NumValues; PredicateT Predicate; vtkm::Id LeafSize; std::vector<Node> Nodes; size_t NextNode; UniqueHelper(IterT iter, vtkm::Id numValues, RawPredicateT pred) : Data(iter) , NumValues(numValues) , Predicate(pred) , LeafSize(0) , NextNode(0) { } vtkm::Id Execute() { vtkm::Id outSize = 0; VTKM_OPENMP_DIRECTIVE(parallel default(shared)) { VTKM_OPENMP_DIRECTIVE(single) { this->Prepare(); // Kick off task-based divide-and-conquer uniquification: Node* rootNode = this->AllocNode(); rootNode->InputRange = vtkm::Id2(0, this->NumValues); this->Uniquify(rootNode); outSize = rootNode->OutputRange[1] - rootNode->OutputRange[0]; } } return outSize; } private: void Prepare() { // Figure out how many values each thread should handle: int numThreads = omp_get_num_threads(); vtkm::Id chunksPerThread = 8; vtkm::Id numChunks; ComputeChunkSize( this->NumValues, numThreads, chunksPerThread, sizeof(ValueType), numChunks, this->LeafSize); // Compute an upper-bound of the number of nodes in the tree: std::size_t numNodes = static_cast<std::size_t>(numChunks); while (numChunks > 1) { numChunks = (numChunks + 1) / 2; numNodes += static_cast<std::size_t>(numChunks); } this->Nodes.resize(numNodes); this->NextNode = 0; } Node* AllocNode() { size_t nodeIdx; // GCC emits a false positive "value computed but not used" for this block: #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-value" VTKM_OPENMP_DIRECTIVE(atomic capture) { nodeIdx = this->NextNode; ++this->NextNode; } #pragma GCC diagnostic pop VTKM_ASSERT(nodeIdx < this->Nodes.size()); return &this->Nodes[nodeIdx]; } bool IsLeaf(const vtkm::Id2& range) { return (range[1] - range[0]) <= this->LeafSize; } // Not an strict midpoint, but ensures that the first range will always be // a multiple of the leaf size. vtkm::Id ComputeMidpoint(const vtkm::Id2& range) { const vtkm::Id n = range[1] - range[0]; const vtkm::Id np = this->LeafSize; return CeilDivide(n / 2, np) * np + range[0]; } void Uniquify(Node* node) { if (!this->IsLeaf(node->InputRange)) { vtkm::Id midpoint = this->ComputeMidpoint(node->InputRange); Node* right = this->AllocNode(); Node* left = this->AllocNode(); right->InputRange = vtkm::Id2(midpoint, node->InputRange[1]); // Intel compilers seem to have trouble following the 'this' pointer // when launching tasks, resulting in a corrupt task environment. // Explicitly copying the pointer into a local variable seems to fix this. auto explicitThis = this; VTKM_OPENMP_DIRECTIVE(taskgroup) { VTKM_OPENMP_DIRECTIVE(task) { explicitThis->Uniquify(right); } left->InputRange = vtkm::Id2(node->InputRange[0], midpoint); this->Uniquify(left); } // end taskgroup. Both sides of the tree will be completed here. // Combine the ranges in the left side: if (this->Predicate(this->Data[left->OutputRange[1] - 1], this->Data[right->OutputRange[0]])) { ++right->OutputRange[0]; } vtkm::Id numVals = right->OutputRange[1] - right->OutputRange[0]; DoCopy(this->Data + right->OutputRange[0], this->Data + left->OutputRange[1], numVals); node->OutputRange[0] = left->OutputRange[0]; node->OutputRange[1] = left->OutputRange[1] + numVals; } else { auto start = this->Data + node->InputRange[0]; auto end = this->Data + node->InputRange[1]; end = std::unique(start, end, this->Predicate); node->OutputRange[0] = node->InputRange[0]; node->OutputRange[1] = node->InputRange[0] + static_cast<vtkm::Id>(end - start); } } }; } } } // end namespace vtkm::cont::openmp #endif // vtk_m_cont_openmp_internal_FunctorsOpenMP_h
dropout-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file dropout-inl.h * \brief * \author Bing Xu, Da Zheng, Hang Zhang */ #ifndef MXNET_OPERATOR_NN_DROPOUT_INL_H_ #define MXNET_OPERATOR_NN_DROPOUT_INL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <map> #include <vector> #include <string> #include <utility> #include <algorithm> #include "../mxnet_op.h" #include "../mshadow_op.h" #include "../random/sampler.h" #include "../tensor/elemwise_binary_broadcast_op.h" #if defined(USE_MKL) && defined(_OPENMP) #include <omp.h> #include <mkl_vml_functions.h> #include <mkl_vsl.h> #endif // USE_MKL && _OPENMP namespace dropout { enum DropoutOpInputs {kData}; enum DropoutOpOutputs {kOut, kMask}; enum DropoutOpForwardResource {kRandom}; enum DropoutOpMode {kTraining, kAlways}; } // namespace dropout namespace mxnet { namespace op { const int MAX_DIM = 5; struct DropoutParam : public dmlc::Parameter<DropoutParam> { float p; int mode; TShape axes; DMLC_DECLARE_PARAMETER(DropoutParam) { DMLC_DECLARE_FIELD(p).set_default(0.5) .set_range(0, 1) .describe("Fraction of the input that gets dropped out during training time."); DMLC_DECLARE_FIELD(mode) .add_enum("training", dropout::kTraining) .add_enum("always", dropout::kAlways) .set_default(dropout::kTraining) .describe("Whether to only turn on dropout during training or to also turn on for inference."); DMLC_DECLARE_FIELD(axes).set_default(TShape()) .describe("Axes for variational dropout kernel."); } }; // struct DropoutParam template<typename xpu, typename DType> class DropoutOp { #if defined(USE_MKL) && defined(_OPENMP) static void BernoulliGenerate(common::random::RandGenerator<cpu, DType> gen, int n, double p, int* r) { typename RandGenerator<xpu, DType>::Impl genImpl(&gen, 1); const int seed = 17 + genImpl.rand() % 4096; // NOLINT(runtime/threadsafe_fn) const int nthr = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); #pragma omp parallel num_threads(nthr) { const int ithr = omp_get_thread_num(); const int avg_amount = (n + nthr - 1) / nthr; const int my_offset = ithr * avg_amount; const int my_amount = std::min(my_offset + avg_amount, n) - my_offset; if (my_amount > 0) { VSLStreamStatePtr stream; vslNewStream(&stream, VSL_BRNG_MCG31, seed + my_offset); vslSkipAheadStream(stream, my_offset); viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount, r + my_offset, p); vslDeleteStream(&stream); } } } // MKL forward pass static bool MSHADOW_CINLINE MKLForward(mshadow::Stream<cpu> *s, RandGenerator<cpu, DType> *pgen, const double pkeep, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data) { // BernoulliGenerate expects an array int, so for types smaller than int, the mask buffer // will be too small, so we can;t use MKL in those cases if (sizeof(DType) >= sizeof(int)) { Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> data = in_data[dropout::kData].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> out = out_data[dropout::kOut].FlatTo2D<xpu, DType>(s); DType *outptr = out.dptr_; DType *dataptr = data.dptr_; auto maskptr = reinterpret_cast<int *>(mask.dptr_); int count = mask.shape_[0] * mask.shape_[1]; BernoulliGenerate(*pgen, count, pkeep, maskptr); const float pk_1 = 1.0f / pkeep; #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (int i = 0; i < count; ++i) { outptr[i] = dataptr[i] * maskptr[i] * pk_1; } return true; } return false; } // MKL backward pass static bool MSHADOW_CINLINE MKLBackward(mshadow::Stream<cpu> *s, const double pkeep, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &out_data, const std::vector<TBlob> &out_grad) { if (sizeof(DType) >= sizeof(int)) { Tensor<xpu, 2, DType> grad = out_grad[dropout::kOut].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> gdata = in_grad[dropout::kData].FlatTo2D<xpu, DType>(s); DType *ingradptr = gdata.dptr_; const DType *outgradptr = grad.dptr_; auto maskptr = reinterpret_cast<int *>(mask.dptr_); int count = mask.shape_[0] * mask.shape_[1]; const float pk_1 = 1.0f / pkeep; #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (int i = 0; i < count; ++i) { ingradptr[i] = outgradptr[i] * maskptr[i] * pk_1; } return true; } return false; } #ifdef __CUDACC__ // GPU never uses MKL static bool MSHADOW_CINLINE MKLForward(mshadow::Stream<gpu> *s, RandGenerator<gpu, DType> *pgen, const double pkeep, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data) { return false; } static bool MSHADOW_CINLINE MKLBackward(mshadow::Stream<gpu> *s, const double pkeep, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &out_data, const std::vector<TBlob> &out_grad) { return false; } #endif // __CUDACC__ #else // #if defined(USE_MKL) && defined(_OPENMP) static bool MSHADOW_CINLINE MKLForward(mshadow::Stream<xpu> *s, RandGenerator<xpu, DType> *pgen, const double pkeep, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data) { return false; } static bool MSHADOW_CINLINE MKLBackward(mshadow::Stream<xpu> *s, const double pkeep, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &out_data, const std::vector<TBlob> &out_grad) { return false; } #endif // #if defined(USE_MKL) && defined(_OPENMP) public: /*! * \brief Dropout kernel, compute dropout tensor */ struct DropoutKernel { /*! * \brief Dropout kernel function * \param id Thread number (0-based representing count) * \param gen Random number generator * \param N Total number of items in the output * \param step Step between items, related to parallelism * \param dropout_out Output dropout values * \param mask_out Output mask (is multiplied to create dropout output, may be 0) * \param input_data Input data to perform the dropout on * \param pkeep Dropout rate (keep when the generated random number is less than this value) */ MSHADOW_XINLINE static void Map(int id, RandGenerator<xpu, DType> gen, const int N, const int step, DType *dropout_out, DType *mask_out, const DType *input_data, const real_t pkeep) { RNG_KERNEL_LOOP(xpu, DType, id, gen, N, step, { const real_t rand_num = static_cast<real_t>(genImpl.uniform()); mask_out[i] = mshadow_op::threshold::Map<real_t>(rand_num, pkeep) * (1.0f / pkeep); dropout_out[i] = input_data[i] * mask_out[i]; }); } }; struct BernoulliKernel { /*! \brief Bernoulli kernel for generating mask */ MSHADOW_XINLINE static void Map(int id, RandGenerator<xpu, DType> gen, const int N, const int step, DType *mask_out, const real_t pkeep) { RNG_KERNEL_LOOP(xpu, DType, id, gen, N, step, { const real_t rand_num = static_cast<real_t>(genImpl.uniform()); mask_out[i] = mshadow_op::threshold::Map<real_t>(rand_num, pkeep) * (1.0f / pkeep); }); } }; void Init(const DropoutParam &param) { this->pkeep_ = 1.0f - param.p; this->mode_ = static_cast<dropout::DropoutOpMode>(param.mode); this->axes_ = param.axes; } void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data) { if (req[dropout::kOut] != kNullOp) { CHECK_EQ(in_data.size(), 1U); if (ctx.is_train) { CHECK_EQ(out_data.size(), 2U); } Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob &out = out_data[dropout::kOut]; if (ctx.is_train || this->mode_ == dropout::kAlways) { RandGenerator<xpu, DType> *pgen = ctx.requested[0].get_parallel_random<xpu, DType>(); CHECK_NOTNULL(pgen); if (this->axes_.ndim() != 0 || !MKLForward(s, pgen, this->pkeep_, in_data, out_data)) { const TBlob &mask = out_data[dropout::kMask]; CHECK(req[dropout::kOut] != kAddTo); if (this->axes_.ndim() == 0) { // standard case for dropout LaunchRNG<DropoutKernel, xpu>(s, pgen, out.Size(), out.dptr<DType>(), mask.dptr<DType>(), in_data[dropout::kData].dptr<DType>(), this->pkeep_); return; } // initialize the mask LaunchRNG<BernoulliKernel, xpu>(s, pgen, mask.Size(), mask.dptr<DType>(), this->pkeep_); // broadcast mul TShape new_lshape, new_rshape, new_oshape; int ndim = BinaryBroadcastShapeCompact(in_data[dropout::kData].shape_, mask.shape_, out.shape_, &new_lshape, &new_rshape, &new_oshape); if (!ndim) { MXNET_ASSIGN_REQ_SWITCH(req[dropout::kOut], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch( s, out.Size(), out.dptr<DType>(), in_data[dropout::kData].dptr<DType>(), mask.dptr<DType>()); }); } else { BROADCAST_NDIM_SWITCH(ndim, NDim, { mshadow::Shape<NDim> oshape = new_oshape.get<NDim>(); mshadow::Shape<NDim> lstride = mxnet_op::calc_stride(new_lshape.get<NDim>()); mshadow::Shape<NDim> rstride = mxnet_op::calc_stride(new_rshape.get<NDim>()); mxnet_op::Kernel<mxnet_op::binary_broadcast_kernel<NDim, DType, mshadow_op::mul>, xpu>:: template LaunchEx(s, new_oshape.Size(), req[dropout::kOut], lstride, rstride, oshape, in_data[dropout::kData].dptr<DType>(), mask.dptr<DType>(), out.dptr<DType>()); }); } } } else { const TBlob& data = in_data[dropout::kData]; if (req[dropout::kOut] == kWriteTo) { mxnet_op::copy(s, out, data); } else { MXNET_ASSIGN_REQ_SWITCH(req[dropout::kOut], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, Req>, xpu>::Launch( s, out.Size(), out.dptr<DType>(), data.dptr<DType>()); }); } } } } void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &out_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad) { using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.get_stream<xpu>(); if (ctx.is_train || mode_ == dropout::kAlways) { if (this->axes_.ndim() != 0 || !MKLBackward(s, this->pkeep_, in_grad, out_data, out_grad)) { const TBlob &gdata = in_grad[dropout::kData]; const TBlob &grad = out_grad[dropout::kOut]; const TBlob &mask = out_data[dropout::kMask]; if (this->axes_.ndim() == 0) { // standard case for dropout CHECK_EQ(grad.Size(), mask.Size()); MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch( s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>(), mask.dptr<DType>()); }); return; } // broardcast mul TShape new_lshape, new_rshape, new_oshape; int ndim = BinaryBroadcastShapeCompact(grad.shape_, mask.shape_, gdata.shape_, &new_lshape, &new_rshape, &new_oshape); if (!ndim) { MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch( s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>(), mask.dptr<DType>()); }); } else { BROADCAST_NDIM_SWITCH(ndim, NDim, { mshadow::Shape<NDim> oshape = new_oshape.get<NDim>(); mshadow::Shape<NDim> lstride = mxnet_op::calc_stride(new_lshape.get<NDim>()); mshadow::Shape<NDim> rstride = mxnet_op::calc_stride(new_rshape.get<NDim>()); mxnet_op::Kernel<mxnet_op::binary_broadcast_kernel<NDim, DType, mshadow_op::mul>, xpu>:: template LaunchEx(s, new_oshape.Size(), req[0], lstride, rstride, oshape, grad.dptr<DType>(), mask.dptr<DType>(), gdata.dptr<DType>()); }); } } } else { const TBlob& gdata = in_grad[dropout::kData]; const TBlob& grad = out_grad[dropout::kOut]; if (req[dropout::kData] == kWriteTo) { mxnet_op::copy(s, gdata, grad); } else { MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, Req>, xpu>::Launch( s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>()); }); } } } private: /*! \brief Dropout rate (keep when the generated random number is less than this value) */ real_t pkeep_; /*! \brief Dropout mode */ dropout::DropoutOpMode mode_; TShape axes_; }; // class DropoutOp template<typename xpu> void DropoutCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const DropoutParam& param = nnvm::get<DropoutParam>(attrs.parsed); MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, { static thread_local DropoutOp<xpu, DType> op; op.Init(param); op.Forward(ctx, inputs, req, outputs); }); } template<typename xpu> void DropoutGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const DropoutParam& param = nnvm::get<DropoutParam>(attrs.parsed); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1); CHECK_EQ(req.size(), 1); std::vector<TBlob> out_grads(2); std::vector<TBlob> out_data(2); out_grads[dropout::kOut] = inputs[0]; out_data[dropout::kMask] = inputs[1]; MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, { static thread_local DropoutOp<xpu, DType> op; op.Init(param); op.Backward(ctx, out_grads, out_data, req, outputs); }); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_DROPOUT_INL_H_
sse.h
/* SPDX-License-Identifier: MIT * * 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. * * Copyright: * 2017-2020 Evan Nemerson <evan@nemerson.com> * 2015-2017 John W. Ratcliff <jratcliffscarab@gmail.com> * 2015 Brandon Rowlett <browlett@nvidia.com> * 2015 Ken Fast <kfast@gdeb.com> */ #if !defined(SIMDE_X86_SSE_H) #define SIMDE_X86_SSE_H #include "mmx.h" #if defined(_WIN32) #include <windows.h> #endif HEDLEY_DIAGNOSTIC_PUSH SIMDE_DISABLE_UNWANTED_DIAGNOSTICS SIMDE_BEGIN_DECLS_ typedef union { #if defined(SIMDE_VECTOR_SUBSCRIPT) SIMDE_ALIGN_TO_16 int8_t i8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int16_t i16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int32_t i32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int64_t i64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint8_t u8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint16_t u16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint32_t u32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint64_t u64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 simde_uint128 u128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #endif SIMDE_ALIGN_TO_16 simde_float32 f32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int_fast32_t i32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint_fast32_t u32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else SIMDE_ALIGN_TO_16 int8_t i8[16]; SIMDE_ALIGN_TO_16 int16_t i16[8]; SIMDE_ALIGN_TO_16 int32_t i32[4]; SIMDE_ALIGN_TO_16 int64_t i64[2]; SIMDE_ALIGN_TO_16 uint8_t u8[16]; SIMDE_ALIGN_TO_16 uint16_t u16[8]; SIMDE_ALIGN_TO_16 uint32_t u32[4]; SIMDE_ALIGN_TO_16 uint64_t u64[2]; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128[1]; SIMDE_ALIGN_TO_16 simde_uint128 u128[1]; #endif SIMDE_ALIGN_TO_16 simde_float32 f32[4]; SIMDE_ALIGN_TO_16 int_fast32_t i32f[16 / sizeof(int_fast32_t)]; SIMDE_ALIGN_TO_16 uint_fast32_t u32f[16 / sizeof(uint_fast32_t)]; #endif SIMDE_ALIGN_TO_16 simde__m64_private m64_private[2]; SIMDE_ALIGN_TO_16 simde__m64 m64[2]; #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_ALIGN_TO_16 __m128 n; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 int8x16_t neon_i8; SIMDE_ALIGN_TO_16 int16x8_t neon_i16; SIMDE_ALIGN_TO_16 int32x4_t neon_i32; SIMDE_ALIGN_TO_16 int64x2_t neon_i64; SIMDE_ALIGN_TO_16 uint8x16_t neon_u8; SIMDE_ALIGN_TO_16 uint16x8_t neon_u16; SIMDE_ALIGN_TO_16 uint32x4_t neon_u32; SIMDE_ALIGN_TO_16 uint64x2_t neon_u64; SIMDE_ALIGN_TO_16 float32x4_t neon_f32; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_ALIGN_TO_16 float64x2_t neon_f64; #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_ALIGN_TO_16 v128_t wasm_v128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) altivec_u8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned short) altivec_u16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) altivec_u32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed char) altivec_i8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed short) altivec_i16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed int) altivec_i32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(float) altivec_f32; #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long) altivec_u64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed long long) altivec_i64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(double) altivec_f64; #endif #endif } simde__m128_private; #if defined(SIMDE_X86_SSE_NATIVE) typedef __m128 simde__m128; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) typedef float32x4_t simde__m128; #elif defined(SIMDE_WASM_SIMD128_NATIVE) typedef v128_t simde__m128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) typedef SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128; #elif defined(SIMDE_VECTOR_SUBSCRIPT) typedef simde_float32 simde__m128 SIMDE_ALIGN_TO_16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else typedef simde__m128_private simde__m128; #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) typedef simde__m128 __m128; #endif HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128), "simde__m128 size incorrect"); HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128_private), "simde__m128_private size incorrect"); #if defined(SIMDE_CHECK_ALIGNMENT) && defined(SIMDE_ALIGN_OF) HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128) == 16, "simde__m128 is not 16-byte aligned"); HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128_private) == 16, "simde__m128_private is not 16-byte aligned"); #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_private(simde__m128_private v) { simde__m128 r; simde_memcpy(&r, &v, sizeof(r)); return r; } SIMDE_FUNCTION_ATTRIBUTES simde__m128_private simde__m128_to_private(simde__m128 v) { simde__m128_private r; simde_memcpy(&r, &v, sizeof(r)); return r; } #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int8x16_t, neon, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int16x8_t, neon, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int32x4_t, neon, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int64x2_t, neon, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint8x16_t, neon, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint16x8_t, neon, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint32x4_t, neon, u32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint64x2_t, neon, u64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float32x4_t, neon, f32) #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float64x2_t, neon, f64) #endif #endif /* defined(SIMDE_ARM_NEON_A32V7_NATIVE) */ #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed char), altivec, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed short), altivec, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed int), altivec, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned char), altivec, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned short), altivec, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), altivec, u32) #if defined(SIMDE_BUG_GCC_95782) SIMDE_FUNCTION_ATTRIBUTES SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128_to_altivec_f32(simde__m128 value) { simde__m128_private r_ = simde__m128_to_private(value); return r_.altivec_f32; } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_altivec_f32(SIMDE_POWER_ALTIVEC_VECTOR(float) value) { simde__m128_private r_; r_.altivec_f32 = value; return simde__m128_from_private(r_); } #else SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(float), altivec, f32) #endif #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed long long), altivec, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long), altivec, u64) #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, v128_t, wasm, v128); #endif /* defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) */ enum { #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_MM_ROUND_NEAREST = _MM_ROUND_NEAREST, SIMDE_MM_ROUND_DOWN = _MM_ROUND_DOWN, SIMDE_MM_ROUND_UP = _MM_ROUND_UP, SIMDE_MM_ROUND_TOWARD_ZERO = _MM_ROUND_TOWARD_ZERO #else SIMDE_MM_ROUND_NEAREST = 0x0000, SIMDE_MM_ROUND_DOWN = 0x2000, SIMDE_MM_ROUND_UP = 0x4000, SIMDE_MM_ROUND_TOWARD_ZERO = 0x6000 #endif }; #if defined(_MM_FROUND_TO_NEAREST_INT) # define SIMDE_MM_FROUND_TO_NEAREST_INT _MM_FROUND_TO_NEAREST_INT # define SIMDE_MM_FROUND_TO_NEG_INF _MM_FROUND_TO_NEG_INF # define SIMDE_MM_FROUND_TO_POS_INF _MM_FROUND_TO_POS_INF # define SIMDE_MM_FROUND_TO_ZERO _MM_FROUND_TO_ZERO # define SIMDE_MM_FROUND_CUR_DIRECTION _MM_FROUND_CUR_DIRECTION # define SIMDE_MM_FROUND_RAISE_EXC _MM_FROUND_RAISE_EXC # define SIMDE_MM_FROUND_NO_EXC _MM_FROUND_NO_EXC #else # define SIMDE_MM_FROUND_TO_NEAREST_INT 0x00 # define SIMDE_MM_FROUND_TO_NEG_INF 0x01 # define SIMDE_MM_FROUND_TO_POS_INF 0x02 # define SIMDE_MM_FROUND_TO_ZERO 0x03 # define SIMDE_MM_FROUND_CUR_DIRECTION 0x04 # define SIMDE_MM_FROUND_RAISE_EXC 0x00 # define SIMDE_MM_FROUND_NO_EXC 0x08 #endif #define SIMDE_MM_FROUND_NINT \ (SIMDE_MM_FROUND_TO_NEAREST_INT | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_FLOOR \ (SIMDE_MM_FROUND_TO_NEG_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_CEIL \ (SIMDE_MM_FROUND_TO_POS_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_TRUNC \ (SIMDE_MM_FROUND_TO_ZERO | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_RINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_NEARBYINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_NO_EXC) #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) && !defined(_MM_FROUND_TO_NEAREST_INT) # define _MM_FROUND_TO_NEAREST_INT SIMDE_MM_FROUND_TO_NEAREST_INT # define _MM_FROUND_TO_NEG_INF SIMDE_MM_FROUND_TO_NEG_INF # define _MM_FROUND_TO_POS_INF SIMDE_MM_FROUND_TO_POS_INF # define _MM_FROUND_TO_ZERO SIMDE_MM_FROUND_TO_ZERO # define _MM_FROUND_CUR_DIRECTION SIMDE_MM_FROUND_CUR_DIRECTION # define _MM_FROUND_RAISE_EXC SIMDE_MM_FROUND_RAISE_EXC # define _MM_FROUND_NINT SIMDE_MM_FROUND_NINT # define _MM_FROUND_FLOOR SIMDE_MM_FROUND_FLOOR # define _MM_FROUND_CEIL SIMDE_MM_FROUND_CEIL # define _MM_FROUND_TRUNC SIMDE_MM_FROUND_TRUNC # define _MM_FROUND_RINT SIMDE_MM_FROUND_RINT # define _MM_FROUND_NEARBYINT SIMDE_MM_FROUND_NEARBYINT #endif SIMDE_FUNCTION_ATTRIBUTES unsigned int SIMDE_MM_GET_ROUNDING_MODE(void) { #if defined(SIMDE_X86_SSE_NATIVE) return _MM_GET_ROUNDING_MODE(); #elif defined(SIMDE_HAVE_FENV_H) unsigned int vfe_mode; switch (fegetround()) { #if defined(FE_TONEAREST) case FE_TONEAREST: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; #endif #if defined(FE_TOWARDZERO) case FE_TOWARDZERO: vfe_mode = SIMDE_MM_ROUND_DOWN; break; #endif #if defined(FE_UPWARD) case FE_UPWARD: vfe_mode = SIMDE_MM_ROUND_UP; break; #endif #if defined(FE_DOWNWARD) case FE_DOWNWARD: vfe_mode = SIMDE_MM_ROUND_TOWARD_ZERO; break; #endif default: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; } return vfe_mode; #else return SIMDE_MM_ROUND_NEAREST; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_GET_ROUNDING_MODE() SIMDE_MM_GET_ROUNDING_MODE() #endif SIMDE_FUNCTION_ATTRIBUTES void SIMDE_MM_SET_ROUNDING_MODE(unsigned int a) { #if defined(SIMDE_X86_SSE_NATIVE) _MM_SET_ROUNDING_MODE(a); #elif defined(SIMDE_HAVE_FENV_H) int fe_mode = FE_TONEAREST; switch (a) { #if defined(FE_TONEAREST) case SIMDE_MM_ROUND_NEAREST: fe_mode = FE_TONEAREST; break; #endif #if defined(FE_TOWARDZERO) case SIMDE_MM_ROUND_TOWARD_ZERO: fe_mode = FE_TOWARDZERO; break; #endif #if defined(FE_DOWNWARD) case SIMDE_MM_ROUND_DOWN: fe_mode = FE_DOWNWARD; break; #endif #if defined(FE_UPWARD) case SIMDE_MM_ROUND_UP: fe_mode = FE_UPWARD; break; #endif default: return; } fesetround(fe_mode); #else (void) a; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_ROUNDING_MODE(a) SIMDE_MM_SET_ROUNDING_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES uint32_t simde_mm_getcsr (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_getcsr(); #else return SIMDE_MM_GET_ROUNDING_MODE(); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_getcsr() simde_mm_getcsr() #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_setcsr (uint32_t a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_setcsr(a); #else SIMDE_MM_SET_ROUNDING_MODE(HEDLEY_STATIC_CAST(unsigned int, a)); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_setcsr(a) simde_mm_setcsr(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_round_ps (simde__m128 a, int rounding) SIMDE_REQUIRE_CONSTANT_RANGE(rounding, 0, 15) { simde__m128_private r_, a_ = simde__m128_to_private(a); /* For architectures which lack a current direction SIMD instruction. * * Note that NEON actually has a current rounding mode instruction, * but in ARMv8+ the rounding mode is ignored and nearest is always * used, so we treat ARMv7 as having a rounding mode but ARMv8 as * not. */ #if \ defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || \ defined(SIMDE_ARM_NEON_A32V8) if ((rounding & 7) == SIMDE_MM_FROUND_CUR_DIRECTION) rounding = HEDLEY_STATIC_CAST(int, SIMDE_MM_GET_ROUNDING_MODE()) << 13; #endif switch (rounding & ~SIMDE_MM_FROUND_NO_EXC) { case SIMDE_MM_FROUND_CUR_DIRECTION: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_round(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && 0 r_.neon_f32 = vrndiq_f32(a_.neon_f32); #elif defined(simde_math_nearbyintf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_nearbyintf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEAREST_INT: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_round(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && 0 r_.neon_f32 = vrndaq_f32(a_.neon_f32); #elif defined(simde_math_roundf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_roundf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEG_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_floor(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && 0 r_.neon_f32 = vrndmq_f32(a_.neon_f32); #elif defined(simde_math_floorf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_floorf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_POS_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_ceil(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && 0 r_.neon_f32 = vrndpq_f32(a_.neon_f32); #elif defined(simde_math_ceilf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_ceilf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_ZERO: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_trunc(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && 0 r_.neon_f32 = vrndq_f32(a_.neon_f32); #elif defined(simde_math_truncf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_truncf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; default: HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); } return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE4_1_NATIVE) #define simde_mm_round_ps(a, rounding) _mm_round_ps(a, rounding) #endif #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) #define _mm_round_ps(a, rounding) simde_mm_round_ps(a, rounding) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps(e3, e2, e1, e0); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 simde_float32 data[4] = { e0, e1, e2, e3 }; r_.neon_f32 = vld1q_f32(data); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_make(e0, e1, e2, e3); #else r_.f32[0] = e0; r_.f32[1] = e1; r_.f32[2] = e2; r_.f32[3] = e3; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps(e3, e2, e1, e0) simde_mm_set_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps1 (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps1(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(a); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) (void) a; return vec_splats(a); #else return simde_mm_set_ps(a, a, a, a); #endif } #define simde_mm_set1_ps(a) simde_mm_set_ps1(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps1(a) simde_mm_set_ps1(a) # define _mm_set1_ps(a) simde_mm_set1_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_move_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_move_ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(b_.neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) m = { 16, 17, 18, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; r_.altivec_f32 = vec_perm(a_.altivec_f32, b_.altivec_f32, m); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v8x16_shuffle(b_.wasm_v128, a_.wasm_v128, 0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 4, 1, 2, 3); #else r_.f32[0] = b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_move_ss(a, b) simde_mm_move_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vaddq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_add(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_add(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 + b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] + b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ps(a, b) simde_mm_add_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_add_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t b0 = vgetq_lane_f32(b_.neon_f32, 0); float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); // the upper values in the result must be the remnants of <a>. r_.neon_f32 = vaddq_f32(a_.neon_f32, value); #else r_.f32[0] = a_.f32[0] + b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ss(a, b) simde_mm_add_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_and_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_and_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vandq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 & b_.i32; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_and(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_and_ps(a, b) simde_mm_and_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_andnot_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_andnot_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbicq_s32(b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_andnot(b_.wasm_v128, a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_andc(b_.altivec_f32, a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32 & b_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]) & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_andnot_ps(a, b) simde_mm_andnot_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_xor_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_xor_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = veorq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_xor(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_xor(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f ^ b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] ^ b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_xor_ps(a, b) simde_mm_xor_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_or_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_or_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vorrq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_or(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f | b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] | b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_or_ps(a, b) simde_mm_or_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_not_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE2_NATIVE) /* Note: we use ints instead of floats because we don't want cmpeq * to return false for (NaN, NaN) */ __m128i ai = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_andnot_si128(ai, _mm_cmpeq_epi32(ai, ai))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vmvnq_s32(a_.neon_i32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_nor(a_.altivec_i32, a_.altivec_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_not(a_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_select_ps(simde__m128 a, simde__m128 b, simde__m128 mask) { /* This function is for when you want to blend two elements together * according to a mask. It is similar to _mm_blendv_ps, except that * it is undefined whether the blend is based on the highest bit in * each lane (like blendv) or just bitwise operations. This allows * us to implement the function efficiently everywhere. * * Basically, you promise that all the lanes in mask are either 0 or * ~0. */ #if defined(SIMDE_X86_SSE4_1_NATIVE) return _mm_blendv_ps(a, b, mask); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b), mask_ = simde__m128_to_private(mask); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbslq_s32(mask_.neon_u32, b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_bitselect(b_.wasm_v128, a_.wasm_v128, mask_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_sel(a_.altivec_i32, b_.altivec_i32, mask_.altivec_u32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 ^ ((a_.i32 ^ b_.i32) & mask_.i32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] ^ ((a_.i32[i] ^ b_.i32[i]) & mask_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u16 = vrhadd_u16(b_.neon_u16, a_.neon_u16); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint32_t wa SIMDE_VECTOR(16); uint32_t wb SIMDE_VECTOR(16); uint32_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u16); SIMDE_CONVERT_VECTOR_(wb, b_.u16); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u16, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = (a_.u16[i] + b_.u16[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgw(a, b) simde_mm_avg_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu16(a, b) simde_mm_avg_pu16(a, b) # define _m_pavgw(a, b) simde_mm_avg_pu16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vrhadd_u8(b_.neon_u8, a_.neon_u8); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint16_t wa SIMDE_VECTOR(16); uint16_t wb SIMDE_VECTOR(16); uint16_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u8); SIMDE_CONVERT_VECTOR_(wb, b_.u8); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u8, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] + b_.u8[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgb(a, b) simde_mm_avg_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu8(a, b) simde_mm_avg_pu8(a, b) # define _m_pavgb(a, b) simde_mm_avg_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_abs_ps(simde__m128 a) { #if defined(SIMDE_X86_AVX512F_NATIVE) && \ (!defined(HEDLEY_GCC_VERSION) || HEDLEY_GCC_VERSION_CHECK(7,1,0)) return _mm512_castps512_ps128(_mm512_abs_ps(_mm512_castps128_ps512(a))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vabsq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_abs(a_.altivec_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_abs(a_.wasm_v128); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_fabsf(a_.f32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vceqq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_eq(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), a_.f32 == b_.f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] == b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ps(a, b) simde_mm_cmpeq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpeq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] == b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ss(a, b) simde_mm_cmpeq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpge_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgeq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ge(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpge(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 >= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] >= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ps(a, b) simde_mm_cmpge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpge_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpge_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] >= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ss(a, b) simde_mm_cmpge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpgt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgtq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_gt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpgt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 > b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] > b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ps(a, b) simde_mm_cmpgt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpgt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpgt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] > b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ss(a, b) simde_mm_cmpgt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcleq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_le(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmple(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 <= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] <= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ps(a, b) simde_mm_cmple_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmple_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] <= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ss(a, b) simde_mm_cmple_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcltq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmplt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 < b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] < b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ps(a, b) simde_mm_cmplt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmplt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] < b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ss(a, b) simde_mm_cmplt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ne(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) && SIMDE_ARCH_POWER_CHECK(900) && !defined(HEDLEY_IBM_VERSION) /* vec_cmpne(SIMDE_POWER_ALTIVEC_VECTOR(float), SIMDE_POWER_ALTIVEC_VECTOR(float)) is missing from XL C/C++ v16.1.1, though the documentation (table 89 on page 432 of the IBM XL C/C++ for Linux Compiler Reference, Version 16.1.1) shows that it should be present. Both GCC and clang support it. */ r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpne(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nor(r_.altivec_f32, r_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 != b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] != b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ps(a, b) simde_mm_cmpneq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpneq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] != b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ss(a, b) simde_mm_cmpneq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ps(a, b) simde_mm_cmpnge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ss(a, b) simde_mm_cmpnge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ps(a, b) simde_mm_cmpngt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ss(a, b) simde_mm_cmpngt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ps(a, b) simde_mm_cmpnle_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ss(a, b) simde_mm_cmpnle_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ps(a, b) simde_mm_cmpnlt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ss(a, b) simde_mm_cmpnlt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_and(wasm_f32x4_eq(a, a), wasm_f32x4_eq(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) /* Note: NEON does not have ordered compare builtin Need to compare a eq a and b eq b to check for NaN Do AND of results to get final */ uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vandq_u32(ceqaa, ceqbb); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(wasm_f32x4_eq(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_eq(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_and(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? UINT32_C(0) : ~UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ps(a, b) simde_mm_cmpord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpunord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_or(wasm_f32x4_ne(a, a), wasm_f32x4_ne(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vmvnq_u32(vandq_u32(ceqaa, ceqbb)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(wasm_f32x4_ne(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_ne(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nand(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? ~UINT32_C(0) : UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ps(a, b) simde_mm_cmpunord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpunord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpunord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(a_.f32[0]) || simde_math_isnanf(b_.f32[0])) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ss(a, b) simde_mm_cmpunord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #else return a_.f32[0] == b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comieq_ss(a, b) simde_mm_comieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #else return a_.f32[0] >= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comige_ss(a, b) simde_mm_comige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #else return a_.f32[0] > b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comigt_ss(a, b) simde_mm_comigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #else return a_.f32[0] <= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comile_ss(a, b) simde_mm_comile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #else return a_.f32[0] < b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comilt_ss(a, b) simde_mm_comilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #else return a_.f32[0] != b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comineq_ss(a, b) simde_mm_comineq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_copysign_ps(simde__m128 dest, simde__m128 src) { simde__m128_private r_, dest_ = simde__m128_to_private(dest), src_ = simde__m128_to_private(src); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t sign_pos = vreinterpretq_u32_f32(vdupq_n_f32(-SIMDE_FLOAT32_C(0.0))); r_.neon_u32 = vbslq_u32(sign_pos, src_.neon_u32, dest_.neon_u32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) const v128_t sign_pos = wasm_f32x4_splat(-0.0f); r_.wasm_v128 = wasm_v128_bitselect(src_.wasm_v128, dest_.wasm_v128, sign_pos); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) #if !defined(HEDLEY_IBM_VERSION) r_.altivec_f32 = vec_cpsgn(dest_.altivec_f32, src_.altivec_f32); #else r_.altivec_f32 = vec_cpsgn(src_.altivec_f32, dest_.altivec_f32); #endif #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) const SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) sign_pos = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), vec_splats(-0.0f)); r_.altivec_f32 = vec_sel(dest_.altivec_f32, src_.altivec_f32, sign_pos); #elif defined(SIMDE_IEEE754_STORAGE) (void) src_; (void) dest_; simde__m128 sign_pos = simde_mm_set1_ps(-0.0f); r_ = simde__m128_to_private(simde_mm_xor_ps(dest, simde_mm_and_ps(simde_mm_xor_ps(dest, src), sign_pos))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_copysignf(dest_.f32[i], src_.f32[i]); } #endif return simde__m128_from_private(r_); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_xorsign_ps(simde__m128 dest, simde__m128 src) { return simde_mm_xor_ps(simde_mm_and_ps(simde_mm_set1_ps(-0.0f), src), dest); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_pi2ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_pi2ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_pi2ps(a, b) simde_mm_cvt_pi2ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) && !defined(__clang__) && 0 SIMDE_CONVERT_VECTOR_(r_.i32, a_.m64_private[0].f32); #else a_ = simde__m128_to_private(a); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = HEDLEY_STATIC_CAST(int32_t, simde_math_nearbyintf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ps2pi(a) simde_mm_cvt_ps2pi((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_si2ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_si2ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float, b), a_.neon_f32, 0); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); r_.i32[1] = a_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_si2ss(a, b) simde_mm_cvt_si2ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_ss2si(a); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) return vgetq_lane_s32(vcvtnq_s32_f32(simde__m128_to_neon_f32(a)), 0); #else simde__m128_private a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); return SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ss2si(a) simde_mm_cvt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && 0 /* TODO */ r_.neon_f32 = vmovl_s16(vget_low_s16(vuzp1q_s16(a_.neon_i16, vmovq_n_s16(0)))); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { simde_float32 v = a_.i16[i]; r_.f32[i] = v; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi16_ps(a) simde_mm_cvtpi16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32_ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32_ps(a, b) simde_mm_cvtpi32_ps((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32x2_ps (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32x2_ps(a, b); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vcombine_s32(a_.neon_i32, b_.neon_i32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, a_.i32); SIMDE_CONVERT_VECTOR_(r_.m64_private[1].f32, b_.i32); #else r_.f32[0] = (simde_float32) a_.i32[0]; r_.f32[1] = (simde_float32) a_.i32[1]; r_.f32[2] = (simde_float32) b_.i32[0]; r_.f32[3] = (simde_float32) b_.i32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32x2_ps(a, b) simde_mm_cvtpi32x2_ps(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(vmovl_s8(a_.neon_i8)))); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[0]); r_.f32[1] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[1]); r_.f32[2] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[2]); r_.f32[3] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[3]); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi8_ps(a) simde_mm_cvtpi8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi16 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi16(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i16 = vmovn_s32(vcvtq_s32_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = SIMDE_CONVERT_FTOI(int16_t, simde_math_roundf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi16(a) simde_mm_cvtps_pi16((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi32(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, simde_math_roundf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi32(a) simde_mm_cvtps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi8 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi8(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95471) /* Clamp the input to [INT8_MIN, INT8_MAX], round, convert to i32, narrow to * i16, combine with an all-zero vector of i16 (which will become the upper * half), narrow to i8. */ float32x4_t max = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)); float32x4_t min = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)); float32x4_t values = vrndnq_f32(vmaxq_f32(vminq_f32(max, a_.neon_f32), min)); r_.neon_i8 = vmovn_s16(vcombine_s16(vmovn_s32(vcvtq_s32_f32(values)), vdup_n_s16(0))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.f32) / sizeof(a_.f32[0])) ; i++) { if (a_.f32[i] > HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)) r_.i8[i] = INT8_MAX; else if (a_.f32[i] < HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)) r_.i8[i] = INT8_MIN; else r_.i8[i] = SIMDE_CONVERT_FTOI(int8_t, simde_math_roundf(a_.f32[i])); } /* Note: the upper half is undefined */ #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi8(a) simde_mm_cvtps_pi8((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(a_.neon_u16)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.u16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (simde_float32) a_.u16[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu16_ps(a) simde_mm_cvtpu16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(vget_low_u16(vmovl_u8(a_.neon_u8)))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = HEDLEY_STATIC_CAST(simde_float32, a_.u8[i]); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu8_ps(a) simde_mm_cvtpu8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi32_ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtsi32_ss(a, b); #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtsi32_ss(a, b) simde_mm_cvtsi32_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi64_ss (simde__m128 a, int64_t b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtsi64_ss(a, b); #else return _mm_cvtsi64x_ss(a, b); #endif #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtsi64_ss(a, b) simde_mm_cvtsi64_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde_float32 simde_mm_cvtss_f32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtss_f32(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vgetq_lane_f32(a_.neon_f32, 0); #else return a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_f32(a) simde_mm_cvtss_f32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtss_si32 (simde__m128 a) { return simde_mm_cvt_ss2si(a); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_si32(a) simde_mm_cvtss_si32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvtss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtss_si64(a); #else return _mm_cvtss_si64x(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(vgetq_lane_f32(a_.neon_f32, 0))); #else return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(a_.f32[0])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_si64(a) simde_mm_cvtss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.i32, a_.m64_private[0].f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, a_.f32[i]); } #endif return simde__m64_from_private(r_); #endif } #define simde_mm_cvttps_pi32(a) simde_mm_cvtt_ps2pi(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ps2pi(a) simde_mm_cvtt_ps2pi((a)) # define _mm_cvttps_pi32(a) simde_mm_cvttps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtt_ss2si(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int32_t, vgetq_lane_f32(a_.neon_f32, 0)); #else return SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]); #endif #endif } #define simde_mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ss2si(a) simde_mm_cvtt_ss2si((a)) # define _mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvttss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) && !defined(_MSC_VER) #if defined(__PGI) return _mm_cvttss_si64x(a); #else return _mm_cvttss_si64(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, vgetq_lane_f32(a_.neon_f32, 0)); #else return SIMDE_CONVERT_FTOI(int64_t, a_.f32[0]); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvttss_si64(a) simde_mm_cvttss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(simde_mm_cvtss_f32(a)) || simde_math_isnanf(simde_mm_cvtss_f32(b))) ? UINT32_C(0) : ~UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ss(a, b) simde_mm_cmpord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vdivq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip0 = vrecpeq_f32(b_.neon_f32); float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, b_.neon_f32)); r_.neon_f32 = vmulq_f32(a_.neon_f32, recip1); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_div(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 / b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] / b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ps(a, b) simde_mm_div_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_div_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_div_ps(a, b)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = a_.f32[0] / b_.f32[0]; SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ss(a, b) simde_mm_div_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int16_t simde_mm_extract_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private a_ = simde__m64_to_private(a); return a_.i16[imm8]; } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(HEDLEY_PGI_VERSION) # if HEDLEY_HAS_WARNING("-Wvector-conversion") /* https://bugs.llvm.org/show_bug.cgi?id=44589 */ # define simde_mm_extract_pi16(a, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16((a), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_extract_pi16(a, imm8) HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16(a, imm8)) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_extract_pi16(a, imm8) vget_lane_s16(simde__m64_to_private(a).neon_i16, imm8) #endif #define simde_m_pextrw(a, imm8) simde_mm_extract_pi16(a, imm8) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_extract_pi16(a, imm8) simde_mm_extract_pi16((a), (imm8)) # define _m_pextrw(a, imm8) simde_mm_extract_pi16((a), (imm8)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_insert_pi16 (simde__m64 a, int16_t i, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private r_, a_ = simde__m64_to_private(a); r_.i64[0] = a_.i64[0]; r_.i16[imm8] = i; return simde__m64_from_private(r_); } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # if HEDLEY_HAS_WARNING("-Wvector-conversion") /* https://bugs.llvm.org/show_bug.cgi?id=44589 */ # define ssimde_mm_insert_pi16(a, i, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ (_mm_insert_pi16((a), (i), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_insert_pi16(a, i, imm8) _mm_insert_pi16(a, i, imm8) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_insert_pi16(a, i, imm8) simde__m64_from_neon_i16(vset_lane_s16((i), simde__m64_to_neon_i16(a), (imm8))) #endif #define simde_m_pinsrw(a, i, imm8) (simde_mm_insert_pi16(a, i, imm8)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_insert_pi16(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) # define _m_pinsrw(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_ld(0, mem_addr); #else simde_memcpy(&r_, SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128), sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps(mem_addr) simde_mm_load_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load1_ps (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps1(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_dup_f32(mem_addr); #else r_ = simde__m128_to_private(simde_mm_set1_ps(*mem_addr)); #endif return simde__m128_from_private(r_); #endif } #define simde_mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) # define _mm_load1_ps(mem_addr) simde_mm_load1_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ss (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ss(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(*mem_addr, vdupq_n_f32(0), 0); #else r_.f32[0] = *mem_addr; r_.i32[1] = 0; r_.i32[2] = 0; r_.i32[3] = 0; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ss(mem_addr) simde_mm_load_ss(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadh_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_loadh_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vget_low_f32(a_.neon_f32), vld1_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr))); #else simde__m64_private b_ = *HEDLEY_REINTERPRET_CAST(simde__m64_private const*, mem_addr); r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadh_pi(a, mem_addr) simde_mm_loadh_pi((a), (simde__m64 const*) (mem_addr)) #endif /* The SSE documentation says that there are no alignment requirements for mem_addr. Unfortunately they used the __m64 type for the argument which is supposed to be 8-byte aligned, so some compilers (like clang with -Wcast-align) will generate a warning if you try to cast, say, a simde_float32* to a simde__m64* for this function. I think the choice of argument type is unfortunate, but I do think we need to stick to it here. If there is demand I can always add something like simde_x_mm_loadl_f32(simde__m128, simde_float32 mem_addr[2]) */ SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadl_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadl_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vld1_f32( HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)), vget_high_f32(a_.neon_f32)); #else simde__m64_private b_; simde_memcpy(&b_, mem_addr, sizeof(b_)); r_.i32[0] = b_.i32[0]; r_.i32[1] = b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadl_pi(a, mem_addr) simde_mm_loadl_pi((a), (simde__m64 const*) (mem_addr)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadr_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadr_ps(mem_addr); #else simde__m128_private r_, v_ = simde__m128_to_private(simde_mm_load_ps(mem_addr)); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrev64q_f32(v_.neon_f32); r_.neon_f32 = vextq_f32(r_.neon_f32, r_.neon_f32, 2); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_reve(v_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, v_.f32, v_.f32, 3, 2, 1, 0); #else r_.f32[0] = v_.f32[3]; r_.f32[1] = v_.f32[2]; r_.f32[2] = v_.f32[1]; r_.f32[3] = v_.f32[0]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadr_ps(mem_addr) simde_mm_loadr_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadu_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadu_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_load(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #else simde_memcpy(&r_, mem_addr, sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadu_ps(mem_addr) simde_mm_loadu_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_maskmove_si64 (simde__m64 a, simde__m64 mask, int8_t* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_maskmove_si64(a, mask, HEDLEY_REINTERPRET_CAST(char*, mem_addr)); #else simde__m64_private a_ = simde__m64_to_private(a), mask_ = simde__m64_to_private(mask); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.i8) / sizeof(a_.i8[0])) ; i++) if (mask_.i8[i] < 0) mem_addr[i] = a_.i8[i]; #endif } #define simde_m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64(a, mask, mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_maskmove_si64(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) # define _m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmax_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] > b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pi16(a, b) simde_mm_max_pi16(a, b) # define _m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vmaxq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_max(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_max(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] > b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ps(a, b) simde_mm_max_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmax_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] > b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxub(a, b) simde_mm_max_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pu8(a, b) simde_mm_max_pu8(a, b) # define _m_pmaxub(a, b) simde_mm_max_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_max_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(maxq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] > b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ss(a, b) simde_mm_max_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmin_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] < b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminsw(a, b) simde_mm_min_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pi16(a, b) simde_mm_min_pi16(a, b) # define _m_pminsw(a, b) simde_mm_min_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ps(a, b); #elif defined(SIMDE_FAST_NANS) && defined(SIMDE_ARM_NEON_A32V7_NATIVE) return simde__m128_from_neon_f32(vminq_f32(simde__m128_to_neon_f32(a), simde__m128_to_neon_f32(b))); #elif defined(SIMDE_WASM_SIMD128_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.wasm_v128 = wasm_f32x4_min(a_.wasm_v128, b_.wasm_v128); #else r_.wasm_v128 = wasm_v128_bitselect(a_.wasm_v128, b_.wasm_v128, wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128)); #endif return simde__m128_from_private(r_); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.altivec_f32 = vec_min(a_.altivec_f32, b_.altivec_f32); #else r_.altivec_f32 = vec_sel(b_.altivec_f32, a_.altivec_f32, vec_cmpgt(b_.altivec_f32, a_.altivec_f32)); #endif return simde__m128_from_private(r_); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) simde__m128 mask = simde_mm_cmplt_ps(a, b); return simde_mm_or_ps(simde_mm_and_ps(mask, a), simde_mm_andnot_ps(mask, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] < b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ps(a, b) simde_mm_min_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmin_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] < b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminub(a, b) simde_mm_min_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pu8(a, b) simde_mm_min_pu8(a, b) # define _m_pminub(a, b) simde_mm_min_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_min_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(vminq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] < b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ss(a, b) simde_mm_min_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movehl_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movehl_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a32 = vget_high_f32(a_.neon_f32); float32x2_t b32 = vget_high_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(b32, a32); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergel(b_.altivec_i64, a_.altivec_i64)); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 6, 7, 2, 3); #else r_.f32[0] = b_.f32[2]; r_.f32[1] = b_.f32[3]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movehl_ps(a, b) simde_mm_movehl_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movelh_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movelh_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a10 = vget_low_f32(a_.neon_f32); float32x2_t b10 = vget_low_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(a10, b10); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 1, 4, 5); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergeh(a_.altivec_i64, b_.altivec_i64)); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movelh_ps(a, b) simde_mm_movelh_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_pi8 (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_pi8(a); #else simde__m64_private a_ = simde__m64_to_private(a); int r = 0; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) uint8x8_t input = a_.neon_u8; const int8_t xr[8] = {-7, -6, -5, -4, -3, -2, -1, 0}; const uint8x8_t mask_and = vdup_n_u8(0x80); const int8x8_t mask_shift = vld1_s8(xr); const uint8x8_t mask_result = vshl_u8(vand_u8(input, mask_and), mask_shift); uint8x8_t lo = mask_result; r = vaddv_u8(lo); #else const size_t nmemb = sizeof(a_.i8) / sizeof(a_.i8[0]); SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < nmemb ; i++) { r |= (a_.u8[nmemb - 1 - i] >> 7) << (nmemb - 1 - i); } #endif return r; #endif } #define simde_m_pmovmskb(a) simde_mm_movemask_pi8(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_pi8(a) simde_mm_movemask_pi8(a) # define _m_pmovmskb(a) simde_mm_movemask_pi8(a) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_ps(a); #else int r = 0; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) static const int32_t shift_amount[] = { 0, 1, 2, 3 }; const int32x4_t shift = vld1q_s32(shift_amount); uint32x4_t tmp = vshrq_n_u32(a_.neon_u32, 31); return HEDLEY_STATIC_CAST(int, vaddvq_u32(vshlq_u32(tmp, shift))); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) // Shift out everything but the sign bits with a 32-bit unsigned shift right. uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(a_.neon_u32, 31)); // Merge the two pairs together with a 64-bit unsigned shift right + add. uint8x16_t paired = vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); // Extract the result. return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); #else SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < sizeof(a_.u32) / sizeof(a_.u32[0]) ; i++) { r |= (a_.u32[i] >> ((sizeof(a_.u32[i]) * CHAR_BIT) - 1)) << i; } #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_ps(a) simde_mm_movemask_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vmulq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_mul(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 * b_.f32; #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_mul(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] * b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ps(a, b) simde_mm_mul_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_mul_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] * b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ss(a, b) simde_mm_mul_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_mulhi_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_mulhi_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t t1 = vmull_u16(a_.neon_u16, b_.neon_u16); const uint32x4_t t2 = vshrq_n_u32(t1, 16); const uint16x4_t t3 = vmovn_u32(t2); r_.neon_u16 = t3; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = HEDLEY_STATIC_CAST(uint16_t, ((HEDLEY_STATIC_CAST(uint32_t, a_.u16[i]) * HEDLEY_STATIC_CAST(uint32_t, b_.u16[i])) >> UINT32_C(16))); } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mulhi_pu16(a, b) simde_mm_mulhi_pu16(a, b) # define _m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_prefetch (char const* p, int i) { #if defined(HEDLEY_GCC_VERSION) __builtin_prefetch(p); #else (void) p; #endif (void) i; } #if defined(SIMDE_X86_SSE_NATIVE) # define simde_mm_prefetch(p, i) _mm_prefetch(p, i) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_prefetch(p, i) simde_mm_prefetch(p, i) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_negate_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return simde_mm_xor_ps(a, _mm_set1_ps(SIMDE_FLOAT32_C(-0.0))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) && \ (!defined(HEDLEY_GCC_VERSION) || HEDLEY_GCC_VERSION_CHECK(8,1,0)) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vnegq_f32(a_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_neg(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_VECTOR_NEGATE) r_.f32 = -a_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = -a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip = vrecpeq_f32(a_.neon_f32); #if SIMDE_ACCURACY_PREFERENCE > 0 for (int i = 0; i < SIMDE_ACCURACY_PREFERENCE ; ++i) { recip = vmulq_f32(recip, vrecpsq_f32(recip, a_.neon_f32)); } #endif r_.neon_f32 = recip; #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(simde_mm_set1_ps(1.0f), a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_re(a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) r_.f32 = 1.0f / a_.f32; #elif defined(SIMDE_IEEE754_STORAGE) /* https://stackoverflow.com/questions/12227126/division-as-multiply-and-lut-fast-float-division-reciprocal/12228234#12228234 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { int32_t ix; simde_float32 fx = a_.f32[i]; simde_memcpy(&ix, &fx, sizeof(ix)); int32_t x = INT32_C(0x7EF311C3) - ix; simde_float32 temp; simde_memcpy(&temp, &x, sizeof(temp)); r_.f32[i] = temp * (SIMDE_FLOAT32_C(2.0) - temp * fx); } #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ps(a) simde_mm_rcp_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rcp_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); r_.f32[0] = 1.0f / a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ss(a) simde_mm_rcp_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrsqrteq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_rsqrte(a_.altivec_f32); #elif defined(SIMDE_IEEE754_STORAGE) /* https://basesandframes.files.wordpress.com/2020/04/even_faster_math_functions_green_2020.pdf Pages 100 - 103 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[i] = INT32_C(0x5F37624F) - (a_.i32[i] >> 1); #else simde_float32 x = a_.f32[i]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[i] = x; #endif } #elif defined(simde_math_sqrtf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ps(a) simde_mm_rsqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rsqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(simde_mm_rsqrt_ps(a).neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_IEEE754_STORAGE) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[0] = INT32_C(0x5F37624F) - (a_.i32[0] >> 1); #else simde_float32 x = a_.f32[0]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[0] = x; #endif } r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #elif defined(simde_math_sqrtf) r_.f32[0] = 1.0f / simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ss(a) simde_mm_rsqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_sad_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_sad_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint16x4_t t = vpaddl_u8(vabd_u8(a_.neon_u8, b_.neon_u8)); uint16_t r0 = t[0] + t[1] + t[2] + t[3]; r_.neon_u16 = vset_lane_u16(r0, vdup_n_u16(0), 0); #else uint16_t sum = 0; #if defined(SIMDE_HAVE_STDLIB_H) SIMDE_VECTORIZE_REDUCTION(+:sum) for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { sum += HEDLEY_STATIC_CAST(uint8_t, abs(a_.u8[i] - b_.u8[i])); } r_.i16[0] = HEDLEY_STATIC_CAST(int16_t, sum); r_.i16[1] = 0; r_.i16[2] = 0; r_.i16[3] = 0; #else HEDLEY_UNREACHABLE(); #endif #endif return simde__m64_from_private(r_); #endif } #define simde_m_psadbw(a, b) simde_mm_sad_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sad_pu8(a, b) simde_mm_sad_pu8(a, b) # define _m_psadbw(a, b) simde_mm_sad_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ss (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ss(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vsetq_lane_f32(a, vdupq_n_f32(SIMDE_FLOAT32_C(0.0)), 0); #else return simde_mm_set_ps(SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ss(a) simde_mm_set_ss(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setr_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setr_ps(e3, e2, e1, e0); #else return simde_mm_set_ps(e0, e1, e2, e3); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setr_ps(e3, e2, e1, e0) simde_mm_setr_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setzero_ps (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setzero_ps(); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(SIMDE_FLOAT32_C(0.0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) return vec_splats(SIMDE_FLOAT32_C(0.0)); #else simde__m128 r; simde_memset(&r, 0, sizeof(r)); return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setzero_ps() simde_mm_setzero_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_undefined_ps (void) { simde__m128_private r_; #if defined(SIMDE_HAVE_UNDEFINED128) r_.n = _mm_undefined_ps(); #elif !defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) r_ = simde__m128_to_private(simde_mm_setzero_ps()); #endif return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_undefined_ps() simde_mm_undefined_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_POP #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_setone_ps (void) { simde__m128 t = simde_mm_setzero_ps(); return simde_mm_cmpeq_ps(t, t); } SIMDE_FUNCTION_ATTRIBUTES void simde_mm_sfence (void) { /* TODO: Use Hedley. */ #if defined(SIMDE_X86_SSE_NATIVE) _mm_sfence(); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) __atomic_thread_fence(__ATOMIC_SEQ_CST); #elif !defined(__INTEL_COMPILER) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9) __atomic_thread_fence(__ATOMIC_SEQ_CST); #else atomic_thread_fence(memory_order_seq_cst); #endif #elif defined(_MSC_VER) MemoryBarrier(); #elif HEDLEY_HAS_EXTENSION(c_atomic) __c11_atomic_thread_fence(__ATOMIC_SEQ_CST); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) __sync_synchronize(); #elif defined(_OPENMP) #pragma omp critical(simde_mm_sfence_) { } #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sfence() simde_mm_sfence() #endif #define SIMDE_MM_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_SHUFFLE(z, y, x, w) SIMDE_MM_SHUFFLE(z, y, x, w) #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_pi16(a, imm8) _mm_shuffle_pi16(a, imm8) #elif defined(SIMDE_SHUFFLE_VECTOR_) # define simde_mm_shuffle_pi16(a, imm8) (__extension__ ({ \ const simde__m64_private simde__tmp_a_ = simde__m64_to_private(a); \ simde__m64_from_private((simde__m64_private) { .i16 = \ SIMDE_SHUFFLE_VECTOR_(16, 8, \ (simde__tmp_a_).i16, \ (simde__tmp_a_).i16, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3), \ (((imm8) >> 6) & 3)) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_shuffle_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m64_private r_; simde__m64_private a_ = simde__m64_to_private(a); for (size_t i = 0 ; i < sizeof(r_.i16) / sizeof(r_.i16[0]) ; i++) { r_.i16[i] = a_.i16[(imm8 >> (i * 2)) & 3]; } HEDLEY_DIAGNOSTIC_PUSH #if HEDLEY_HAS_WARNING("-Wconditional-uninitialized") # pragma clang diagnostic ignored "-Wconditional-uninitialized" #endif return simde__m64_from_private(r_); HEDLEY_DIAGNOSTIC_POP } #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_m_pshufw(a, imm8) _m_pshufw(a, imm8) #else # define simde_m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_pi16(a, imm8) simde_mm_shuffle_pi16(a, imm8) # define _m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_ps(a, b, imm8) _mm_shuffle_ps(a, b, imm8) #elif defined(SIMDE_SHUFFLE_VECTOR_) && 0 # define simde_mm_shuffle_ps(a, b, imm8) (__extension__ ({ \ simde__m128_from_private((simde__m128_private) { .f32 = \ SIMDE_SHUFFLE_VECTOR_(32, 16, \ simde__m128_to_private(a).f32, \ simde__m128_to_private(b).f32, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3) + 4, \ (((imm8) >> 6) & 3) + 4) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_shuffle_ps (simde__m128 a, simde__m128 b, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[(imm8 >> 0) & 3]; r_.f32[1] = a_.f32[(imm8 >> 2) & 3]; r_.f32[2] = b_.f32[(imm8 >> 4) & 3]; r_.f32[3] = b_.f32[(imm8 >> 6) & 3]; return simde__m128_from_private(r_); } #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_ps(a, b, imm8) simde_mm_shuffle_ps((a), (b), imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vsqrtq_f32(a_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t est = vrsqrteq_f32(a_.neon_f32); for (int i = 0 ; i <= SIMDE_ACCURACY_PREFERENCE ; i++) { est = vmulq_f32(vrsqrtsq_f32(vmulq_f32(a_.neon_f32, est), est), est); } r_.neon_f32 = vmulq_f32(a_.neon_f32, est); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sqrt(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_sqrt(a_.altivec_f32); #elif defined(simde_math_sqrt) SIMDE_VECTORIZE for (size_t i = 0 ; i < sizeof(r_.f32) / sizeof(r_.f32[0]) ; i++) { r_.f32[i] = simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ps(a) simde_mm_sqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_sqrt_ps(a)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #elif defined(simde_math_sqrtf) r_.f32[0] = simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ss(a) simde_mm_sqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P5_NATIVE) vec_st(a_.altivec_f32, 0, mem_addr); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr, a_.wasm_v128); #else simde_memcpy(mem_addr, &a_, sizeof(a)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps(mem_addr, a) simde_mm_store_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store1_ps (simde_float32 mem_addr[4], simde__m128 a) { simde_float32* mem_addr_ = SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128); #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps1(mem_addr_, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr_, vdupq_lane_f32(vget_low_f32(a_.neon_f32), 0)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr_, wasm_v32x4_shuffle(a_.wasm_v128, a_.wasm_v128, 0, 0, 0, 0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_splat(a_.altivec_f32, 0), 0, mem_addr_); #elif defined(SIMDE_SHUFFLE_VECTOR_) simde__m128_private tmp_; tmp_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 0, 0, 0, 0); simde_mm_store_ps(mem_addr_, tmp_.f32); #else SIMDE_VECTORIZE_ALIGNED(mem_addr_:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr_[i] = a_.f32[0]; } #endif #endif } #define simde_mm_store_ps1(mem_addr, a) simde_mm_store1_ps(mem_addr, a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps1(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) # define _mm_store1_ps(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ss (simde_float32* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ss(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_lane_f32(mem_addr, a_.neon_f32, 0); #else *mem_addr = a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ss(mem_addr, a) simde_mm_store_ss(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeh_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeh_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1_f32(HEDLEY_REINTERPRET_CAST(float32_t*, mem_addr), vget_high_f32(a_.neon_f32)); #else simde_memcpy(mem_addr, &(a_.m64[1]), sizeof(a_.m64[1])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeh_pi(mem_addr, a) simde_mm_storeh_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storel_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storel_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest_ = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr); simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest_->neon_f32 = vget_low_f32(a_.neon_f32); #else dest_->f32[0] = a_.f32[0]; dest_->f32[1] = a_.f32[1]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storel_pi(mem_addr, a) simde_mm_storel_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storer_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storer_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_reve(a_.altivec_f32), 0, mem_addr); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t tmp = vrev64q_f32(a_.neon_f32); vst1q_f32(mem_addr, vextq_f32(tmp, tmp, 2)); #elif defined(SIMDE_SHUFFLE_VECTOR_) a_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 3, 2, 1, 0); simde_mm_store_ps(mem_addr, simde__m128_from_private(a_)); #else SIMDE_VECTORIZE_ALIGNED(mem_addr:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr[i] = a_.f32[((sizeof(a_.f32) / sizeof(a_.f32[0])) - 1) - i]; } #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storer_ps(mem_addr, a) simde_mm_storer_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeu_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeu_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) vec_vsx_st(a_.altivec_f32, 0, mem_addr); #else simde_memcpy(mem_addr, &a_, sizeof(a_)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeu_ps(mem_addr, a) simde_mm_storeu_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsubq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sub(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_sub(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 - b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] - b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ps(a, b) simde_mm_sub_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sub_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] - b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ss(a, b) simde_mm_sub_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] == b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] == b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomieq_ss(a, b) simde_mm_ucomieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] >= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] >= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomige_ss(a, b) simde_mm_ucomige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] > b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] > b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomigt_ss(a, b) simde_mm_ucomigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] <= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] <= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomile_ss(a, b) simde_mm_ucomile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] < b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] < b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomilt_ss(a, b) simde_mm_ucomilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] != b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] != b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomineq_ss(a, b) simde_mm_ucomineq_ss((a), (b)) #endif #if defined(SIMDE_X86_SSE_NATIVE) # if defined(__has_builtin) # if __has_builtin(__builtin_ia32_undef128) # define SIMDE_HAVE_UNDEFINED128 # endif # elif !defined(__PGI) && !defined(SIMDE_BUG_GCC_REV_208793) && !defined(_MSC_VER) # define SIMDE_HAVE_UNDEFINED128 # endif #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpackhi_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpackhi_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip2q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_high_f32(a_.neon_f32); float32x2_t b1 = vget_high_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 2, 6, 3, 7); #else r_.f32[0] = a_.f32[2]; r_.f32[1] = b_.f32[2]; r_.f32[2] = a_.f32[3]; r_.f32[3] = b_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpackhi_ps(a, b) simde_mm_unpackhi_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpacklo_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpacklo_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip1q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_mergeh(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 4, 1, 5); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_low_f32(a_.neon_f32); float32x2_t b1 = vget_low_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = b_.f32[0]; r_.f32[2] = a_.f32[1]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpacklo_ps(a, b) simde_mm_unpacklo_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_pi (simde__m64* mem_addr, simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_stream_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr), a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest->i64[0] = vget_lane_s64(a_.neon_i64, 0); #else dest->i64[0] = a_.i64[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_pi(mem_addr, a) simde_mm_stream_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_stream_ps(mem_addr, a); #elif HEDLEY_HAS_BUILTIN(__builtin_nontemporal_store) && defined(SIMDE_VECTOR_SUBSCRIPT_OPS) simde__m128_private a_ = simde__m128_to_private(a); __builtin_nontemporal_store(a_.f32, SIMDE_ALIGN_CAST(__typeof__(a_.f32)*, mem_addr)); #else simde_mm_store_ps(mem_addr, a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_ps(mem_addr, a) simde_mm_stream_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ float32x4x2_t ROW01 = vtrnq_f32(row0, row1); \ float32x4x2_t ROW23 = vtrnq_f32(row2, row3); \ row0 = vcombine_f32(vget_low_f32(ROW01.val[0]), \ vget_low_f32(ROW23.val[0])); \ row1 = vcombine_f32(vget_low_f32(ROW01.val[1]), \ vget_low_f32(ROW23.val[1])); \ row2 = vcombine_f32(vget_high_f32(ROW01.val[0]), \ vget_high_f32(ROW23.val[0])); \ row3 = vcombine_f32(vget_high_f32(ROW01.val[1]), \ vget_high_f32(ROW23.val[1])); \ } while (0) #else #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ simde__m128 tmp3, tmp2, tmp1, tmp0; \ tmp0 = simde_mm_unpacklo_ps((row0), (row1)); \ tmp2 = simde_mm_unpacklo_ps((row2), (row3)); \ tmp1 = simde_mm_unpackhi_ps((row0), (row1)); \ tmp3 = simde_mm_unpackhi_ps((row2), (row3)); \ row0 = simde_mm_movelh_ps(tmp0, tmp2); \ row1 = simde_mm_movehl_ps(tmp2, tmp0); \ row2 = simde_mm_movelh_ps(tmp1, tmp3); \ row3 = simde_mm_movehl_ps(tmp3, tmp1); \ } while (0) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_TRANSPOSE4_PS(row0, row1, row2, row3) SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) #endif #if defined(_MM_EXCEPT_INVALID) # define SIMDE_MM_EXCEPT_INVALID _MM_EXCEPT_INVALID #else # define SIMDE_MM_EXCEPT_INVALID (0x0001) #endif #if defined(_MM_EXCEPT_DENORM) # define SIMDE_MM_EXCEPT_DENORM _MM_EXCEPT_DENORM #else # define SIMDE_MM_EXCEPT_DENORM (0x0002) #endif #if defined(_MM_EXCEPT_DIV_ZERO) # define SIMDE_MM_EXCEPT_DIV_ZERO _MM_EXCEPT_DIV_ZERO #else # define SIMDE_MM_EXCEPT_DIV_ZERO (0x0004) #endif #if defined(_MM_EXCEPT_OVERFLOW) # define SIMDE_MM_EXCEPT_OVERFLOW _MM_EXCEPT_OVERFLOW #else # define SIMDE_MM_EXCEPT_OVERFLOW (0x0008) #endif #if defined(_MM_EXCEPT_UNDERFLOW) # define SIMDE_MM_EXCEPT_UNDERFLOW _MM_EXCEPT_UNDERFLOW #else # define SIMDE_MM_EXCEPT_UNDERFLOW (0x0010) #endif #if defined(_MM_EXCEPT_INEXACT) # define SIMDE_MM_EXCEPT_INEXACT _MM_EXCEPT_INEXACT #else # define SIMDE_MM_EXCEPT_INEXACT (0x0020) #endif #if defined(_MM_EXCEPT_MASK) # define SIMDE_MM_EXCEPT_MASK _MM_EXCEPT_MASK #else # define SIMDE_MM_EXCEPT_MASK \ (SIMDE_MM_EXCEPT_INVALID | SIMDE_MM_EXCEPT_DENORM | \ SIMDE_MM_EXCEPT_DIV_ZERO | SIMDE_MM_EXCEPT_OVERFLOW | \ SIMDE_MM_EXCEPT_UNDERFLOW | SIMDE_MM_EXCEPT_INEXACT) #endif #if defined(_MM_MASK_INVALID) # define SIMDE_MM_MASK_INVALID _MM_MASK_INVALID #else # define SIMDE_MM_MASK_INVALID (0x0080) #endif #if defined(_MM_MASK_DENORM) # define SIMDE_MM_MASK_DENORM _MM_MASK_DENORM #else # define SIMDE_MM_MASK_DENORM (0x0100) #endif #if defined(_MM_MASK_DIV_ZERO) # define SIMDE_MM_MASK_DIV_ZERO _MM_MASK_DIV_ZERO #else # define SIMDE_MM_MASK_DIV_ZERO (0x0200) #endif #if defined(_MM_MASK_OVERFLOW) # define SIMDE_MM_MASK_OVERFLOW _MM_MASK_OVERFLOW #else # define SIMDE_MM_MASK_OVERFLOW (0x0400) #endif #if defined(_MM_MASK_UNDERFLOW) # define SIMDE_MM_MASK_UNDERFLOW _MM_MASK_UNDERFLOW #else # define SIMDE_MM_MASK_UNDERFLOW (0x0800) #endif #if defined(_MM_MASK_INEXACT) # define SIMDE_MM_MASK_INEXACT _MM_MASK_INEXACT #else # define SIMDE_MM_MASK_INEXACT (0x1000) #endif #if defined(_MM_MASK_MASK) # define SIMDE_MM_MASK_MASK _MM_MASK_MASK #else # define SIMDE_MM_MASK_MASK \ (SIMDE_MM_MASK_INVALID | SIMDE_MM_MASK_DENORM | \ SIMDE_MM_MASK_DIV_ZERO | SIMDE_MM_MASK_OVERFLOW | \ SIMDE_MM_MASK_UNDERFLOW | SIMDE_MM_MASK_INEXACT) #endif #if defined(_MM_FLUSH_ZERO_MASK) # define SIMDE_MM_FLUSH_ZERO_MASK _MM_FLUSH_ZERO_MASK #else # define SIMDE_MM_FLUSH_ZERO_MASK (0x8000) #endif #if defined(_MM_FLUSH_ZERO_ON) # define SIMDE_MM_FLUSH_ZERO_ON _MM_FLUSH_ZERO_ON #else # define SIMDE_MM_FLUSH_ZERO_ON (0x8000) #endif #if defined(_MM_FLUSH_ZERO_OFF) # define SIMDE_MM_FLUSH_ZERO_OFF _MM_FLUSH_ZERO_OFF #else # define SIMDE_MM_FLUSH_ZERO_OFF (0x0000) #endif SIMDE_END_DECLS_ HEDLEY_DIAGNOSTIC_POP #endif /* !defined(SIMDE_X86_SSE_H) */
solver.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include "litiv/3rdparty/ofdis/fdf/image.h" #include "litiv/3rdparty/ofdis/fdf/solver.h" #include "litiv/utils/defines.hpp" // only used here for compiler flags #if defined(_MSC_VER) #include <intrin.h> #else //(!defined(_MSC_VER)) #include <x86intrin.h> #endif //(!defined(_MSC_VER)) typedef __v4sf v4sf; //THIS IS A SLOW VERSION BUT READABLE //Perform n iterations of the sor_coupled algorithm //du and dv are used as initial guesses //The system form is the same as in opticalflow.c void sor_coupled_slow_but_readable(image_t *du, image_t *dv, image_t *a11, image_t *a12, image_t *a22, const image_t *b1, const image_t *b2, const image_t *dpsis_horiz, const image_t *dpsis_vert, const int iterations, const float omega) { int i,j,iter; for(iter = 0 ; iter<iterations ; iter++) { #if USE_OPENMP #pragma omp parallel for #endif //USE_OPENMP for(j=0 ; j<du->height ; j++) { float sigma_u,sigma_v,sum_dpsis,A11,A22,A12,B1,B2;//,det; for(i=0 ; i<du->width ; i++) { sigma_u = 0.0f; sigma_v = 0.0f; sum_dpsis = 0.0f; if(j>0) { sigma_u -= dpsis_vert->c1[(j-1)*du->stride+i]*du->c1[(j-1)*du->stride+i]; sigma_v -= dpsis_vert->c1[(j-1)*du->stride+i]*dv->c1[(j-1)*du->stride+i]; sum_dpsis += dpsis_vert->c1[(j-1)*du->stride+i]; } if(i>0) { sigma_u -= dpsis_horiz->c1[j*du->stride+i-1]*du->c1[j*du->stride+i-1]; sigma_v -= dpsis_horiz->c1[j*du->stride+i-1]*dv->c1[j*du->stride+i-1]; sum_dpsis += dpsis_horiz->c1[j*du->stride+i-1]; } if(j<du->height-1) { sigma_u -= dpsis_vert->c1[j*du->stride+i]*du->c1[(j+1)*du->stride+i]; sigma_v -= dpsis_vert->c1[j*du->stride+i]*dv->c1[(j+1)*du->stride+i]; sum_dpsis += dpsis_vert->c1[j*du->stride+i]; } if(i<du->width-1) { sigma_u -= dpsis_horiz->c1[j*du->stride+i]*du->c1[j*du->stride+i+1]; sigma_v -= dpsis_horiz->c1[j*du->stride+i]*dv->c1[j*du->stride+i+1]; sum_dpsis += dpsis_horiz->c1[j*du->stride+i]; } A11 = a11->c1[j*du->stride+i]+sum_dpsis; A12 = a12->c1[j*du->stride+i]; A22 = a22->c1[j*du->stride+i]+sum_dpsis; //det = A11*A22-A12*A12; B1 = b1->c1[j*du->stride+i]-sigma_u; B2 = b2->c1[j*du->stride+i]-sigma_v; // du->c1[j*du->stride+i] = (1.0f-omega)*du->c1[j*du->stride+i] +omega*( A22*B1-A12*B2)/det; // dv->c1[j*du->stride+i] = (1.0f-omega)*dv->c1[j*du->stride+i] +omega*(-A12*B1+A11*B2)/det; du->c1[j*du->stride+i] = (1.0f-omega)*du->c1[j*du->stride+i] + omega/A11 *(B1 - A12* dv->c1[j*du->stride+i] ); dv->c1[j*du->stride+i] = (1.0f-omega)*dv->c1[j*du->stride+i] + omega/A22 *(B2 - A12* du->c1[j*du->stride+i] ); } } } } // THIS IS A FASTER VERSION BUT UNREADABLE, ONLY OPTICAL FLOW WITHOUT OPENMP PARALLELIZATION // the first iteration is separated from the other to compute the inverse of the 2x2 block diagonal // each iteration is split in two first line / middle lines / last line, and the left block is computed separately on each line void sor_coupled(image_t *du, image_t *dv, image_t *a11, image_t *a12, image_t *a22, const image_t *b1, const image_t *b2, const image_t *dpsis_horiz, const image_t *dpsis_vert, const int iterations, const float omega){ //sor_coupled_slow(du,dv,a11,a12,a22,b1,b2,dpsis_horiz,dpsis_vert,iterations,omega); return; printf("test\n"); if(du->width<2 || du->height<2 || iterations < 1){ sor_coupled_slow_but_readable(du,dv,a11,a12,a22,b1,b2,dpsis_horiz,dpsis_vert,iterations,omega); return; } const int stride = du->stride, width = du->width; const int iterheight = du->height-1, iterline = (stride)/4, width_minus_1_sizeoffloat = sizeof(float)*(width-1); int j,iter,i,k; float *floatarray = (float*) memalign(16, stride*sizeof(float)*3); if(floatarray==NULL){ fprintf(stderr, "error in sor_coupled(): not enough memory\n"); exit(1); } float *f1 = floatarray; float *f2 = f1+stride; float *f3 = f2+stride; f1[0] = 0.0f; memset(&f1[width], 0, sizeof(float)*(stride-width)); memset(&f2[width-1], 0, sizeof(float)*(stride-width+1)); memset(&f3[width-1], 0, sizeof(float)*(stride-width+1)); { // first iteration v4sf *a11p = (v4sf*) a11->c1, *a12p = (v4sf*) a12->c1, *a22p = (v4sf*) a22->c1, *b1p = (v4sf*) b1->c1, *b2p = (v4sf*) b2->c1, *hp = (v4sf*) dpsis_horiz->c1, *vp = (v4sf*) dpsis_vert->c1; float *du_ptr = du->c1, *dv_ptr = dv->c1; v4sf *dub = (v4sf*) (du_ptr+stride), *dvb = (v4sf*) (dv_ptr+stride); { // first iteration - first line memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vp); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vp)*(*dvb) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline;--i;){ // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vp); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vp)*(*dvb) + (*b2p); for(k=0;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } v4sf *vpt = (v4sf*) dpsis_vert->c1; v4sf *dut = (v4sf*) du->c1, *dvt = (v4sf*) dv->c1; for(j=iterheight;--j;){ // first iteration - middle lines memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vpt) + (*vp); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*vp)*(*dvb) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline;--i;){ // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vpt) + (*vp); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*vp)*(*dvb) + (*b2p); for(k=0;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } { // first iteration - last line memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vpt); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline;--i;){ // reverse 2x2 diagonal block const v4sf dpsis = (*hpl) + (*hp) + (*vpt); const v4sf A11 = (*a22p)+dpsis, A22 = (*a11p)+dpsis; const v4sf det = A11*A22 - (*a12p)*(*a12p); *a11p = A11/det; *a22p = A22/det; *a12p /= -det; // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*b2p); for(k=0;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } } for(iter=iterations;--iter;) // other iterations { v4sf *a11p = (v4sf*) a11->c1, *a12p = (v4sf*) a12->c1, *a22p = (v4sf*) a22->c1, *b1p = (v4sf*) b1->c1, *b2p = (v4sf*) b2->c1, *hp = (v4sf*) dpsis_horiz->c1, *vp = (v4sf*) dpsis_vert->c1; float *du_ptr = du->c1, *dv_ptr = dv->c1; v4sf *dub = (v4sf*) (du_ptr+stride), *dvb = (v4sf*) (dv_ptr+stride); { // other iteration - first line memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vp)*(*dvb) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline;--i;){ // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vp)*(*dvb) + (*b2p); for(k=0;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } v4sf *vpt = (v4sf*) dpsis_vert->c1; v4sf *dut = (v4sf*) du->c1, *dvt = (v4sf*) dv->c1; for(j=iterheight;--j;) { // other iteration - middle lines memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*vp)*(*dvb) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++) { const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline; --i;) { // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*vp)*(*dub) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*vp)*(*dvb) + (*b2p); for(k=0;k<4;k++) { const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; vp+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; dub+=1; dvb +=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } { // other iteration - last line memcpy(f1+1, ((float*) hp), width_minus_1_sizeoffloat); memcpy(f2, du_ptr+1, width_minus_1_sizeoffloat); memcpy(f3, dv_ptr+1, width_minus_1_sizeoffloat); v4sf* hpl = (v4sf*) f1, *dur = (v4sf*) f2, *dvr = (v4sf*) f3; { // left block // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*b2p); du_ptr[0] += omega*( a11p[0][0]*s1[0] + a12p[0][0]*s2[0] - du_ptr[0] ); dv_ptr[0] += omega*( a12p[0][0]*s1[0] + a22p[0][0]*s2[0] - dv_ptr[0] ); for(k=1;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } for(i=iterline;--i;){ // do one iteration const v4sf s1 = (*hp)*(*dur) + (*vpt)*(*dut) + (*b1p); const v4sf s2 = (*hp)*(*dvr) + (*vpt)*(*dvt) + (*b2p); for(k=0;k<4;k++){ const float B1 = hpl[0][k]*du_ptr[k-1] + s1[k]; const float B2 = hpl[0][k]*dv_ptr[k-1] + s2[k]; du_ptr[k] += omega*( a11p[0][k]*B1 + a12p[0][k]*B2 - du_ptr[k] ); dv_ptr[k] += omega*( a12p[0][k]*B1 + a22p[0][k]*B2 - dv_ptr[k] ); } // increment pointer hpl+=1; hp+=1; vpt+=1; a11p+=1; a12p+=1; a22p+=1; dur+=1; dvr+=1; dut+=1; dvt+=1; b1p+=1; b2p+=1; du_ptr += 4; dv_ptr += 4; } } } free(floatarray); } //THIS IS A SLOW VERSION BUT READABLE //Perform n iterations of the sor_coupled algorithm //du is used as initial guesses //The system form is the same as in opticalflow.c void sor_coupled_slow_but_readable_DE(image_t *du, const image_t *a11, const image_t *b1, const image_t *dpsis_horiz, const image_t *dpsis_vert, const int iterations, const float omega) { int i,j,iter; for(iter = 0 ; iter<iterations ; iter++) { #if USE_OPENMP #pragma omp parallel for #endif //USE_OPENMP for(j=0 ; j<du->height ; j++) { float sigma_u,sum_dpsis,A11,B1; for(i=0 ; i<du->width ; i++){ sigma_u = 0.0f; sum_dpsis = 0.0f; if(j>0) { sigma_u -= dpsis_vert->c1[(j-1)*du->stride+i]*du->c1[(j-1)*du->stride+i]; sum_dpsis += dpsis_vert->c1[(j-1)*du->stride+i]; } if(i>0) { sigma_u -= dpsis_horiz->c1[j*du->stride+i-1]*du->c1[j*du->stride+i-1]; sum_dpsis += dpsis_horiz->c1[j*du->stride+i-1]; } if(j<du->height-1) { sigma_u -= dpsis_vert->c1[j*du->stride+i]*du->c1[(j+1)*du->stride+i]; sum_dpsis += dpsis_vert->c1[j*du->stride+i]; } if(i<du->width-1) { sigma_u -= dpsis_horiz->c1[j*du->stride+i]*du->c1[j*du->stride+i+1]; sum_dpsis += dpsis_horiz->c1[j*du->stride+i]; } A11 = a11->c1[j*du->stride+i]+sum_dpsis; B1 = b1->c1[j*du->stride+i]-sigma_u; du->c1[j*du->stride+i] = (1.0f-omega)*du->c1[j*du->stride+i] +omega*( B1/A11 ); } } } }
helloworld.c
/* PMSIS includes */ #include "pmsis.h" #include "omp.h" /* Cluster main entry, executed by core 0. */ void cluster_delegate(void *arg) { printf("Cluster delegate\n"); #pragma omp parallel num_threads(4) { printf("[%d %d] Hello world!\n", pi_cluster_id(), omp_get_thread_num() ); } printf("Cluster master core exit\n"); } void helloworld(void) { printf("Entering main controller\n"); uint32_t errors = 0; uint32_t core_id = pi_core_id(), cluster_id = pi_cluster_id(); printf("[%d %d] Hello World!\n", cluster_id, core_id); struct pi_device cluster_dev; struct pi_cluster_conf cl_conf; /* Init cluster configuration structure. */ pi_cluster_conf_init(&cl_conf); cl_conf.id = 0; /* Set cluster ID. */ /* Configure & open cluster. */ pi_open_from_conf(&cluster_dev, &cl_conf); if (pi_cluster_open(&cluster_dev)) { printf("Cluster open failed !\n"); pmsis_exit(-1); } /* Prepare cluster task and send it to cluster. */ struct pi_cluster_task cl_task; pi_cluster_task(&cl_task, cluster_delegate, NULL); pi_cluster_send_task_to_cl(&cluster_dev, &cl_task); pi_cluster_close(&cluster_dev); printf("Test success !\n"); pmsis_exit(errors); } /* Program Entry. */ int main(void) { printf("\n\n\t *** PMSIS HelloWorld ***\n\n"); return pmsis_kickoff((void *) helloworld); }
GB_unop__ainv_uint32_uint32.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__ainv_uint32_uint32 // op(A') function: GB_unop_tran__ainv_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: uint32_t cij = aij // unaryop: cij = -aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CAST(z, aij) \ uint32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = aij ; \ Cx [pC] = -z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__ainv_uint32_uint32 ( uint32_t *Cx, // Cx and Ax may be aliased const uint32_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 (uint32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; uint32_t z = aij ; Cx [p] = -z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint32_t aij = Ax [p] ; uint32_t z = aij ; Cx [p] = -z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__ainv_uint32_uint32 ( 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
BitmapPrimitiveShape.h
#ifndef BITMAPPRIMITIVESHAPE_HEADER #define BITMAPPRIMITIVESHAPE_HEADER #include "BasePrimitiveShape.h" #include <GfxTL/AABox.h> #include <MiscLib/Vector.h> #include <algorithm> #include <istream> #include <MiscLib/Performance.h> #include <GfxTL/MathHelper.h> #include <GfxTL/IndexedIterator.h> #include "IndexIterator.h" #include <MiscLib/Pair.h> #ifdef DOPARALLEL #include <omp.h> #endif #ifndef DLL_LINKAGE #define DLL_LINKAGE #endif struct BitmapInfo { MiscLib::Vector< std::pair< float, float > > params; MiscLib::Vector< char > bitmap; GfxTL::AABox< GfxTL::Vector2Df > bbox; MiscLib::Vector< size_t > bmpIdx; size_t uextent, vextent; }; class DLL_LINKAGE BitmapPrimitiveShape : public BasePrimitiveShape { public: bool Init(bool binary, std::istream *i); size_t ConnectedComponent(const PointCloud &pc, float epsilon, MiscLib::Vector< size_t > *indices, bool doFiltering = true, float* borderRatio = 0 ); size_t AllConnectedComponents(const PointCloud &pc, float epsilon, BitmapInfo& bitmapInfo, MiscLib::Vector< size_t > *indices, MiscLib::Vector< int >& componentsImg, MiscLib::Vector< std::pair< int, size_t > >& labels, bool doFiltering = true ); void TrimmingPolygons(const PointCloud &pc, float epsilon, size_t begin, size_t end, std::deque< ComponentPolygons > *polys) const; void GenerateBitmapPoints(const PointCloud &pc, float epsilon, size_t begin, size_t end, PointCloud *bmpPc) const; public: virtual void Parameters(const Vec3f &p, std::pair< float, float > *param) const = 0; virtual bool InSpace(float u, float v, Vec3f *p, Vec3f *n) const = 0; virtual void Parameters(GfxTL::IndexedIterator< MiscLib::Vector< size_t >::iterator, PointCloud::const_iterator > begin, GfxTL::IndexedIterator< MiscLib::Vector< size_t >::iterator, PointCloud::const_iterator > end, MiscLib::Vector< std::pair< float, float > > *bmpParams) const = 0; virtual void Parameters(GfxTL::IndexedIterator< IndexIterator, PointCloud::const_iterator > begin, GfxTL::IndexedIterator< IndexIterator, PointCloud::const_iterator > end, MiscLib::Vector< std::pair< float, float > > *bmpParams) const = 0; virtual void BitmapExtent(float epsilon, GfxTL::AABox< GfxTL::Vector2Df > *bbox, MiscLib::Vector< std::pair< float, float > > *params, size_t *uextent, size_t *vextent) = 0; virtual void InBitmap(const std::pair< float, float > &param, float epsilon, const GfxTL::AABox< GfxTL::Vector2Df > &bbox, size_t uextent, size_t vextent, std::pair< int, int > *inBmp) const = 0; virtual void PreWrapBitmap(const GfxTL::AABox< GfxTL::Vector2Df > &bbox, float epsilon, size_t uextent, size_t vextent, MiscLib::Vector< char > *bmp) const; virtual void WrapBitmap(const GfxTL::AABox< GfxTL::Vector2Df > &bbox, float epsilon, bool *uwrap, bool *vwrap) const = 0; virtual void WrapComponents(const GfxTL::AABox< GfxTL::Vector2Df > &bbox, float epsilon, size_t uextent, size_t vextent, MiscLib::Vector< int > *componentImg, MiscLib::Vector< std::pair< int, size_t > > *labels) const; virtual bool InSpace(size_t u, size_t v, float epsilon, const GfxTL::AABox< GfxTL::Vector2Df > &bbox, size_t uextent, size_t vextent, Vec3f *p, Vec3f *n) const = 0; template< class IteratorT > void BuildBitmap(const PointCloud &pc, float *epsilon, IteratorT begin, IteratorT end, MiscLib::Vector< std::pair< float, float > > *params, GfxTL::AABox< GfxTL::Vector2Df > *bbox, MiscLib::Vector< char > *bitmap, size_t *uextent, size_t *vextent, MiscLib::Vector< size_t > *bmpIdx) const; template< class IteratorT > void BuildBitmap(const PointCloud &pc, float *epsilon, IteratorT begin, IteratorT end, MiscLib::Vector< std::pair< float, float > > *params, GfxTL::AABox< GfxTL::Vector2Df > *bbox, MiscLib::Vector< char > *bitmap, size_t *uextent, size_t *vextent, MiscLib::Vector< size_t > *bmpIdx, size_t border) const; void BuildPolygons(const PointCloud &pc, float epsilon, size_t begin, size_t end, GfxTL::AABox< GfxTL::Vector2Df > *bbox, size_t *uextent, size_t *vextent, std::deque< ComponentPolygons > *polys) const; protected: mutable GfxTL::AABox< GfxTL::Vector2Df > m_extBbox; }; template< class IteratorT > void BitmapPrimitiveShape::BuildBitmap(const PointCloud &pc, float *epsilon, IteratorT begin, IteratorT end, MiscLib::Vector< std::pair< float, float > > *params, GfxTL::AABox< GfxTL::Vector2Df > *bbox, MiscLib::Vector< char > *bitmap, size_t *uextent, size_t *vextent, MiscLib::Vector< size_t > *bmpIdx) const { int size = end - begin; params->resize(size); // compute parameters and extent Parameters(GfxTL::IndexIterate(begin, pc.begin()), GfxTL::IndexIterate(end, pc.begin()), params); bbox->Min() = GfxTL::Vector2Df(std::numeric_limits< float >::infinity(), std::numeric_limits< float >::infinity()); bbox->Max() = -bbox->Min(); for(size_t i = 0; i < (size_t)size; ++i) { if((*params)[i].first < bbox->Min()[0]) bbox->Min()[0] = (*params)[i].first; if((*params)[i].first > bbox->Max()[0]) bbox->Max()[0] = (*params)[i].first; if((*params)[i].second < bbox->Min()[1]) bbox->Min()[1] = (*params)[i].second; if((*params)[i].second > bbox->Max()[1]) bbox->Max()[1] = (*params)[i].second; } // bbox gives the bounding box in parameter space // we can now set up the bitmap const_cast< BitmapPrimitiveShape * >(this)->BitmapExtent(*epsilon, bbox, params, uextent, vextent); if(*uextent < 2) *uextent = 2; if(*vextent < 2) *vextent = 2; bitmap->resize((*uextent) * (*vextent)); std::fill(bitmap->begin(), bitmap->end(), false); // set all true bits in bitmap bmpIdx->resize(params->size()); #ifdef DOPARALLEL #pragma omp parallel for schedule(static) #endif for(int i = 0; i < size; ++i) { std::pair< int, int > bmpParam; InBitmap((*params)[i], *epsilon, *bbox, *uextent, *vextent, &bmpParam); // clamp bitmap coords bmpParam.first = GfxTL::Math< int >::Clamp(bmpParam.first, 0, *uextent - 1); bmpParam.second = GfxTL::Math< int >::Clamp(bmpParam.second, 0, *vextent - 1); (*bitmap)[(*bmpIdx)[i] = bmpParam.first + bmpParam.second * (*uextent)] = true; } } template< class IteratorT > void BitmapPrimitiveShape::BuildBitmap(const PointCloud &pc, float *epsilon, IteratorT begin, IteratorT end, MiscLib::Vector< std::pair< float, float > > *params, GfxTL::AABox< GfxTL::Vector2Df > *bbox, MiscLib::Vector< char > *bitmap, size_t *uextent, size_t *vextent, MiscLib::Vector< size_t > *bmpIdx, size_t border) const { params->resize(end - begin); // compute parameters and extent Parameters(pc[*begin].pos, &(*params)[0]); bbox->Min() = bbox->Max() = GfxTL::Vector2Df((*params)[0].first, (*params)[0].second); size_t j = 1; IteratorT i = begin; for(++i; i != end; ++i, ++j) { Parameters(pc[*i].pos, &(*params)[j]); if(bbox->Min()[0] > (*params)[j].first) bbox->Min()[0] = (*params)[j].first; else if(bbox->Max()[0] < (*params)[j].first) bbox->Max()[0] = (*params)[j].first; if(bbox->Min()[1] > (*params)[j].second) bbox->Min()[1] = (*params)[j].second; else if(bbox->Max()[1] < (*params)[j].second) bbox->Max()[1] = (*params)[j].second; } // bbox gives the bounding box in parameter space // we can now set up the bitmap const_cast< BitmapPrimitiveShape * >(this)->BitmapExtent(*epsilon, bbox, params, uextent, vextent); if(*uextent < 2) *uextent = 2; if(*vextent < 2) *vextent = 2; bitmap->resize(((*uextent) + 2 * border) * ((*vextent) + 2 * border)); std::fill(bitmap->begin(), bitmap->end(), false); // set all true bits in bitmap bmpIdx->resize(params->size()); size_t lineWidth = (*uextent) + 2 * border; for(size_t i = 0; i < params->size(); ++i) { std::pair< int, int > bmpParam; InBitmap((*params)[i], *epsilon, *bbox, *uextent, *vextent, &bmpParam); // clamp bitmap coords bmpParam.first = GfxTL::Math< int >::Clamp(bmpParam.first, 0, *uextent - 1); bmpParam.second = GfxTL::Math< int >::Clamp(bmpParam.second, 0, *vextent - 1); (*bitmap)[(*bmpIdx)[i] = bmpParam.first + border + (bmpParam.second + border) * lineWidth] = true; } } #endif
USCMatrix.h
#ifndef USCMATRIX_H #define USCMATRIX_H #include <Eigen/Dense> #include "maybe_omp.h" #include "util.h" namespace nplm { // is this cheating? using Eigen::Matrix; using Eigen::MatrixBase; using Eigen::Dynamic; // USC = Uniform Sparse Columns. A USCMatrix is a sparse matrix in which // each column has exactly k nonzero entries. This allows for a // simpler and faster compressed representation. // A USCMatrix can be converted into CSC format fairly easily, by // adding a third array [0, k, 2k, ..., nk]. However, the indices will // not be unique. // We use: // dense2 = dense1^T * sparse (output bProp, input fProp) // dense1 = sparse * dense2^T (output computeGradient, input computeGradient) // where: // sparse is vocab_size x minibatch_size // dense1 is vocab_size x embedding_dimension // dense2 is embedding_dimension x minibatch_size template <typename Scalar, typename Index=int> // should be EIGEN_DEFAULT_DENSE_INDEX_TYPE but int is smaller class USCMatrix { public: Matrix<Index,Dynamic,Dynamic> indexes; Matrix<Scalar,Dynamic,Dynamic> values; int m_rows; USCMatrix() : m_rows(0) { } template <typename Indexes, typename Values> USCMatrix(Index rows, const MatrixBase<Indexes> &indexes, const MatrixBase<Values> &values) : indexes(indexes), values(values), m_rows(rows) { } USCMatrix(Index rows, Index nnz, Index cols) : indexes(Matrix<Index,Dynamic,Dynamic>(nnz, cols)), values(Matrix<Scalar,Dynamic,Dynamic>(nnz, cols)), m_rows(rows) { this->indexes.fill(-1); } Index rows() const { return m_rows; } Index cols() const { return indexes.cols(); } void resize(Index rows, Index nnz, Index cols) { indexes.resize(nnz, cols); values.resize(nnz, cols); m_rows = rows; } }; // Dense matrix - sparse matrix product // a is presumably very wide template <typename DerivedA, typename ScalarB, typename Index, typename DerivedC> void uscgemm(user_data_t alpha, const MatrixBase<DerivedA> &a, const USCMatrix<ScalarB,Index> &b, const MatrixBase<DerivedC> &c_const) { UNCONST(DerivedC, c_const, c); eigen_assert(a.rows() == c.rows()); eigen_assert(a.cols() == b.rows()); eigen_assert(b.cols() == c.cols()); #pragma omp parallel for for (Index k=0; k<b.cols(); k++) for (Index r=0; r<b.indexes.rows(); r++) { Index j = b.indexes(r,k); eigen_assert(j >= 0); eigen_assert(j < a.cols()); c.col(k) += alpha * a.col(j) * b.values(r,k); } } // sparse matrix - dense matrix product template <typename ScalarA, typename Index, typename DerivedB, typename DerivedC> void uscgemm(user_data_t alpha, const USCMatrix<ScalarA,Index> &a, const MatrixBase<DerivedB> &b, const MatrixBase<DerivedC> &c_const) { UNCONST(DerivedC, c_const, c); eigen_assert(a.rows() == c.rows()); eigen_assert(a.cols() == b.rows()); eigen_assert(b.cols() == c.cols()); // This needs to be tuned for each system, unfortunately, // and seems to vary a lot. A lot. int i_blocks = omp_get_num_threads()*16; // Assume only one block in k direction. // We don't need to explicitly block in the j direction. #pragma omp parallel for for (Index ib=0; ib<i_blocks; ib++) for (Index j=0; j<a.cols(); j++) for (Index r=0; r<a.indexes.rows(); r++) { Index i = a.indexes(r,j); eigen_assert(i >= 0); eigen_assert(i < c.rows()); if (i % i_blocks == ib) c.row(i) += alpha * a.values(r,j) * b.row(j); } /* If c.cols() is really large, then theoretically it seems like we should do: parallel for blocks in i direction for blocks in j direction pack block of a into smaller sparse matrix for blocks in k direction for k for i (sparse) for j c(i,k) += a(i,j) * b(j,k) However, the copying of blocks of a doesn't seem practical for any realistic sizes of c.cols(). */ } // Dense matrix - dense matrix product, but masked by a sparse matrix, // that is, compute a*b only for those positions in c.indexes, and put // them in c.values. // a is presumably a very tall matrix. Row-major order is preferred. // For b, column-major is preferred. template <typename DerivedA, typename DerivedB, typename ScalarC, typename Index> void uscgemm_masked(user_data_t alpha, const MatrixBase<DerivedA> &a, const MatrixBase<DerivedB> &b, USCMatrix<ScalarC,Index> &c) { eigen_assert(a.rows() == c.rows()); eigen_assert(a.cols() == b.rows()); eigen_assert(b.cols() == c.cols()); #pragma omp parallel for for (Index k=0; k<b.cols(); k++) for (Index r=0; r<c.indexes.rows(); r++) { Index i = c.indexes(r, k); eigen_assert(i >= 0); eigen_assert(i < a.rows()); c.values(r, k) += alpha * a.row(i) * b.col(k); } } // sparse matrix - dense vector product template <typename ScalarA, typename Index, typename DerivedB, typename DerivedC> void uscgemv(user_data_t alpha, const USCMatrix<ScalarA,Index> &a, const MatrixBase<DerivedB> &b, const MatrixBase<DerivedC> &c_const) { UNCONST(DerivedC, c_const, c); eigen_assert(a.rows() == c.rows()); eigen_assert(a.cols() == b.rows()); eigen_assert(b.cols() == 1 && c.cols() == 1); for (Index j=0; j<a.cols(); j++) for (Index r=0; r<a.indexes.rows(); r++) { Index i = a.indexes(r,j); eigen_assert(i >= 0); eigen_assert(i < c.rows()); c(i) += alpha * a.values(r,j) * b(j); } } } #endif
stream-optimized.c
/*-----------------------------------------------------------------------*/ /* Program: STREAM */ /* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */ /* Original code developed by John D. McCalpin */ /* Programmers: John D. McCalpin */ /* Joe R. Zagar */ /* */ /* This program measures memory transfer rates in MB/s for simple */ /* computational kernels coded in C. */ /*-----------------------------------------------------------------------*/ /* Copyright 1991-2013: John D. McCalpin */ /*-----------------------------------------------------------------------*/ /* License: */ /* 1. You are free to use this program and/or to redistribute */ /* this program. */ /* 2. You are free to modify this program for your own use, */ /* including commercial use, subject to the publication */ /* restrictions in item 3. */ /* 3. You are free to publish results obtained from running this */ /* program, or from works that you derive from this program, */ /* with the following limitations: */ /* 3a. In order to be referred to as "STREAM benchmark results", */ /* published results must be in conformance to the STREAM */ /* Run Rules, (briefly reviewed below) published at */ /* http://www.cs.virginia.edu/stream/ref.html */ /* and incorporated herein by reference. */ /* As the copyright holder, John McCalpin retains the */ /* right to determine conformity with the Run Rules. */ /* 3b. Results based on modified source code or on runs not in */ /* accordance with the STREAM Run Rules must be clearly */ /* labelled whenever they are published. Examples of */ /* proper labelling include: */ /* "tuned STREAM benchmark results" */ /* "based on a variant of the STREAM benchmark code" */ /* Other comparable, clear, and reasonable labelling is */ /* acceptable. */ /* 3c. Submission of results to the STREAM benchmark web site */ /* is encouraged, but not required. */ /* 4. Use of this program or creation of derived works based on this */ /* program constitutes acceptance of these licensing restrictions. */ /* 5. Absolutely no warranty is expressed or implied. */ /*-----------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <math.h> #include <float.h> #include <limits.h> #ifndef WIN32 #include <unistd.h> #include <sys/time.h> #else #include <Windows.h> #endif /*----------------------------------------------------------------------- * INSTRUCTIONS: * * 1) STREAM requires different amounts of memory to run on different * systems, depending on both the system cache size(s) and the * granularity of the system timer. * You should adjust the value of 'STREAM_ARRAY_SIZE' (below) * to meet *both* of the following criteria: * (a) Each array must be at least 4 times the size of the * available cache memory. I don't worry about the difference * between 10^6 and 2^20, so in practice the minimum array size * is about 3.8 times the cache size. * Example 1: One Xeon E3 with 8 MB L3 cache * STREAM_ARRAY_SIZE should be >= 4 million, giving * an array size of 30.5 MB and a total memory requirement * of 91.5 MB. * Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP) * STREAM_ARRAY_SIZE should be >= 20 million, giving * an array size of 153 MB and a total memory requirement * of 458 MB. * (b) The size should be large enough so that the 'timing calibration' * output by the program is at least 20 clock-ticks. * Example: most versions of Windows have a 10 millisecond timer * granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds. * If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec. * This means the each array must be at least 1 GB, or 128M elements. * * Version 5.10 increases the default array size from 2 million * elements to 10 million elements in response to the increasing * size of L3 caches. The new default size is large enough for caches * up to 20 MB. * Version 5.10 changes the loop index variables from "register int" * to "ssize_t", which allows array indices >2^32 (4 billion) * on properly configured 64-bit systems. Additional compiler options * (such as "-mcmodel=medium") may be required for large memory runs. * * Array size can be set at compile time without modifying the source * code for the (many) compilers that support preprocessor definitions * on the compile line. E.g., * gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M * will override the default size of 10M with a new size of 100M elements * per array. */ #ifndef STREAM_ARRAY_SIZE # define STREAM_ARRAY_SIZE 10000000 #endif /* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result * for any iteration after the first, therefore the minimum value * for NTIMES is 2. * There are no rules on maximum allowable values for NTIMES, but * values larger than the default are unlikely to noticeably * increase the reported performance. * NTIMES can also be set on the compile line without changing the source * code using, for example, "-DNTIMES=7". */ #ifdef NTIMES #if NTIMES<=1 # define NTIMES 10 #endif #endif #ifndef NTIMES # define NTIMES 10 #endif /* Users are allowed to modify the "OFFSET" variable, which *may* change the * relative alignment of the arrays (though compilers may change the * effective offset by making the arrays non-contiguous on some systems). * Use of non-zero values for OFFSET can be especially helpful if the * STREAM_ARRAY_SIZE is set to a value close to a large power of 2. * OFFSET can also be set on the compile line without changing the source * code using, for example, "-DOFFSET=56". */ #ifndef OFFSET # define OFFSET 0 #endif /* * 3) Compile the code with optimization. Many compilers generate * unreasonably bad code before the optimizer tightens things up. * If the results are unreasonably good, on the other hand, the * optimizer might be too smart for me! * * For a simple single-core version, try compiling with: * cc -O stream.c -o stream * This is known to work on many, many systems.... * * To use multiple cores, you need to tell the compiler to obey the OpenMP * directives in the code. This varies by compiler, but a common example is * gcc -O -fopenmp stream.c -o stream_omp * The environment variable OMP_NUM_THREADS allows runtime control of the * number of threads/cores used when the resulting "stream_omp" program * is executed. * * To run with single-precision variables and arithmetic, simply add * -DSTREAM_TYPE=float * to the compile line. * Note that this changes the minimum array sizes required --- see (1) above. * * The preprocessor directive "TUNED" does not do much -- it simply causes the * code to call separate functions to execute each kernel. Trivial versions * of these functions are provided, but they are *not* tuned -- they just * provide predefined interfaces to be replaced with tuned code. * * * 4) Optional: Mail the results to mccalpin@cs.virginia.edu * Be sure to include info that will help me understand: * a) the computer hardware configuration (e.g., processor model, memory type) * b) the compiler name/version and compilation flags * c) any run-time information (such as OMP_NUM_THREADS) * d) all of the output from the test case. * * Thanks! * *-----------------------------------------------------------------------*/ # define HLINE "-------------------------------------------------------------\n" # ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) # endif # ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) # endif #ifndef STREAM_TYPE #define STREAM_TYPE double #endif // it turns out that massive static arrays make Emscripten blow up, as it // encodes their initializers naively. A ten million entry array gets a // ten million entry initializer. //static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET], // b[STREAM_ARRAY_SIZE+OFFSET], // c[STREAM_ARRAY_SIZE+OFFSET]; static STREAM_TYPE* a, *b, *c; static double avgtime[4] = {0}, maxtime[4] = {0}, mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; static char *label[4] = {"Copy: ", "Scale: ", "Add: ", "Triad: "}; static double bytes[4] = { 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE }; extern double mysecond(); extern void checkSTREAMresults(); #ifdef TUNED extern void tuned_STREAM_Copy(); extern void tuned_STREAM_Scale(STREAM_TYPE scalar); extern void tuned_STREAM_Add(); extern void tuned_STREAM_Triad(STREAM_TYPE scalar); #endif #ifdef _OPENMP extern int omp_get_num_threads(); #endif int main() { int quantum, checktick(); int BytesPerWord; int k; intptr_t j; STREAM_TYPE scalar; double t, times[4][NTIMES]; a = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); b = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); c = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); if(!a || !b || !c) { printf("Memory allocation failed.\n"); return -1; } /* --- SETUP --- determine precision and check timing --- */ printf(HLINE); printf("STREAM version $Revision: 5.10 $\n"); printf(HLINE); BytesPerWord = sizeof(STREAM_TYPE); printf("This system uses %d bytes per array element.\n", BytesPerWord); printf(HLINE); #ifdef N printf("***** WARNING: ******\n"); printf(" It appears that you set the preprocessor variable N when compiling this code.\n"); printf(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n"); printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",(unsigned long long) STREAM_ARRAY_SIZE); printf("***** WARNING: ******\n"); #endif printf("Array size = %llu (elements), Offset = %d (elements)\n" , (unsigned long long) STREAM_ARRAY_SIZE, OFFSET); printf("Memory per array = %.1f MiB (= %.1f GiB).\n", BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0), BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0/1024.0)); printf("Total memory required = %.1f MiB (= %.1f GiB).\n", (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.), (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024./1024.)); printf("Each kernel will be executed %d times.\n", NTIMES); printf(" The *best* time for each kernel (excluding the first iteration)\n"); printf(" will be used to compute the reported bandwidth.\n"); #ifdef _OPENMP printf(HLINE); #pragma omp parallel { #pragma omp master { k = omp_get_num_threads(); printf ("Number of Threads requested = %i\n",k); } } #endif #ifdef _OPENMP k = 0; #pragma omp parallel #pragma omp atomic k++; printf ("Number of Threads counted = %i\n",k); #endif /* Get initial value for system clock. */ #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) { a[j] = 1.0; b[j] = 2.0; c[j] = 0.0; } printf(HLINE); if ( (quantum = checktick()) >= 1) printf("Your clock granularity/precision appears to be " "%d microseconds.\n", quantum); else { printf("Your clock granularity appears to be " "less than one microsecond.\n"); quantum = 1; } t = mysecond(); #pragma omp parallel for for (j = 0; j < STREAM_ARRAY_SIZE; j++) a[j] = 2.0E0 * a[j]; t = 1.0E6 * (mysecond() - t); printf("Each test below will take on the order" " of %d microseconds.\n", (int) t ); printf(" (= %d clock ticks)\n", (int) (t/quantum) ); printf("Increase the size of the arrays if this shows that\n"); printf("you are not getting at least 20 clock ticks per test.\n"); printf(HLINE); printf("WARNING -- The above is only a rough guideline.\n"); printf("For best results, please be sure you know the\n"); printf("precision of your system timer.\n"); printf(HLINE); /* --- MAIN LOOP --- repeat test cases NTIMES times --- */ scalar = 3.0; for (k=0; k<NTIMES; k++) { times[0][k] = mysecond(); #ifdef TUNED tuned_STREAM_Copy(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; #endif times[0][k] = mysecond() - times[0][k]; times[1][k] = mysecond(); #ifdef TUNED tuned_STREAM_Scale(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; #endif times[1][k] = mysecond() - times[1][k]; times[2][k] = mysecond(); #ifdef TUNED tuned_STREAM_Add(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; #endif times[2][k] = mysecond() - times[2][k]; times[3][k] = mysecond(); #ifdef TUNED tuned_STREAM_Triad(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; #endif times[3][k] = mysecond() - times[3][k]; } /* --- SUMMARY --- */ for (k=1; k<NTIMES; k++) /* note -- skip first iteration */ { for (j=0; j<4; j++) { avgtime[j] = avgtime[j] + times[j][k]; mintime[j] = MIN(mintime[j], times[j][k]); maxtime[j] = MAX(maxtime[j], times[j][k]); } } printf("Function Best Rate MB/s Avg time Min time Max time\n"); for (j=0; j<4; j++) { avgtime[j] = avgtime[j]/(double)(NTIMES-1); printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j], 1.0E-06 * bytes[j]/mintime[j], avgtime[j], mintime[j], maxtime[j]); } printf(HLINE); /* --- Check Results --- */ checkSTREAMresults(); printf(HLINE); free(a); free(b); free(c); return 0; } # define M 20 int checktick() { int i, minDelta, Delta; double t1, t2, timesfound[M]; /* Collect a sequence of M unique time values from the system. */ for (i = 0; i < M; i++) { t1 = mysecond(); while( ((t2=mysecond()) - t1) < 1.0E-6 ) ; timesfound[i] = t1 = t2; } /* * Determine the minimum difference between these M values. * This result will be our estimate (in microseconds) for the * clock granularity. */ minDelta = 1000000; for (i = 1; i < M; i++) { Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1])); minDelta = MIN(minDelta, MAX(Delta,0)); } return(minDelta); } /* A gettimeofday routine to give access to the wall clock timer on most UNIX-like systems. */ #ifndef WIN32 #include <sys/time.h> double mysecond() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } #else #include <Windows.h> double mysecond() { static LARGE_INTEGER freq = {0}; LARGE_INTEGER count = {0}; if(freq.QuadPart == 0LL) { QueryPerformanceFrequency(&freq); } QueryPerformanceCounter(&count); return (double)count.QuadPart / (double)freq.QuadPart; } #endif #ifndef abs #define abs(a) ((a) >= 0 ? (a) : -(a)) #endif void checkSTREAMresults () { STREAM_TYPE aj,bj,cj,scalar; STREAM_TYPE aSumErr,bSumErr,cSumErr; STREAM_TYPE aAvgErr,bAvgErr,cAvgErr; double epsilon; size_t j; int k,ierr,err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (k=0; k<NTIMES; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; if (sizeof(STREAM_TYPE) == 4) { epsilon = 1.e-6; } else if (sizeof(STREAM_TYPE) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr/aj) > epsilon) { err++; printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(a[j]/aj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,aj,a[j],abs((aj-a[j])/aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n",ierr); } if (abs(bAvgErr/bj) > epsilon) { err++; printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(b[j]/bj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,bj,b[j],abs((bj-b[j])/bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n",ierr); } if (abs(cAvgErr/cj) > epsilon) { err++; printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(c[j]/cj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,cj,c[j],abs((cj-c[j])/cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n",ierr); } if (err == 0) { printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon); } #ifdef VERBOSE printf ("Results Validation Verbose Results: \n"); printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj); printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]); printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj)); #endif } #ifdef TUNED /* stubs for "tuned" versions of the kernels */ void tuned_STREAM_Copy() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; } void tuned_STREAM_Scale(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; } void tuned_STREAM_Add() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; } void tuned_STREAM_Triad(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; } /* end of stubs for the "tuned" versions of the kernels */ #endif
test_omp.c
#include <omp.h> #include <stdio.h> int main() { int num_threads = omp_get_max_threads(); printf("Maximum number of OpenMP threads: %d\n", num_threads); #pragma omp parallel printf("thread %d / %d\n", omp_get_thread_num(), num_threads); }
ode_solver.c
// // Created by sachetto on 02/10/17. // #include "ode_solver.h" #include <string.h> #include <dlfcn.h> #include <assert.h> #include "../utils/file_utils.h" #include "../config/stim_config.h" #ifdef COMPILE_CUDA #include "../gpu_utils/gpu_utils.h" #endif #include "../single_file_libraries/stb_ds.h" #include "../config_helpers/config_helpers.h" #include "../string/sds.h" struct ode_solver* new_ode_solver() { struct ode_solver* result = (struct ode_solver *) malloc(sizeof(struct ode_solver)); result->sv = NULL; result->cells_to_solve = NULL; result->handle = NULL; result->get_cell_model_data = NULL; result->set_ode_initial_conditions_cpu = NULL; result->solve_model_ode_cpu = NULL; result->set_ode_initial_conditions_gpu = NULL; result->solve_model_ode_gpu = NULL; result->model_data.initial_v = INFINITY; result->model_data.number_of_ode_equations = -1; result->model_data.model_library_path = NULL; result->ode_extra_data = NULL; result->ode_extra_data = 0; return result; } void free_ode_solver(struct ode_solver *solver) { if(solver->sv) { if(solver->gpu) { #ifdef COMPILE_CUDA cudaFree(solver->sv); #endif } else { free(solver->sv); } } if(solver->ode_extra_data) { free(solver->ode_extra_data); } if(solver->cells_to_solve) { free(solver->cells_to_solve); } if(solver->model_data.model_library_path) { free(solver->model_data.model_library_path); } if(solver->handle) { dlclose(solver->handle); } free(solver); } void init_ode_solver_with_cell_model(struct ode_solver* solver) { char *error; if(!solver->model_data.model_library_path) { fprintf(stderr, "model_library_path not provided. Exiting!\n"); exit(1); } solver->handle = dlopen (solver->model_data.model_library_path, RTLD_LAZY); if (!solver->handle) { fprintf(stderr, "%s\n", dlerror()); exit(1); } solver->get_cell_model_data = dlsym(solver->handle, "init_cell_model_data"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "init_cell_model_data function not found in the provided model library\n"); if(!isfinite(solver->model_data.initial_v)) { fprintf(stderr, "intial_v not provided in the [cell_model] of the config file! Exiting\n"); exit(1); } } solver->set_ode_initial_conditions_cpu = dlsym(solver->handle, "set_model_initial_conditions_cpu"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "set_model_initial_conditions function not found in the provided model library\n"); exit(1); } solver->solve_model_ode_cpu = dlsym(solver->handle, "solve_model_odes_cpu"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "solve_model_odes_cpu function not found in the provided model library\n"); exit(1); } #ifdef COMPILE_CUDA solver->set_ode_initial_conditions_gpu = dlsym(solver->handle, "set_model_initial_conditions_gpu"); if ((error = dlerror()) != NULL) { fputs(error, stderr); fprintf(stderr, "set_model_initial_conditions_gpu function not found in the provided model library\n"); exit(1); } solver->solve_model_ode_gpu = dlsym(solver->handle, "solve_model_odes_gpu"); if ((error = dlerror()) != NULL) { fputs(error, stderr); fprintf(stderr, "\nsolve_model_odes_gpu function not found in the provided model library\n"); exit(1); } #endif } void set_ode_initial_conditions_for_all_volumes(struct ode_solver *solver, struct string_hash_entry *ode_extra_config) { bool get_initial_v = !isfinite(solver->model_data.initial_v); bool get_neq = solver->model_data.number_of_ode_equations == -1; uint32_t num_cells = solver->original_num_cells; (*(solver->get_cell_model_data))(&(solver->model_data), get_initial_v, get_neq); int n_odes = solver->model_data.number_of_ode_equations; if (solver->gpu) { #ifdef COMPILE_CUDA set_ode_initial_conditions_gpu_fn *soicg_fn_pt = solver->set_ode_initial_conditions_gpu; if(!soicg_fn_pt) { fprintf(stderr, "The ode solver was set to use the GPU, \n " "but no function called set_model_initial_conditions_gpu " "was provided in the %s shared library file\n", solver->model_data.model_library_path); exit(11); } if(solver->sv != NULL) { check_cuda_errors(cudaFree(solver->sv)); } solver->pitch = soicg_fn_pt(ode_extra_config, &(solver->sv), num_cells, solver->ode_extra_data, solver->extra_data_size); #endif } else { set_ode_initial_conditions_cpu_fn *soicc_fn_pt = solver->set_ode_initial_conditions_cpu; if(!soicc_fn_pt) { fprintf(stderr, "The ode solver was set to use the CPU, \n " "but no function called set_model_initial_conditions_cpu " "was provided in the %s shared library file\n", solver->model_data.model_library_path); exit(11); } if(solver->sv != NULL) { free(solver->sv); } solver->sv = (real*)malloc(n_odes*num_cells*sizeof(real)); int i; #pragma omp parallel for for(i = 0; i < num_cells; i++) { soicc_fn_pt(ode_extra_config, solver->sv + (i*n_odes), i, solver->ode_extra_data, solver->extra_data_size); } } } void solve_all_volumes_odes(struct ode_solver *the_ode_solver, uint32_t n_active, real_cpu cur_time, int num_steps, struct string_voidp_hash_entry *stim_configs, struct string_hash_entry *ode_extra_config) { assert(the_ode_solver->sv); real dt = the_ode_solver->min_dt; //int n_odes = the_ode_solver->model_data.number_of_ode_equations; real *sv = the_ode_solver->sv; void *extra_data = the_ode_solver->ode_extra_data; real_cpu time = cur_time; real *merged_stims = (real*)calloc(sizeof(real), n_active); struct config *tmp = NULL; uint32_t i; ptrdiff_t n = hmlen(stim_configs); if(stim_configs) { real stim_start = 0.0; real stim_dur = 0.0; real stim_period = 0.0; for (long k = 0; k < n; k++) { tmp = (struct config*) stim_configs[k].value; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, stim_start, tmp->config_data, "start"); GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, stim_dur, tmp->config_data, "duration"); GET_PARAMETER_NUMERIC_VALUE_OR_USE_DEFAULT(real, stim_period, tmp->config_data, "period"); for (int j = 0; j < num_steps; ++j) { if ((time >= stim_start) && (time <= stim_start + stim_dur)) { #pragma omp parallel for for (i = 0; i < n_active; i++) { // This variable should be an accumulator to allow multiple stimulus // TODO: Implement a stimuli_config just for the Purkinje merged_stims[i] += ((real*)(tmp->persistent_data))[i]; } } time += dt; } if(stim_period > 0.0) { if (time >= stim_start + stim_period) { stim_start = stim_start + stim_period; sds stim_start_char = sdscatprintf(sdsempty(), "%lf", stim_start); shput_dup_value(tmp->config_data, "start", stim_start_char); sdsfree(stim_start_char); } } time = cur_time; } } if(the_ode_solver->gpu) { #ifdef COMPILE_CUDA size_t extra_data_size = the_ode_solver->extra_data_size; solve_model_ode_gpu_fn *solve_odes_pt = the_ode_solver->solve_model_ode_gpu; solve_odes_pt(ode_extra_config, dt, sv, merged_stims, the_ode_solver->cells_to_solve, n_active, num_steps, extra_data, extra_data_size); #endif } else { solve_model_ode_cpu_fn *solve_odes_pt = the_ode_solver->solve_model_ode_cpu; solve_odes_pt(ode_extra_config, dt, sv, merged_stims, the_ode_solver->cells_to_solve, n_active, num_steps, extra_data); } free(merged_stims); } void update_state_vectors_after_refinement(struct ode_solver *ode_solver, const uint32_t *refined_this_step) { assert(ode_solver); assert(ode_solver->sv); size_t num_refined_cells = (size_t) arrlen(refined_this_step)/8; real *sv = ode_solver->sv; int neq = ode_solver->model_data.number_of_ode_equations; real *sv_src; real *sv_dst; int i; if(ode_solver->gpu) { #ifdef COMPILE_CUDA size_t pitch_h = ode_solver->pitch; #pragma omp parallel for private(sv_src, sv_dst) for (i = 0; i < num_refined_cells; i++) { size_t index_id = i * (size_t )8; uint32_t index = refined_this_step[index_id]; sv_src = &sv[index]; for (int j = 1; j < 8; j++) { index = refined_this_step[index_id + j]; sv_dst = &sv[index]; check_cuda_errors(cudaMemcpy2D(sv_dst, pitch_h, sv_src, pitch_h, sizeof(real), (size_t )neq, cudaMemcpyDeviceToDevice)); } } #endif } else { #pragma omp parallel for private(sv_src, sv_dst) for (i = 0; i < num_refined_cells; i++) { size_t index_id = i * (size_t )8; uint32_t index = refined_this_step[index_id]; sv_src = &sv[index * neq]; for (int j = 1; j < 8; j++) { index = refined_this_step[index_id + j]; sv_dst = &sv[index * neq]; memcpy(sv_dst, sv_src, neq * sizeof(real)); } } } } void configure_ode_solver_from_options(struct ode_solver *solver, struct user_options *options) { solver->gpu_id = options->gpu_id; solver->min_dt = (real)options->dt_ode; solver->gpu = options->gpu; if(options->model_file_path) { free(solver->model_data.model_library_path); solver->model_data.model_library_path = strdup(options->model_file_path); } } void configure_purkinje_ode_solver_from_options (struct ode_solver *purkinje_solver, struct user_options *options) { purkinje_solver->gpu_id = options->purkinje_gpu_id; purkinje_solver->min_dt = (real)options->purkinje_dt_ode; purkinje_solver->gpu = options->purkinje_gpu; if(options->purkinje_model_file_path) { free(purkinje_solver->model_data.model_library_path); purkinje_solver->model_data.model_library_path = strdup(options->purkinje_model_file_path); } } void configure_purkinje_ode_solver_from_ode_solver (struct ode_solver *purkinje_solver, struct ode_solver *solver) { purkinje_solver->gpu_id = solver->gpu_id; purkinje_solver->min_dt = (real)solver->min_dt; purkinje_solver->gpu = solver->gpu; if(solver->model_data.model_library_path) { purkinje_solver->model_data.model_library_path = strdup(solver->model_data.model_library_path); } } void solve_purkinje_volumes_odes (struct ode_solver *the_ode_solver, uint32_t n_active, real_cpu cur_time, int num_steps, struct string_voidp_hash_entry *stim_configs, struct string_hash_entry *ode_extra_config) { assert(the_ode_solver->sv); real dt = the_ode_solver->min_dt; //int n_odes = the_ode_solver->model_data.number_of_ode_equations; real *sv = the_ode_solver->sv; void *extra_data = the_ode_solver->ode_extra_data; real_cpu time = cur_time; real *merged_stims = (real*)calloc(sizeof(real), n_active); struct config *tmp = NULL; uint32_t i; ptrdiff_t n = hmlen(stim_configs); if(stim_configs) { real stim_start = 0.0; real stim_dur = 0.0; real stim_period = 0.0; for (long k = 0; k < n; k++) { tmp = (struct config*) stim_configs[k].value; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, stim_start, tmp->config_data, "start"); GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, stim_dur, tmp->config_data, "duration"); GET_PARAMETER_NUMERIC_VALUE_OR_USE_DEFAULT(real, stim_period, tmp->config_data, "period"); for (int j = 0; j < num_steps; ++j) { if ((time >= stim_start) && (time <= stim_start + stim_dur)) { #pragma omp parallel for for (i = 0; i < n_active; i++) { // This variable should be an accumulator to allow multiple stimulus merged_stims[i] += ((real*)(tmp->persistent_data))[i]; } } time += dt; } if(stim_period > 0.0) { if (time >= stim_start + stim_period) { stim_start = stim_start + stim_period; sds stim_start_char = sdscatprintf(sdsempty(), "%lf", stim_start); shput_dup_value(tmp->config_data, "start", stim_start_char); sdsfree(stim_start_char); } } time = cur_time; } } if(the_ode_solver->gpu) { #ifdef COMPILE_CUDA size_t extra_data_size = the_ode_solver->extra_data_size; solve_model_ode_gpu_fn *solve_odes_pt = the_ode_solver->solve_model_ode_gpu; solve_odes_pt(ode_extra_config, dt, sv, merged_stims, the_ode_solver->cells_to_solve, n_active, num_steps, extra_data, extra_data_size); #endif } else { solve_model_ode_cpu_fn *solve_odes_pt = the_ode_solver->solve_model_ode_cpu; solve_odes_pt(ode_extra_config, dt, sv, merged_stims, the_ode_solver->cells_to_solve, n_active, num_steps, extra_data); } free(merged_stims); } void init_purkinje_ode_solver_with_cell_model (struct ode_solver* solver, const char *model_library_path) { char *error; if(model_library_path) { free(solver->model_data.model_library_path); solver->model_data.model_library_path = strdup(model_library_path); } if(!solver->model_data.model_library_path) { fprintf(stderr, "model_library_path not provided. Exiting!\n"); exit(1); } solver->handle = dlopen (solver->model_data.model_library_path, RTLD_LAZY); if (!solver->handle) { fprintf(stderr, "%s\n", dlerror()); exit(1); } solver->get_cell_model_data = dlsym(solver->handle, "init_cell_model_data"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "init_cell_model_data function not found in the provided model library\n"); if(!isfinite(solver->model_data.initial_v)) { fprintf(stderr, "intial_v not provided in the [cell_model] of the config file! Exiting\n"); exit(1); } } solver->set_ode_initial_conditions_cpu = dlsym(solver->handle, "set_model_initial_conditions_cpu"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "set_model_initial_conditions function not found in the provided model library\n"); exit(1); } solver->solve_model_ode_cpu = dlsym(solver->handle, "solve_model_odes_cpu"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); fprintf(stderr, "solve_model_odes_cpu function not found in the provided model library\n"); exit(1); } #ifdef COMPILE_CUDA solver->set_ode_initial_conditions_gpu = dlsym(solver->handle, "set_model_initial_conditions_gpu"); if ((error = dlerror()) != NULL) { fputs(error, stderr); fprintf(stderr, "set_model_initial_conditions_gpu function not found in the provided model library\n"); exit(1); } solver->solve_model_ode_gpu = dlsym(solver->handle, "solve_model_odes_gpu"); if ((error = dlerror()) != NULL) { fputs(error, stderr); fprintf(stderr, "\nsolve_model_odes_gpu function not found in the provided model library\n"); exit(1); } #endif }
GB_binop__minus_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__minus_uint64) // A.*B function (eWiseMult): GB (_AemultB_01__minus_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__minus_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__minus_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint64) // A*D function (colscale): GB (_AxD__minus_uint64) // D*A function (rowscale): GB (_DxB__minus_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__minus_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__minus_uint64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint64) // C=scalar+B GB (_bind1st__minus_uint64) // C=scalar+B' GB (_bind1st_tran__minus_uint64) // C=A+scalar GB (_bind2nd__minus_uint64) // C=A'+scalar GB (_bind2nd_tran__minus_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij - bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,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_MINUS || GxB_NO_UINT64 || GxB_NO_MINUS_UINT64) //------------------------------------------------------------------------------ // 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__minus_uint64) ( 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__minus_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__minus_uint64) ( 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__minus_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__minus_uint64) ( 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 uint64_t *restrict Cx = (uint64_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__minus_uint64) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) 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__minus_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__minus_uint64) ( 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__minus_uint64) ( 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__minus_uint64) ( 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__minus_uint64) ( 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__minus_uint64) ( 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 uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_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__minus_uint64) ( 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 ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = 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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x - aij) ; \ } GrB_Info GB (_bind1st_tran__minus_uint64) ( 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 \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - y) ; \ } GrB_Info GB (_bind2nd_tran__minus_uint64) ( 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
l8t1qa.c
#include<stdio.h> #include "gdal.h" #include<omp.h> /* L8 Qa bits [4] Cloud * 0 -> class 0: Not Cloud * 1 -> class 1: Cloud */ unsigned int L8QA_cloud(unsigned int pixel) { unsigned int qa; pixel >>= 4; /*bits [4] become [0]*/ qa = (unsigned int) (pixel & 0x01); return qa; } /* L8 Qa bits [5-6] Cloud confidence * 00 -> class 0: Not determined * 01 -> class 1: No Cloud (0-33% probability) * 10 -> class 2: Maybe Cloud (34-66% probability) * 11 -> class 3: Cloud (66-100% probability) */ unsigned int L8QA_cloud_confidence(unsigned int pixel) { unsigned int qa; pixel >>= 5; /*bits [5-6] become [0-1]*/ qa = (unsigned int) (pixel & 0x03); return qa; } /* L8 Qa bits [7-8] Cloud shadow confidence * 00 -> class 0: Not determined * 01 -> class 1: No Cloud shadow (0-33% probability) * 10 -> class 2: Maybe Cloud shadow (34-66% probability) * 11 -> class 3: Cloud shadow (66-100% probability) */ unsigned int L8QA_cloud_shadow(unsigned int pixel) { unsigned int qa; pixel >>= 7; /*bits [7-8] become [0-1]*/ qa = (unsigned int) (pixel & 0x03); return qa; } /* L8 Qa bits [11-12] Cirrus confidence * 00 -> class 0: Not determined * 01 -> class 1: No Cirrus (0-33% probability) * 10 -> class 2: Maybe Cirrus (34-66% probability) * 11 -> class 3: Cirrus (66-100% probability) */ unsigned int L8QA_cirrus_confidence(unsigned int pixel) { unsigned int qa; pixel >>= 11; /*bits [11-12] become [0-1]*/ qa = (unsigned int) (pixel & 0x03); return qa; } void usage() { printf( "-----------------------------------------\n"); printf( "--L8 Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./L8 inL8b4 inL8b5 inL8b6 inL8B7 inL8_QA\n"); printf( "\toutL8vi outL8wi outL8LSWI outL8NBR2\n"); printf( "-----------------------------------------\n"); printf( "inL8b4\t\tL8 Band 4 UInt16 (Red)\n"); printf( "inL8b5\t\tL8 Band 5 UInt16 (NIR)\n"); printf( "inL8b6\t\tL8 Band 6 UInt16 (SWIR1)\n"); printf( "inL8b7\t\tL8 Band 7 UInt16 (SWIR2)\n"); printf( "inL8_QA\t\tL8_Qa UInt16\n"); printf( "outL8vi\tCloud removed L8 NDVI output [0-10000]\n"); printf( "outL8wi\tCloud removed L8 NDWI output [0-10000]\n"); printf( "outL8lswi\tCloud removed L8 LSWI output [0-10000]\n"); printf( "outL8nbr2\tCloud removed L8 NBR2 output [0-10000]\n"); return; } int main( int argc, char *argv[] ) { if( argc < 9 ) { usage(); return 1; } char *inB4 = argv[1]; //L8 band 4 (Red) char *inB5 = argv[2]; //L8 band 5 (NIR) char *inB6 = argv[3]; //L8 band 6 (SWIR1) char *inB7 = argv[4]; //L8 band 7 (SIWR2) char *inB8 = argv[5]; //L8_QA char *L8viF = argv[6]; //OUT NDVI char *L8wiF = argv[7]; //OUT NDWI char *L8lswiF= argv[8]; //OUT LSWI char *L8nbr2F= argv[9]; //OUT NBR2 GDALAllRegister(); GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//L8 band 4 (Red) GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//L8 band 5 (NIR) GDALDatasetH hD6 = GDALOpen(inB6,GA_ReadOnly);//L8 band 6 (SWIR1) GDALDatasetH hD7 = GDALOpen(inB7,GA_ReadOnly);//L8 band 7 (SWIR2) GDALDatasetH hD8 = GDALOpen(inB8,GA_ReadOnly);//L8_QA if(hD4==NULL||hD5==NULL||hD6==NULL||hD7==NULL||hD8==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr4 = GDALGetDatasetDriver(hD4); char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDatasetH hDOutVI = GDALCreateCopy(hDr4,L8viF,hD4,FALSE,options,NULL,NULL); GDALDatasetH hDOutWI = GDALCreateCopy(hDr4,L8wiF,hD4,FALSE,options,NULL,NULL); GDALDatasetH hDOutLSWI = GDALCreateCopy(hDr4,L8lswiF,hD4,FALSE,options,NULL,NULL); GDALDatasetH hDOutNBR2 = GDALCreateCopy(hDr4,L8nbr2F,hD4,FALSE,options,NULL,NULL); GDALRasterBandH hBOutVI = GDALGetRasterBand(hDOutVI,1); GDALRasterBandH hBOutWI = GDALGetRasterBand(hDOutWI,1); GDALRasterBandH hBOutLSWI = GDALGetRasterBand(hDOutLSWI,1); GDALRasterBandH hBOutNBR2 = GDALGetRasterBand(hDOutNBR2,1); GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//L8 band 4 (Red) GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//L8 band 5 (NIR) GDALRasterBandH hB6 = GDALGetRasterBand(hD6,1);//L8 band 6 (SWIR1) GDALRasterBandH hB7 = GDALGetRasterBand(hD7,1);//L8 band 7 (SWIR2) GDALRasterBandH hB8 = GDALGetRasterBand(hD8,1);//L8_QA int nX = GDALGetRasterBandXSize(hB4); int nY = GDALGetRasterBandYSize(hB4); int N=nX*nY; unsigned int *l4 = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *l5 = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *l6 = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *l7 = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *l8 = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *lOutVI = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *lOutWI = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *lOutLSWI = (unsigned int *) malloc(sizeof(unsigned int)*N); unsigned int *lOutNBR2 = (unsigned int *) malloc(sizeof(unsigned int)*N); int rc, qac, qacc, qacs, qaci; //L8 band 4/5/6/7 (red/NIR/SWIR1/SWIR2) GDALRasterIO(hB4,GF_Read,0,0,nX,nY,l4,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hB5,GF_Read,0,0,nX,nY,l5,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hB6,GF_Read,0,0,nX,nY,l6,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hB7,GF_Read,0,0,nX,nY,l7,nX,nY,GDT_UInt32,0,0); //L8_QA GDALRasterIO(hB8,GF_Read,0,0,nX,nY,l8,nX,nY,GDT_UInt32,0,0); //Get the number of threads available int n = omp_get_num_threads(); //Do not stall the computer omp_set_num_threads(n-1); #pragma omp parallel for default(none) \ private (rc, qac, qacc, qacs, qaci) \ shared (N, l4, l5, l6, l7, l8, lOutVI, lOutWI, lOutLSWI, lOutNBR2) for(rc=0;rc<N;rc++){ /*process QAs*/ /*QA cloud: bit 4*/ qac=L8QA_cloud(l8[rc]); /*QA cloud confidence: bits 5-6*/ qacc=L8QA_cloud_confidence(l8[rc]); /*QA cloud shadow: bits 7-8*/ qacs=L8QA_cloud_shadow(l8[rc]); /*QA cirrus confidence: bits 11-12*/ qaci=L8QA_cirrus_confidence(l8[rc]); /*No Data in this pixel: [UInt16 val == 1] => -32768*/ if(l8[rc]==1){ lOutVI[rc] = 32768; lOutWI[rc] = 32768; lOutLSWI[rc] = 32768; lOutNBR2[rc] = 32768; /*If clouds, or cloud[shadow][cirrus] confidence QA==[00,01]->[0,1] then mask the pixel*/ }else if(qac == 1 || qacc > 2 || qacs > 2 || qaci > 2){ lOutVI[rc] = 32767; lOutWI[rc] = 32767; lOutLSWI[rc] = 32767; lOutNBR2[rc] = 32767; /*Finally, all sufficiently less cloud confident or not cloud for sure, use the band pixel value*/ }else{ /*process NDVI*/ if((l5[rc]+l4[rc])==0){ lOutVI[rc]=32768; }else{ lOutVI[rc]=(int)(10000.0*l5[rc]-l4[rc])/(1.0*l5[rc]+l4[rc]); } /*process NDWI*/ if((l6[rc]+l5[rc])==0){ lOutWI[rc]=32768; }else{ lOutWI[rc]=(int)(10000.0*l6[rc]-l5[rc])/(1.0*l6[rc]+l5[rc]); } /*process LSWI*/ if((l6[rc]+l5[rc])==0){ lOutLSWI[rc]=32768; }else{ lOutLSWI[rc]=(int)(10000.0*l5[rc]-l6[rc])/(1.0*l5[rc]+l6[rc]); } /*process NBR2*/ if((l6[rc]+l7[rc])==0){ lOutNBR2[rc]=32768; }else{ lOutNBR2[rc]=(int)(10000.0*l6[rc]-l7[rc])/(1.0*l6[rc]+l7[rc]); } } } #pragma omp barrier GDALRasterIO(hBOutVI,GF_Write,0,0,nX,nY,lOutVI,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hBOutWI,GF_Write,0,0,nX,nY,lOutWI,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hBOutLSWI,GF_Write,0,0,nX,nY,lOutLSWI,nX,nY,GDT_UInt32,0,0); GDALRasterIO(hBOutNBR2,GF_Write,0,0,nX,nY,lOutNBR2,nX,nY,GDT_UInt32,0,0); if( l4 != NULL ) free( l4 ); if( l5 != NULL ) free( l5 ); if( l6 != NULL ) free( l6 ); if( l7 != NULL ) free( l7 ); if( l8 != NULL ) free( l8 ); GDALClose(hD4); GDALClose(hD5); GDALClose(hD6); GDALClose(hD7); GDALClose(hD8); GDALClose(hDOutVI); GDALClose(hDOutWI); GDALClose(hDOutLSWI); GDALClose(hDOutNBR2); return(EXIT_SUCCESS); }
tilecorr.h
void tilecorr() { int c0,c1,c2,c3,c5,c6,c7,c9,c11,c10,c4,c12; for( c1 = 1; c1 < N + floord(N - 2, 128); c1 += 1) #pragma omp parallel for schedule(dynamic, 1) shared(c1) private(c3,c4,c9,c10,c11,c5) for( c3 = max(0, -N + c1 + 1); c3 <= (c1 - 1) / 129; c3 += 1) for( c4 = 0; c4 <= 1; c4 += 1) { if (c4 == 1) { for( c9 = N - c1 + 129 * c3; c9 <= min(N - 1, N - c1 + 129 * c3 + 127); c9 += 1) for( c10 = max(0, N - c1 + 129 * c3 - c9 + 1); c10 <= 1; c10 += 1) { if (c10 == 1) { S[(N-c1+c3-1)][c9] = MAX(S[(N-c1+c3-1)][c9], S[(N-c1+c3-1)+1][c9-1] + can_pair(RNA, (N-c1+c3-1), c9)); } else for( c11 = 128 * c3 + 1; c11 <= -N + c1 - c3 + c9; c11 += 1) S[(N-c1+c3-1)][c9] = MAX(S[(N-c1+c3-1)][c11+(N-c1+c3-1)] + S[c11+(N-c1+c3-1)+1][c9], S[(N-c1+c3-1)][c9]); } } else for( c5 = 0; c5 <= 8 * c3; c5 += 1) for( c9 = N - c1 + 129 * c3; c9 <= min(N - 1, N - c1 + 129 * c3 + 127); c9 += 1) for( c11 = 16 * c5; c11 <= min(128 * c3, 16 * c5 + 15); c11 += 1) S[(N-c1+c3-1)][c9] = MAX(S[(N-c1+c3-1)][c11+(N-c1+c3-1)] + S[c11+(N-c1+c3-1)+1][c9], S[(N-c1+c3-1)][c9]); } }
GB_unop__identity_int8_bool.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_int8_bool // op(A') function: GB_unop_tran__identity_int8_bool // C type: int8_t // A type: bool // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #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 = x ; // casting #define GB_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) 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_INT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int8_bool ( int8_t *Cx, // Cx and Ax may be aliased const bool *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 (bool), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool aij = Ax [p] ; int8_t z = (int8_t) 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 ; bool aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int8_bool ( 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
GB_unaryop__lnot_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__lnot_int64_fp32 // op(A') function: GB_tran__lnot_int64_fp32 // C type: int64_t // A type: float // cast: int64_t cij ; GB_CAST_SIGNED(cij,aij,64) // unaryop: cij = !(aij != 0) #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 != 0) ; // 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_LNOT || GxB_NO_INT64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_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__lnot_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
ScCommon.c
/*@file Implements similarity checker APIs for given code inputs. Copyright (C) 2020 Marvin Häuser. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <float.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ScCleanseConfigs.h> #include <ScCleanseInput.h> #include <ScDistances.h> #include <ScFileIo.h> #include <ScSafeInt.h> #include "ScCommon.h" /// /// Statically allocate the Levenshtein matrix buffers to avoid reallocations. /// size_t mScLevenshteinMatrixInit[SC_MAX_LINE_LENGTH]; void ScLevenshteinSwapInitialise(void) { // // Matrix[0,0] = 0 is implicit by the loop in ScLevenshteinDistance(). // This is equivalent to: Fill Matrix[0,1:] with 0,...,Str2Length. // #pragma omp simd for ( size_t ColumnIndexMinus1 = 0; ColumnIndexMinus1 < SC_MAX_LINE_LENGTH; ++ColumnIndexMinus1 ) { mScLevenshteinMatrixInit[ColumnIndexMinus1] = ColumnIndexMinus1 + 1; } } double ScLevenshteinSwap( const sc_cleanse_file_t *File1, const sc_cleanse_file_t *File2, size_t NumLinesSwap ) { assert(File1 != NULL); assert(File1->Buffer != NULL || File1->Length == 0); assert(File1->LinesInfo != NULL); assert(File2 != NULL); assert(File2->Buffer != NULL || File2->Length == 0); assert(File2->LinesInfo != NULL); // // Make sure File1 is the shorter file to improve the control flow below. // const sc_str_lines_info_t *LinesInfo1; const sc_str_lines_info_t *LinesInfo2; if (File1->LinesInfo->NumLines > File2->LinesInfo->NumLines) { LinesInfo1 = File2->LinesInfo; LinesInfo2 = File1->LinesInfo; } else { LinesInfo1 = File1->LinesInfo; LinesInfo2 = File2->LinesInfo; } // // Allocate the scratch buffer on the stack to allow parallelisation. // size_t MatrixScratch[SC_MAX_LINE_LENGTH]; // // Pair all lines in file 1 with appropiate lines in file 2. // size_t TotalDiff = 0; size_t TotalLength = 0; for ( size_t Line1Index = 0; Line1Index < LinesInfo1->NumLines; ++Line1Index ) { size_t BestMatch = SIZE_MAX; size_t MatchLength = 1; // // Lines were cleansed such that there are no subsequent new lines. As such, // the number of lines in a buffer can be at most Size / 2. Use this // knowledge to ensure the addition Line1Index + SC_NUM_LINES_SWAP is safe. // _Static_assert( SC_NUM_LINES_SWAP <= SIZE_MAX / 2, "The addition may overflow." ); // // The subtraction LinesInfo2->NumLines - 1 is safe because // 0 < LinesInfo1->NumLines <= LinesInfo2->NumLines // assert(LinesInfo2->NumLines >= LinesInfo1->NumLines); // // Check [min{Line1Index - NumLinesSwap, 0}, // min{Line1Index + NumLinesSwap, LinesInfo2->NumLines - 1}] // const size_t StartIndex = Line1Index > NumLinesSwap ? Line1Index - NumLinesSwap : 0; const size_t TopIndex = LinesInfo2->NumLines - Line1Index > NumLinesSwap ? Line1Index + NumLinesSwap + 1 : LinesInfo2->NumLines; double BestScore = DBL_MAX; // // TODO: Only match lines in file 2 once? // for (size_t Line2Index = StartIndex; Line2Index < TopIndex; ++Line2Index) { assert(Line2Index < LinesInfo2->NumLines); assert(LinesInfo1->MaxLineLength <= SC_MAX_LINE_LENGTH); assert( LinesInfo1->Lines[Line1Index].Length <= LinesInfo1->MaxLineLength ); assert(LinesInfo2->MaxLineLength <= SC_MAX_LINE_LENGTH); assert( LinesInfo2->Lines[Line2Index].Length <= LinesInfo2->MaxLineLength ); size_t Distance = ScLevenshteinDistance( mScLevenshteinMatrixInit, MatrixScratch, LinesInfo1->Lines[Line1Index].Start, LinesInfo1->Lines[Line1Index].Length, LinesInfo2->Lines[Line2Index].Start, LinesInfo2->Lines[Line2Index].Length ); size_t MatchLengthTmp = SC_MAX( LinesInfo1->Lines[Line1Index].Length, LinesInfo2->Lines[Line2Index].Length ); double CurLineScore; if (Distance == 0) { CurLineScore = 0; } else { CurLineScore = (double) Distance / (double) MatchLengthTmp; } // // Update the highest score of the pairing process for this line. // if (BestScore > CurLineScore) { BestScore = CurLineScore; BestMatch = Distance; MatchLength = MatchLengthTmp; } } // // As MatchLength can at most be the maximum of each line's length, it may // overflow TotalLength. // bool Result = ScSafeAddSize(TotalLength, MatchLength, &TotalLength); if (Result) { return (double) INFINITY; } // // The distance cannot be longer than the longer of the two references, // hence this cannot overflow if MatchLength does not overflow TotalLength. // TotalDiff += BestMatch; assert(TotalDiff >= BestMatch); } return 1. - ((double) TotalDiff / (double) TotalLength); } bool ScInitialiseCleanseFile( sc_cleanse_file_t *File, sc_cleanse_config_type_t FileType ) { assert(File != NULL); assert(File->Buffer != NULL); assert(File->Length > 0); assert(FileType >= ScCleanseConfigTypeMin && FileType <= ScCleanseConfigTypeMax); assert((unsigned int) FileType < SC_ARRAY_LEN(gScCleanseConfigs)); // // Cleanse the read file's contents using the configuration for FileType. // ScCleanseInput(File->Buffer, &File->Length, gScCleanseConfigs[FileType]); // // There is no point in returning an empty file. // if (File->Length == 0) { return false; } // // Retrieve the file lines information for the cleansed content. // File->LinesInfo = ScStrGetLineInfo(File->Buffer, File->Length); if (File->LinesInfo == NULL) { return false; } // // As the file is non-empty and subsequent new lines should be cleansed away, // no line can be empty. // for (size_t Index = 0; Index < File->LinesInfo->NumLines; ++Index) { assert(File->LinesInfo->Lines[Index].Length > 0); } // // Ensure the file line length constraints for the cleansed content. // if (File->LinesInfo->MaxLineLength > SC_MAX_LINE_LENGTH) { free(File->LinesInfo); return false; } return true; } bool ScReadCleansedFile( sc_cleanse_file_t *File, const char *FileName, sc_cleanse_config_type_t FileType ) { assert(File != NULL); assert(FileName != NULL); assert(FileType >= ScCleanseConfigTypeMin && FileType <= ScCleanseConfigTypeMax); // // Use ScCleanseConfigTypeMax as a wildcard to automatically detect the // cleansing configuration. // if (FileType == ScCleanseConfigTypeMax) { const char *FileExt = ScGetFileExtension(FileName); _Static_assert( SC_ARRAY_LEN(gScCleanseConfigs) == ScCleanseConfigTypeMax + 1, "The loop must be adapted." ); // // Iterate over all cleansing configurations to match by file extension. // for ( FileType = ScCleanseConfigTypeMin; FileType < ScCleanseConfigTypeMax; ++FileType ) { size_t ExtIndex; for ( ExtIndex = 0; ExtIndex < gScCleanseConfigs[FileType]->NumFileExt; ++ExtIndex ) { int Result = strcmp( FileExt, gScCleanseConfigs[FileType]->FileExts[ExtIndex] ); if (Result == 0) { break; } } // // If a match was found, terminate this outer loop too. // if (ExtIndex < gScCleanseConfigs[FileType]->NumFileExt) { break; } } // // If the type could not be automatically detected, FileType will be // ScCleanseConfigTypeMax and a profile for unknown inputs will be used. // assert(FileType >= ScCleanseConfigTypeMin && FileType <= ScCleanseConfigTypeMax); } // // Read the file at FileName. // File->Buffer = ScReadFile(&File->Length, FileName, SC_MAX_FILE_SIZE); if (File->Buffer == NULL) { return false; } // // Cleanse the read file's contents using the configuration for FileType. // bool Result = ScInitialiseCleanseFile(File, FileType); if (!Result) { free(File->Buffer); } return Result; } void ScFreeCleansedFile( sc_cleanse_file_t *File ) { assert(File != NULL); free(File->LinesInfo); free(File->Buffer); }
pvector.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef PVECTOR_H_ #define PVECTOR_H_ #include <algorithm> /* GAP Benchmark Suite Class: pvector Author: Scott Beamer Vector class with ability to not initialize or do initialize in parallel - std::vector (when resizing) will always initialize, and does it serially - When pvector is resized, new elements are uninitialized - Resizing is not thread-safe */ template <typename T_> class pvector { public: typedef T_* iterator; pvector() : start_(nullptr), end_size_(nullptr), end_capacity_(nullptr) {} explicit pvector(size_t num_elements) { start_ = new T_[num_elements]; end_size_ = start_ + num_elements; end_capacity_ = end_size_; } pvector(size_t num_elements, T_ init_val) : pvector(num_elements) { fill(init_val); } pvector(iterator copy_begin, iterator copy_end) : pvector(copy_end - copy_begin) { #pragma omp parallel for for (size_t i=0; i < capacity(); i++) start_[i] = copy_begin[i]; } // don't want this to be copied, too much data to move pvector(const pvector &other) = delete; // prefer move because too much data to copy pvector(pvector &&other) : start_(other.start_), end_size_(other.end_size_), end_capacity_(other.end_capacity_) { other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; } // want move assignment pvector& operator= (pvector &&other) { start_ = other.start_; end_size_ = other.end_size_; end_capacity_ = other.end_capacity_; other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; return *this; } ~pvector() { if (start_ != nullptr) delete[] start_; } // not thread-safe void reserve(size_t num_elements) { if (num_elements > capacity()) { T_ *new_range = new T_[num_elements]; #pragma omp parallel for for (size_t i=0; i < size(); i++) new_range[i] = start_[i]; end_size_ = new_range + size(); delete[] start_; start_ = new_range; end_capacity_ = start_ + num_elements; } } bool empty() { return end_size_ == start_; } void clear() { end_size_ = start_; } void resize(size_t num_elements) { reserve(num_elements); end_size_ = start_ + num_elements; } T_& operator[](size_t n) { return start_[n]; } const T_& operator[](size_t n) const { return start_[n]; } void push_back(T_ val) { if (size() == capacity()) { size_t new_size = capacity() == 0 ? 1 : capacity() * growth_factor; reserve(new_size); } *end_size_ = val; end_size_++; } void fill(T_ init_val) { #pragma omp parallel for for (T_* ptr=start_; ptr < end_size_; ptr++) *ptr = init_val; } size_t capacity() const { return end_capacity_ - start_; } size_t size() const { return end_size_ - start_; } iterator begin() const { return start_; } iterator end() const { return end_size_; } T_* data() const { return start_; } void PrintEdgePairVector() { for (T_* ptr=start_; ptr < end_size_; ptr++) (*ptr).PrintPair(); } void PrintNodeIDVector() { for (T_* ptr=start_; ptr < end_size_; ptr++) std::cout << " -- " << *ptr << std::endl; } void swap(pvector &other) { std::swap(start_, other.start_); std::swap(end_size_, other.end_size_); std::swap(end_capacity_, other.end_capacity_); } private: T_* start_; T_* end_size_; T_* end_capacity_; static const size_t growth_factor = 2; }; #endif // PVECTOR_H_
GB_unaryop__abs_int64_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__abs_int64_bool // op(A') function: GB_tran__abs_int64_bool // C type: int64_t // A type: bool // cast: int64_t cij = (int64_t) aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ bool #define GB_CTYPE \ int64_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_IABS (x) ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT64 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int64_bool ( int64_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__abs_int64_bool ( 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
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_binop__bxor_uint16.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__bxor_uint16 // A.*B function (eWiseMult): GB_AemultB__bxor_uint16 // A*D function (colscale): GB_AxD__bxor_uint16 // D*A function (rowscale): GB_DxB__bxor_uint16 // C+=B function (dense accum): GB_Cdense_accumB__bxor_uint16 // C+=b function (dense accum): GB_Cdense_accumb__bxor_uint16 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bxor_uint16 // C=scalar+B GB_bind1st__bxor_uint16 // C=scalar+B' GB_bind1st_tran__bxor_uint16 // C=A+scalar GB_bind2nd__bxor_uint16 // C=A'+scalar GB_bind2nd_tran__bxor_uint16 // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // 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) \ uint16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint16_t bij = Bx [pB] // 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) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x) ^ (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_BXOR || GxB_NO_UINT16 || GxB_NO_BXOR_UINT16) //------------------------------------------------------------------------------ // 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__bxor_uint16 ( 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__bxor_uint16 ( 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__bxor_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__bxor_uint16 ( 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 uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__bxor_uint16 ( 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 uint16_t *GB_RESTRICT Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__bxor_uint16 ( 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__bxor_uint16 ( 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__bxor_uint16 ( 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 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 < anz ; p++) { uint16_t bij = Bx [p] ; Cx [p] = (x) ^ (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__bxor_uint16 ( 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 ; 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++) { uint16_t aij = Ax [p] ; Cx [p] = (aij) ^ (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = (x) ^ (aij) ; \ } GrB_Info GB_bind1st_tran__bxor_uint16 ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #define GB_PHASE_2_OF_2 #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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = (aij) ^ (y) ; \ } GrB_Info GB_bind2nd_tran__bxor_uint16 ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
csr_block_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRBlockMatrix class. * *****************************************************************************/ #include "csr_block_matrix.h" #include "../seq_mv/seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_CSRBlockMatrixMatvec *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRBlockMatrixMatvec(HYPRE_Complex alpha, hypre_CSRBlockMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y) { HYPRE_Complex *A_data = hypre_CSRBlockMatrixData(A); HYPRE_Int *A_i = hypre_CSRBlockMatrixI(A); HYPRE_Int *A_j = hypre_CSRBlockMatrixJ(A); HYPRE_Int num_rows = hypre_CSRBlockMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRBlockMatrixNumCols(A); HYPRE_Int blk_size = hypre_CSRBlockMatrixBlockSize(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int i, b1, b2, jj, bnnz=blk_size*blk_size; HYPRE_Int ierr = 0; HYPRE_Complex temp; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_cols*blk_size != x_size) ierr = 1; if (num_rows*blk_size != y_size) ierr = 2; if (num_cols*blk_size != x_size && num_rows*blk_size != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*blk_size; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*blk_size; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*blk_size; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj,b1,b2,temp) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { for (b1 = 0; b1 < blk_size; b1++) { temp = y_data[i*blk_size+b1]; for (b2 = 0; b2 < blk_size; b2++) temp += A_data[jj*bnnz+b1*blk_size+b2] * x_data[A_j[jj]*blk_size+b2]; y_data[i*blk_size+b1] = temp; } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*blk_size; i++) y_data[i] *= alpha; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRBlockMatrixMatvecT * * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRBlockMatrixMatvecT( HYPRE_Complex alpha, hypre_CSRBlockMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { HYPRE_Complex *A_data = hypre_CSRBlockMatrixData(A); HYPRE_Int *A_i = hypre_CSRBlockMatrixI(A); HYPRE_Int *A_j = hypre_CSRBlockMatrixJ(A); HYPRE_Int num_rows = hypre_CSRBlockMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRBlockMatrixNumCols(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Complex temp; HYPRE_Int i, j, jj; HYPRE_Int ierr = 0; HYPRE_Int b1, b2; HYPRE_Int blk_size = hypre_CSRBlockMatrixBlockSize(A); HYPRE_Int bnnz=blk_size*blk_size; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_rows*blk_size != x_size) ierr = 1; if (num_cols*blk_size != y_size) ierr = 2; if (num_rows*blk_size != x_size && num_cols*blk_size != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*blk_size; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*blk_size; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*blk_size; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i, jj,j, b1, b2) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) /*each nonzero in that row*/ { for (b1 = 0; b1 < blk_size; b1++) /*row */ { for (b2 = 0; b2 < blk_size; b2++) /*col*/ { j = A_j[jj]; /*col */ y_data[j*blk_size+b2] += A_data[jj*bnnz+b1*blk_size+b2] * x_data[i*blk_size + b1]; } } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*blk_size; i++) y_data[i] *= alpha; } return ierr; }
librcorrect.c
#include <inttypes.h> #include <stdio.h> #include <ctype.h> #include <omp.h> #include "err.h" #include "utils.h" #include "reads.h" #include "fml.h" #include "librcorrect.h" UTILS_TYPED_CALLOC_FUNCTION(bseq1_t) static char *_copy_string(const char *str, const size_t len) { char *ret = NULL; ret = malloc((len + 1)*sizeof(char)); if (ret != NULL) { memcpy(ret, str, len*sizeof(char)); ret[len] = '\0'; } return ret; } static ERR_VALUE convert_to_fermilite(PONE_READ Reads, size_t Count, bseq1_t **Result) { ERR_VALUE ret = ERR_INTERNAL_ERROR; bseq1_t *tmpResult = NULL; ret = utils_calloc_bseq1_t(Count, &tmpResult); if (ret == ERR_SUCCESS) { int i = 0; #pragma omp parallel for shared(Reads, tmpResult) for (i = 0; i < (int)Count; ++i) { memset(tmpResult + i, 0, sizeof(tmpResult[i])); tmpResult[i].l_seq = Reads[i].ReadSequenceLen; read_quality_encode(Reads + i); tmpResult[i].seq = _copy_string(Reads[i].ReadSequence, Reads[i].ReadSequenceLen); if (Reads[i].Quality != NULL) tmpResult[i].qual = _copy_string((char *)Reads[i].Quality, Reads[i].ReadSequenceLen); read_quality_decode(Reads + i); if (Reads[i].ReadSequenceLen > 0) { utils_free(Reads[i].Quality); utils_free(Reads[i].ReadSequence); } } if (ret == ERR_SUCCESS) *Result = tmpResult; if (ret != ERR_SUCCESS) utils_free(tmpResult); } return ret; } static ERR_VALUE convert_to_gassm2(const bseq1_t *Seqs, size_t Count, PONE_READ Reads) { ERR_VALUE ret = ERR_INTERNAL_ERROR; int i = 0; #pragma omp parallel for shared(Reads, Seqs) for (i = 0; i < (int)Count; ++i) { if (Seqs[i].l_seq != Reads[i].ReadSequenceLen) { char cigar[20]; memset(cigar, 0, sizeof(cigar)); if (Reads[i].Pos > 0) snprintf(cigar, sizeof(cigar), "%iM", Seqs[i].l_seq); else cigar[0] = '*'; utils_copy_string(cigar, &Reads[i].Extension->CIGAR); } Reads[i].ReadSequenceLen = Seqs[i].l_seq; ret = utils_copy_string(Seqs[i].seq, &Reads[i].ReadSequence); if (ret == ERR_SUCCESS) ret = utils_copy_string(Seqs[i].qual, (uint8_t **)&Reads[i].Quality); if (Seqs[i].l_seq > 0) { free(Seqs[i].seq); free(Seqs[i].qual); } for (uint32_t j = 0; j < Reads[i].ReadSequenceLen; ++j) Reads[i].ReadSequence[j] = toupper(Reads[i].ReadSequence[j]); } return ret; } ERR_VALUE libcorrect_state_init(PLIBCORRECT_STATE State, PONE_READ Reads, const size_t Count) { ERR_VALUE ret = ERR_INTERNAL_ERROR; ret = utils_malloc(sizeof(fml_opt_t), &State->Options); if (ret == ERR_SUCCESS) { bseq1_t *seqs = NULL; fml_opt_t *options = (fml_opt_t *)State->Options; State->Count = Count; State->Reads = Reads; fml_opt_init(options); options->n_threads = omp_get_num_procs(); ret = convert_to_fermilite(Reads, Count, &seqs); if (ret == ERR_SUCCESS) { State->ConvertedReads = seqs; fml_opt_adjust(options, Count, seqs); } if (ret != ERR_SUCCESS) utils_free(State->Options); } return ret; } void libcorrect_correct(PLIBCORRECT_STATE State) { bseq1_t *seqs = (bseq1_t *)State->ConvertedReads; const fml_opt_t *options = (fml_opt_t *)State->Options; fml_correct(options, State->Count, seqs); fml_fltuniq(options, State->Count, seqs); return; } ERR_VALUE libcorrect_correct_stats(const LIBCORRECT_STATE *State, PLIBRCORRECT_STATISTICS Stats) { bseq1_t *seqs = (bseq1_t *)State->ConvertedReads; const fml_opt_t *options = (fml_opt_t *)State->Options; ERR_VALUE ret = ERR_INTERNAL_ERROR; memset(Stats, 0, sizeof(LIBRCORRECT_STATISTICS)); Stats->K = options->ec_k; Stats->TotalReads = State->Count; for (size_t i = 0; i < State->Count; ++i) { Stats->TotalBases += State->Reads[i].ReadSequenceLen; if (Stats->RepairCountDistributionCount < State->Reads[i].ReadSequenceLen) Stats->RepairCountDistributionCount = State->Reads[i].ReadSequenceLen; } ret = utils_calloc_uint64_t(2 * Stats->RepairCountDistributionCount, &Stats->RepairCountDistribution); if (ret == ERR_SUCCESS) { Stats->RepairBasePositionDistribution = Stats->RepairCountDistribution + Stats->RepairCountDistributionCount; for (size_t i = 0; i < State->Count; ++i) { const bseq1_t *s = seqs + i; if (s->l_seq > 0) { uint32_t repairCount = 0; if (s->l_seq != State->Reads[i].ReadSequenceLen) ++Stats->ReadsShortened; for (int32_t j = 0; j < s->l_seq; ++j) { if (s->seq[j] == 'a' || s->seq[j] == 'c' || s->seq[j] == 'g' || s->seq[j] == 't') { ++repairCount; ++Stats->RepairBasePositionDistribution[s->l_seq - j - 1]; } } Stats->TotalRepairs += repairCount; ++Stats->RepairCountDistribution[repairCount]; } else ++Stats->ReadsRemoved; } } return ret; } void librcorrect_stats_free(PLIBRCORRECT_STATISTICS Stats) { utils_free(Stats->RepairCountDistribution); memset(Stats, 0, sizeof(LIBRCORRECT_STATISTICS)); return; } ERR_VALUE librcorrect_state_finit(PLIBCORRECT_STATE State) { ERR_VALUE ret = ERR_INTERNAL_ERROR; bseq1_t *seqs = (bseq1_t *)State->ConvertedReads; ret = convert_to_gassm2(seqs, State->Count, State->Reads); if (ret == ERR_SUCCESS) { for (size_t i = 0; i < State->Count; ++i) read_quality_decode(State->Reads + i); } utils_free(seqs); return ret; } void libcorrect_stats_print(FILE *Stream, const LIBRCORRECT_STATISTICS *Stats) { fprintf(Stream, "K: %u\n", Stats->K); fprintf(Stream, "Total reads: %" PRIu64 "\n", Stats->TotalReads); fprintf(Stream, "Removed reads: %" PRIu64 "\n", Stats->ReadsRemoved); fprintf(Stream, "Shortened reads: %" PRIu64 "\n", Stats->ReadsShortened); fprintf(Stream, "Total bases: %" PRIu64 "\n", Stats->TotalBases); fprintf(Stream, "Total repairs: %" PRIu64 "\n", Stats->TotalRepairs); fputs("Repair count distribution:\n", stderr); for (uint32_t i = 0; i < Stats->RepairCountDistributionCount; ++i) { if (Stats->RepairCountDistribution[i] > 0) fprintf(Stream, "%u,\t%" PRIu64 "\t%.3lf %%\n", i, Stats->RepairCountDistribution[i], (double)Stats->RepairCountDistribution[i] * 100 / Stats->TotalReads); } fputs("Repair base position distribution:\n", Stream); for (uint32_t i = 0; i < Stats->RepairCountDistributionCount; ++i) { if (Stats->RepairBasePositionDistribution[i] > 0) fprintf(Stream, "%u,\t%" PRIu64 "\t%.3lf %%\n", i, Stats->RepairBasePositionDistribution[i], (double)Stats->RepairBasePositionDistribution[i] * 100 / Stats->TotalRepairs); } return; }
GB_binop__eq_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 Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_03__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_uint16) // A*D function (colscale): GB (_AxD__eq_uint16) // D*A function (rowscale): GB (_DxB__eq_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__eq_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__eq_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_uint16) // C=scalar+B GB (_bind1st__eq_uint16) // C=scalar+B' GB (_bind1st_tran__eq_uint16) // C=A+scalar GB (_bind2nd__eq_uint16) // C=A'+scalar GB (_bind2nd_tran__eq_uint16) // C type: bool // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_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) \ uint16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x == y) ; // 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_EQ || GxB_NO_UINT16 || GxB_NO_EQ_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 //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__eq_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__eq_uint16) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__eq_uint16) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_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 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__eq_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_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__eq_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_03__eq_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_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__eq_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__eq_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 anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = Bx [p] ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_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 ; bool *Cx = (bool *) 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 = 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) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__eq_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 = Ax [pA] ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__eq_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
bml_normalize_dense_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_add.h" #include "../bml_allocate.h" #include "../bml_normalize.h" #include "../bml_parallel.h" #include "../bml_types.h" #include "bml_add_dense.h" #include "bml_allocate_dense.h" #include "bml_getters_dense.h" #include "bml_normalize_dense.h" #include "bml_scale_dense.h" #include "bml_types_dense.h" #ifdef BML_USE_MAGMA #include "magma_v2.h" #endif #include <complex.h> #include <float.h> #include <math.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /** Normalize dense matrix given Gershgorin bounds. * * \ingroup normalize_group * * \param A The matrix * \param mineval Calculated min value * \param maxeval Calculated max value */ void TYPED_FUNC( bml_normalize_dense) ( bml_matrix_dense_t * A, double mineval, double maxeval) { double maxminusmin = maxeval - mineval; double beta = maxeval / maxminusmin; double alpha = (double) -1.0 / maxminusmin; TYPED_FUNC(bml_scale_add_identity_dense) (A, alpha, beta); } /** Calculate Gershgorin bounds for a dense matrix. * * \ingroup gershgorin_group * * \param A The matrix * returns mineval Calculated min value * returns maxeval Calculated max value */ void *TYPED_FUNC( bml_gershgorin_dense) ( bml_matrix_dense_t * A) { REAL_T radius, dvalue, absham; int N = A->N; int *A_localRowMin = A->domain->localRowMin; int *A_localRowMax = A->domain->localRowMax; int myRank = bml_getMyRank(); double emin = DBL_MAX; double emax = DBL_MIN; double *eval = bml_allocate_memory(sizeof(double) * 2); #ifdef BML_USE_MAGMA //copy data from GPU to CPU to do the work on the CPU REAL_T *A_matrix = bml_allocate_memory(sizeof(REAL_T) * A->N * A->N); MAGMA(getmatrix) (A->N, A->N, A->matrix, A->ld, (MAGMA_T *) A_matrix, A->N, bml_queue()); #else REAL_T *A_matrix = A->matrix; #endif #pragma omp parallel for \ shared(N, A_matrix) \ shared(A_localRowMin, A_localRowMax, myRank) \ private(absham, radius, dvalue) \ reduction(max:emax) \ reduction(min:emin) //for (int i = 0; i < N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { radius = 0.0; for (int j = 0; j < N; j++) { absham = ABS(A_matrix[ROWMAJOR(i, j, N, N)]); radius += (double) absham; } dvalue = A_matrix[ROWMAJOR(i, i, N, N)]; radius -= ABS(dvalue); /* emax = (emax > REAL_PART(dvalue + radius) ? emax : REAL_PART(dvalue + radius)); emin = (emin < REAL_PART(dvalue - radius) ? emin : REAL_PART(dvalue - radius)); */ if (REAL_PART(dvalue + radius) > emax) emax = REAL_PART(dvalue + radius); if (REAL_PART(dvalue - radius) < emin) emin = REAL_PART(dvalue - radius); } #ifdef BML_USE_MAGMA bml_free_memory(A_matrix); #endif #ifdef DO_MPI if (bml_getNRanks() > 1 && A->distribution_mode == distributed) { bml_minRealReduce(&emin); bml_maxRealReduce(&emax); } #endif eval[0] = emin; eval[1] = emax; return eval; } /** Calculate Gershgorin bounds for a partial dense matrix. * * \ingroup gershgorin_group * * \param A The matrix * \param nrows Number of rows used * returns mineval Calculated min value * returns maxeval Calculated max value */ void *TYPED_FUNC( bml_gershgorin_partial_dense) ( bml_matrix_dense_t * A, int nrows) { REAL_T radius, dvalue, absham; int N = A->N; REAL_T *A_matrix = A->matrix; double emin = DBL_MAX; double emax = DBL_MIN; double *eval = bml_allocate_memory(sizeof(double) * 2); #pragma omp parallel for \ shared(N, A_matrix) \ private(absham, radius, dvalue) \ reduction(max:emax) \ reduction(min:emin) for (int i = 0; i < nrows; i++) { radius = 0.0; for (int j = 0; j < N; j++) { absham = ABS(A_matrix[ROWMAJOR(i, j, N, N)]); radius += (double) absham; } dvalue = A_matrix[ROWMAJOR(i, i, N, N)]; radius -= ABS(dvalue); if (REAL_PART(dvalue + radius) > emax) emax = REAL_PART(dvalue + radius); if (REAL_PART(dvalue - radius) < emin) emin = REAL_PART(dvalue - radius); } eval[0] = emin; eval[1] = emax; return eval; }
diagmm_x_coo_n_col.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "memory.h" #include "alphasparse/opt.h" alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy) { ALPHA_INT rowA = mat->rows; ALPHA_INT nnz = mat->nnz; ALPHA_INT num_threads = alpha_get_thread_num(); ALPHA_Number diag[rowA]; memset(diag, '\0', sizeof(ALPHA_Number) * rowA); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT ar = 0; ar < nnz; ++ar) { if (mat->col_indx[ar] == mat->row_indx[ar]) { diag[mat->row_indx[ar]] = mat->values[ar]; } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT cc = 0; cc < columns; ++cc) for (ALPHA_INT cr = 0; cr < rowA; ++cr) { ALPHA_Number t; alpha_setzero(t); alpha_mul(t, alpha, diag[cr]); alpha_mul(t, t, x[index2(cc, cr, ldx)]); alpha_mul(y[index2(cc, cr, ldy)], beta, y[index2(cc, cr, ldy)]); alpha_add(y[index2(cc, cr, ldy)], y[index2(cc, cr, ldy)], t); } return ALPHA_SPARSE_STATUS_SUCCESS; }
triad.h
#ifndef TRIAD_H #define TRIAD_H #include <iostream> #include <vector> #include <random> #include <set> namespace TSnap { ///////////////////////////////////////////////// // Triads and clustering coefficient /// Computes the average clustering coefficient as defined in Watts and Strogatz, Collective dynamics of 'small-world' networks. ##TSnap::GetClustCf template <class PGraph> double GetClustCf(const PGraph& Graph, int64_t SampleNodes=-1); /// Computes the distribution of average clustering coefficient. ##TSnap::GetClustCf1 template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64_t SampleNodes=-1); /// Computes the distribution of average clustering coefficient as well as the number of open and closed triads in the graph. ##TSnap::GetClustCf2 template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64& ClosedTriadsX, int64& OpenTriadsX, int64_t SampleNodes=-1); /// Returns clustering coefficient of a particular node. ##TSnap::GetNodeClustCf template <class PGraph> double GetNodeClustCf(const PGraph& Graph, const int& NId); /// Computes clustering coefficient of each node of the Graph. ##TSnap::GetClustCf1 template <class PGraph> void GetNodeClustCf(const PGraph& Graph, TIntFltH& NIdCCfH); template <class PGraph> void GetNodeClustCf_scala(const PGraph& Graph, TIntFltH& NIdCCfH); template <class PGraph> void GetNodeClustCf(const PGraph& Graph, std::vector<float>& NIdCCfH); /// Returns the number of triangles in a graph. ##TSnap::GetTriads template <class PGraph> int64 GetTriads(const PGraph& Graph, int64_t SampleNodes=-1); /// Computes the number of Closed and Open triads. ##TSnap::GetTriads1 template <class PGraph> int64 GetTriads(const PGraph& Graph, int64& ClosedTriadsX, int64& OpenTriadsX, int64_t SampleNodes); /// Computes the number of open and close triads for every node of the network. ##TSnap::GetTriads2 template <class PGraph> void GetTriads(const PGraph& Graph, TIntTrV& NIdCOTriadV, int64_t SampleNodes=-1); template <class PGraph> void GetTriads_v0(const PGraph& Graph, TIntTrV& NIdCOTriadV, int SampleNodes=-1); template <class PGraph> void GetTriads(const PGraph& Graph, std::vector<TUInt64Tr>& NIdCOTriadV, int64_t SampleNodes=-1); /// Counts the number of edges that participate in at least one triad. ##TSnap::GetTriadEdges template <class PGraph> int GetTriadEdges(const PGraph& Graph, int SampleEdges=-1); /// Returns the number of undirected triads a node \c NId participates in. ##TSnap::GetNodeTriads template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId); /// Returns number of Open and Closed triads a node \c NId participates in. ##TSnap::GetNodeTriads1 template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId, int& ClosedNTriadsX, int& OpenNTriadsX); /// Returns the number of triads between a node \c NId and a subset of its neighbors \c GroupSet. ##TSnap::GetNodeTriads3 template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId, const TIntSet& GroupSet, int& InGroupEdgesX, int& InOutGroupEdgesX, int& OutGroupEdgesX); /// Triangle Participation Ratio: For each node counts how many triangles it participates in and then returns a set of pairs (number of triangles, number of such nodes). ##TSnap::GetTriadParticip template <class PGraph> void GetTriadParticip(const PGraph& Graph, TIntPrV& TriadCntV); /// Returns a number of shared neighbors between a pair of nodes NId1 and NId2. template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2); /// Returns the shared neighbors between a pair of nodes NId1 and NId2. template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV); /// Returns the number of length 2 directed paths between a pair of nodes NId1, NId2 (NId1 --> U --> NId2). template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2); /// Returns the 2 directed paths between a pair of nodes NId1, NId2 (NId1 --> U --> NId2). ##TSnap::GetLen2Paths template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV); /// Returns the number of triangles in graph \c Graph, original version template<class PGraph> int64 CountTriangles(const PGraph& Graph); /// Returns the number of triangles in graph \c Graph, newer version template<class PGraph> int64 GetTriangleCnt(const PGraph& Graph); /// Merges neighbors. template<class PGraph> void MergeNbrs(TIntV& NeighbourV, const typename PGraph::TObj::TNodeI& NI); template<class PGraph> void GetMergeSortedV(TIntV& NeighbourV, typename PGraph::TObj::TNodeI NI); /// Returns sorted vector \c NbrV containing unique in or out neighbors of node \c NId in graph \c Graph template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int& NId, TIntV& NbrV); template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int64_t& NId, std::vector< int64_t>& NbrV); /// Returns the number of common elements in two sorted TInt vectors int GetCommon(TIntV& A, TIntV& B); int64_t GetCommon(const std::vector< int64_t>& A, const std::vector< int64_t>& B); ///////////////////////////////////////////////// // Implementation template<class PGraph> void GetMergeSortedV(TIntV& NeighbourV, typename PGraph::TObj::TNodeI NI) { int j = 0; int k = 0; int prev = -1; int indeg = NI.GetInDeg(); int outdeg = NI.GetOutDeg(); if (indeg > 0 && outdeg > 0) { int v1 = NI.GetInNId(j); int v2 = NI.GetOutNId(k); while (1) { if (v1 <= v2) { if (prev != v1) { NeighbourV.Add(v1); prev = v1; } j += 1; if (j >= indeg) { break; } v1 = NI.GetInNId(j); } else { if (prev != v2) { NeighbourV.Add(v2); prev = v2; } k += 1; if (k >= outdeg) { break; } v2 = NI.GetOutNId(k); } } } while (j < indeg) { int v = NI.GetInNId(j); if (prev != v) { NeighbourV.Add(v); prev = v; } j += 1; } while (k < outdeg) { int v = NI.GetOutNId(k); if (prev != v) { NeighbourV.Add(v); prev = v; } k += 1; } } template <class PGraph> double GetClustCf(const PGraph& Graph, int64_t SampleNodes) { std::vector<TUInt64Tr> NIdCOTriadV; GetTriads(Graph, NIdCOTriadV, SampleNodes); if (NIdCOTriadV.empty()) { return 0.0; } double SumCcf = 0.0; for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) { const double OpenCnt = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); if (OpenCnt > 0) { SumCcf += NIdCOTriadV[i].Val2() / OpenCnt; } } IAssert(SumCcf>=0); return SumCcf / double(NIdCOTriadV.size()); } template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64_t SampleNodes) { TIntTrV NIdCOTriadV; GetTriads(Graph, NIdCOTriadV, SampleNodes); THash<TInt, TFltPr> DegSumCnt; double SumCcf = 0.0; for (int i = 0; i < NIdCOTriadV.Len(); i++) { const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0; TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg()); SumCnt.Val1 += Ccf; SumCnt.Val2 += 1; SumCcf += Ccf; } // get average clustering coefficient for each degree DegToCCfV.Gen(DegSumCnt.Len(), 0); for (int d = 0; d < DegSumCnt.Len(); d++) { DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, double(DegSumCnt[d].Val1()/DegSumCnt[d].Val2()))); } DegToCCfV.Sort(); return SumCcf / double(NIdCOTriadV.Len()); } template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64& ClosedTriads, int64& OpenTriads, int64_t SampleNodes) { TIntTrV NIdCOTriadV; GetTriads(Graph, NIdCOTriadV, SampleNodes); THash<TInt, TFltPr> DegSumCnt; double SumCcf = 0.0; int64 closedTriads = 0; int64 openTriads = 0; for (int i = 0; i < NIdCOTriadV.Len(); i++) { const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0; closedTriads += NIdCOTriadV[i].Val2; openTriads += NIdCOTriadV[i].Val3; TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg()); SumCnt.Val1 += Ccf; SumCnt.Val2 += 1; SumCcf += Ccf; } // get average clustering coefficient for each degree DegToCCfV.Gen(DegSumCnt.Len(), 0); for (int d = 0; d < DegSumCnt.Len(); d++) { DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, DegSumCnt[d].Val1()/DegSumCnt[d].Val2())); } //if(closedTriads/3 > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g closed triads.\n", __FILE__, __LINE__, float(closedTriads/3)).CStr()); } //if(openTriads > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g open triads.\n", __FILE__, __LINE__, float(openTriads/3)).CStr()); } ClosedTriads = closedTriads/int64(3); // each triad is counted 3 times OpenTriads = openTriads; DegToCCfV.Sort(); return SumCcf / double(NIdCOTriadV.Len()); } template <class PGraph> double GetNodeClustCf(const PGraph& Graph, const int& NId) { int Open, Closed; GetNodeTriads(Graph, NId, Open, Closed); //const double Deg = Graph->GetNI(NId).GetDeg(); return (Open+Closed)==0 ? 0 : double(Open)/double(Open+Closed); } template <class PGraph> void GetNodeClustCf(const PGraph& Graph, std::vector<float>& NIdCCfH) { std::vector<TUInt64Tr> NIdCOTriadV; GetTriads(Graph, NIdCOTriadV); NIdCCfH.clear(); NIdCCfH.reserve(Graph->GetNodes()); for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) { const int64_t D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0; NIdCCfH[NIdCOTriadV[i].Val1] = CCf; } } template <class PGraph> void GetNodeClustCf(const PGraph& Graph, TIntFltH& NIdCCfH) { TIntTrV NIdCOTriadV; GetTriads(Graph, NIdCOTriadV); NIdCCfH.Clr(false); for (int i = 0; i < NIdCOTriadV.Len(); i++) { const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0; NIdCCfH.AddDat(NIdCOTriadV[i].Val1, CCf); } } template <class PGraph> void GetNodeClustCf_scala(const PGraph& Graph, TIntFltH& NIdCCfH) { TIntTrV NIdCOTriadV; GetTriads_v0(Graph, NIdCOTriadV); NIdCCfH.Clr(false); for (int i = 0; i < NIdCOTriadV.Len(); i++) { const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3(); const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0; NIdCCfH.AddDat(NIdCOTriadV[i].Val1, CCf); } } template <class PGraph> int64 GetTriads(const PGraph& Graph, int64_t SampleNodes) { int64 OpenTriads, ClosedTriads; return GetTriads(Graph, ClosedTriads, OpenTriads, SampleNodes); } template <class PGraph> int64 GetTriads(const PGraph& Graph, int64& ClosedTriads, int64& OpenTriads, int64_t SampleNodes) { std::vector<TUInt64Tr> NIdCOTriadV; GetTriads(Graph, NIdCOTriadV, SampleNodes); uint64 closedTriads = 0; uint64 openTriads = 0; for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) { closedTriads += NIdCOTriadV[i].Val2; openTriads += NIdCOTriadV[i].Val3; } ClosedTriads = int64(closedTriads/3); // each triad is counted 3 times OpenTriads = int64(openTriads); return ClosedTriads; } // Function pretends that the graph is undirected (count unique connected triples of nodes) // This implementation is slower, it uses hash tables directly template <class PGraph> void GetTriads_v0(const PGraph& Graph, TIntTrV& NIdCOTriadV, int SampleNodes) { const bool IsDir = Graph->HasFlag(gfDirected); TIntSet NbrH; TIntV NIdV; TRnd Rnd(0); Graph->GetNIdV(NIdV); NIdV.Shuffle(Rnd); if (SampleNodes == -1) { SampleNodes = Graph->GetNodes(); } NIdCOTriadV.Clr(false); NIdCOTriadV.Reserve(SampleNodes); for (int node = 0; node < SampleNodes; node++) { typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[node]); if (NI.GetDeg() < 2) { NIdCOTriadV.Add(TIntTr(NI.GetId(), 0, 0)); // zero triangles continue; } // find neighborhood NbrH.Clr(false); for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetOutNId(e) != NI.GetId()) { NbrH.AddKey(NI.GetOutNId(e)); } } if (IsDir) { for (int e = 0; e < NI.GetInDeg(); e++) { if (NI.GetInNId(e) != NI.GetId()) { NbrH.AddKey(NI.GetInNId(e)); } } } // count connected neighbors int OpenCnt=0, CloseCnt=0; for (int srcNbr = 0; srcNbr < NbrH.Len(); srcNbr++) { const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrH.GetKey(srcNbr)); for (int dstNbr = srcNbr+1; dstNbr < NbrH.Len(); dstNbr++) { const int dstNId = NbrH.GetKey(dstNbr); if (SrcNode.IsNbrNId(dstNId)) { CloseCnt++; } // is edge else { OpenCnt++; } } } IAssert(2*(OpenCnt+CloseCnt) == NbrH.Len()*(NbrH.Len()-1)); NIdCOTriadV.Add(TIntTr(NI.GetId(), CloseCnt, OpenCnt)); } } // Function pretends that the graph is undirected (count unique connected triples of nodes) // This implementation is faster, it converts hash tables to vectors template <class PGraph> void GetTriads(const PGraph& Graph, TIntTrV& NIdCOTriadV, int64_t SampleNodes) { const bool IsDir = Graph->HasFlag(gfDirected); TIntSet NbrH; TIntV NIdV; //TRnd Rnd(0); TRnd Rnd(1); int NNodes; TIntV Nbrs; int NId; int64 hcount; hcount = 0; NNodes = Graph->GetNodes(); Graph->GetNIdV(NIdV); NIdV.Shuffle(Rnd); if (SampleNodes == -1) { SampleNodes = NNodes; } int MxId = -1; for (int i = 0; i < NNodes; i++) { if (NIdV[i] > MxId) { MxId = NIdV[i]; } } TVec<TIntV> NbrV(MxId + 1); if (IsDir) { // get in and out neighbors for (int node = 0; node < NNodes; node++) { int NId = NIdV[node]; NbrV[NId] = TIntV(); GetUniqueNbrV(Graph, NId, NbrV[NId]); } } else { // get only out neighbors for (int node = 0; node < NNodes; node++) { int NId = NIdV[node]; typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId); NbrV[NId] = TIntV(); NbrV[NId].Reserve(NI.GetOutDeg()); NbrV[NId].Reduce(0); for (int i = 0; i < NI.GetOutDeg(); i++) { NbrV[NId].Add(NI.GetOutNId(i)); } } } NIdCOTriadV.Clr(false); NIdCOTriadV.Reserve(SampleNodes); for (int node = 0; node < SampleNodes; node++) { typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[node]); int NLen; NId = NI.GetId(); hcount++; if (NI.GetDeg() < 2) { NIdCOTriadV.Add(TIntTr(NId, 0, 0)); // zero triangles continue; } Nbrs = NbrV[NId]; NLen = Nbrs.Len(); // count connected neighbors int OpenCnt1 = 0, CloseCnt1 = 0; for (int srcNbr = 0; srcNbr < NLen; srcNbr++) { int Count = GetCommon(NbrV[NbrV[NId][srcNbr]],Nbrs); CloseCnt1 += Count; } CloseCnt1 /= 2; OpenCnt1 = (NLen*(NLen-1))/2 - CloseCnt1; NIdCOTriadV.Add(TIntTr(NId, CloseCnt1, OpenCnt1)); } } template <class PGraph> void GetTriads(const PGraph& Graph, std::vector<TUInt64Tr>& NIdCOTriadV, int64_t SampleNodes) { const bool IsDir = Graph->HasFlag(gfDirected); int64_t NNodes = Graph->GetNodes(); int64 hcount; hcount = 0; std::vector< int64_t> samples; int64_t nodesToProcess = NNodes; if (SampleNodes != -1) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution< int64_t> dis(0, NNodes); std::set< int64_t> set_samples; for( int64_t i = 0; i < SampleNodes; ) { int64_t id = dis(gen); if (!set_samples.count(id)) { set_samples.insert(id); samples.push_back(id); i++; } } nodesToProcess = samples.size(); } NIdCOTriadV.resize(nodesToProcess); std::vector< int64_t> Nbrs1; std::vector< int64_t> Nbrs2; for ( int64_t node = 0; node < nodesToProcess; node++) { typename PGraph::TObj::TNodeI NI; if (SampleNodes == -1) { NI = Graph->GetNI(node); } else { NI = Graph->GetNI(samples[node]); } hcount++; if (NI.GetDeg() < 2) { NIdCOTriadV[node] = TUInt64Tr(node, 0, 0); // zero triangles continue; } Nbrs1.clear(); GetUniqueNbrV(Graph, node, Nbrs1); // count connected neighbors int64_t OpenCnt1 = 0, CloseCnt1 = 0; for ( int64_t srcNbr = 0; srcNbr < Nbrs1.size(); srcNbr++) { Nbrs2.clear(); GetUniqueNbrV(Graph, Nbrs1[srcNbr], Nbrs2); int64_t Count = GetCommon(Nbrs2,Nbrs1); CloseCnt1 += Count; } CloseCnt1 /= 2; OpenCnt1 = (Nbrs1.size()*(Nbrs1.size()-1))/2 - CloseCnt1; NIdCOTriadV[node] = TUInt64Tr(node, CloseCnt1, OpenCnt1); } } template<class PGraph> int64 CountTriangles(const PGraph& Graph) { THash<TInt, TInt> H; TIntV MapV; int ind = 0; for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { H.AddDat(NI.GetId(), ind); MapV.Add(NI.GetId()); ind += 1; } TVec<TIntV> HigherDegNbrV(ind); #ifdef USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif for (int i = 0; i < ind; i++) { typename PGraph::TObj::TNodeI NI = Graph->GetNI(MapV[i]); TIntV NbrV; GetMergeSortedV<PGraph>(NbrV, NI); TIntV V; for (int j = 0; j < NbrV.Len(); j++) { TInt Vert = NbrV[j]; TInt Deg = Graph->GetNI(Vert).GetDeg(); if (Deg > NI.GetDeg() || (( int64_t)Deg == NI.GetDeg() && Vert > NI.GetId())) { V.Add(Vert); } } HigherDegNbrV[i] = V; } int64 cnt = 0; #ifdef USE_OPENMP #pragma omp parallel for schedule(dynamic) reduction(+:cnt) #endif for (int i = 0; i < HigherDegNbrV.Len(); i++) { for (int j = 0; j < HigherDegNbrV[i].Len(); j++) { TInt NbrInd = H.GetDat(HigherDegNbrV[i][j]); int64 num = GetCommon(HigherDegNbrV[i], HigherDegNbrV[NbrInd]); cnt += num; } } return cnt; } template<class PGraph> int64 GetTriangleCnt(const PGraph& Graph) { struct timeval start, end; struct timeval startall, endall; float delta; TTmProfiler Profiler; int TimerId = Profiler.AddTimer("Profiler"); int TimerAll = Profiler.AddTimer("ProfilerAll"); const int NNodes = Graph->GetNodes(); TIntV MapV(NNodes); TVec<typename PGraph::TObj::TNodeI> NV(NNodes); NV.Reduce(0); Profiler.ResetTimer(TimerAll); Profiler.StartTimer(TimerAll); gettimeofday(&startall, NULL); Profiler.ResetTimer(TimerId); Profiler.StartTimer(TimerId); gettimeofday(&start, NULL); int MxId = -1; int ind = 0; for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NV.Add(NI); int Id = NI.GetId(); if (Id > MxId) { MxId = Id; } MapV[ind] = Id; ind++; } TIntV IndV(MxId+1); for (int j = 0; j < NNodes; j++) { IndV[MapV[j]] = j; } gettimeofday(&end, NULL); Profiler.StopTimer(TimerId); delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; printf("__nodemap__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId)); Profiler.ResetTimer(TimerId); Profiler.StartTimer(TimerId); gettimeofday(&start, NULL); ind = MapV.Len(); Profiler.ResetTimer(TimerId); Profiler.StartTimer(TimerId); gettimeofday(&start, NULL); TVec<TIntV> HigherDegNbrV(ind); for (int i = 0; i < ind; i++) { HigherDegNbrV[i] = TVec<TInt>(); HigherDegNbrV[i].Reserve(NV[i].GetDeg()); HigherDegNbrV[i].Reduce(0); } gettimeofday(&end, NULL); Profiler.StopTimer(TimerId); delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; printf("__valloc__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId)); Profiler.ResetTimer(TimerId); Profiler.StartTimer(TimerId); gettimeofday(&start, NULL); #ifdef USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif for (int i = 0; i < ind; i++) { typename PGraph::TObj::TNodeI NI = NV[i]; //HigherDegNbrV[i] = TVec<TInt>(); //HigherDegNbrV[i].Reserve(NI.GetDeg()); //HigherDegNbrV[i].Reduce(0); MergeNbrs<PGraph>(HigherDegNbrV[i], NI); int k = 0; for (int j = 0; j < HigherDegNbrV[i].Len(); j++) { TInt Vert = HigherDegNbrV[i][j]; TInt Deg = NV[IndV[Vert]].GetDeg(); if (Deg > NI.GetDeg() || (Deg == NI.GetDeg() && Vert > NI.GetId())) { HigherDegNbrV[i][k] = Vert; k++; } } HigherDegNbrV[i].Reduce(k); } gettimeofday(&end, NULL); Profiler.StopTimer(TimerId); delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; printf("__sort__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId)); Profiler.ResetTimer(TimerId); Profiler.StartTimer(TimerId); gettimeofday(&start, NULL); int64 cnt = 0; #ifdef USE_OPENMP #pragma omp parallel for schedule(dynamic) reduction(+:cnt) #endif for (int i = 0; i < HigherDegNbrV.Len(); i++) { for (int j = 0; j < HigherDegNbrV[i].Len(); j++) { //TInt NbrInd = H.GetDat(HigherDegNbrV[i][j]); TInt NbrInd = IndV[HigherDegNbrV[i][j]]; int64 num = GetCommon(HigherDegNbrV[i], HigherDegNbrV[NbrInd]); cnt += num; } } gettimeofday(&end, NULL); Profiler.StopTimer(TimerId); delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; printf("__count__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId)); gettimeofday(&endall, NULL); Profiler.StopTimer(TimerAll); delta = ((endall.tv_sec - startall.tv_sec) * 1000000u + endall.tv_usec - startall.tv_usec) / 1.e6; printf("__all__ \ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerAll)); return cnt; } template<class PGraph> void MergeNbrs(TIntV& NeighbourV, const typename PGraph::TObj::TNodeI& NI) { int j = 0; int k = 0; int prev = -1; int indeg = NI.GetInDeg(); int outdeg = NI.GetOutDeg(); //while (j < NI.GetInDeg() && k < NI.GetOutDeg()) { if (indeg > 0 && outdeg > 0) { int v1 = NI.GetInNId(j); int v2 = NI.GetOutNId(k); while (1) { if (v1 <= v2) { if (prev != v1) { NeighbourV.Add(v1); prev = v1; } j += 1; if (j >= indeg) { break; } v1 = NI.GetInNId(j); } else { if (prev != v2) { NeighbourV.Add(v2); prev = v2; } k += 1; if (k >= outdeg) { break; } v2 = NI.GetOutNId(k); } } } while (j < indeg) { int v = NI.GetInNId(j); if (prev != v) { NeighbourV.Add(v); prev = v; } j += 1; } while (k < outdeg) { int v = NI.GetOutNId(k); if (prev != v) { NeighbourV.Add(v); prev = v; } k += 1; } } // Count the number of edges that participate in at least one triad template <class PGraph> int GetTriadEdges(const PGraph& Graph, int SampleEdges) { const bool IsDir = Graph->HasFlag(gfDirected); TIntSet NbrH; int TriadEdges = 0; for(typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NbrH.Clr(false); for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetOutNId(e) != NI.GetId()) { NbrH.AddKey(NI.GetOutNId(e)); } } if (IsDir) { for (int e = 0; e < NI.GetInDeg(); e++) { if (NI.GetInNId(e) != NI.GetId()) { NbrH.AddKey(NI.GetInNId(e)); } } } for (int e = 0; e < NI.GetOutDeg(); e++) { if (!IsDir && NI.GetId()<NI.GetOutNId(e)) { continue; } // for undirected graphs count each edge only once const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NI.GetOutNId(e)); bool Triad=false; for (int e1 = 0; e1 < SrcNode.GetOutDeg(); e1++) { if (NbrH.IsKey(SrcNode.GetOutNId(e1))) { Triad=true; break; } } if (IsDir && ! Triad) { for (int e1 = 0; e1 < SrcNode.GetInDeg(); e1++) { if (NbrH.IsKey(SrcNode.GetInNId(e1))) { Triad=true; break; } } } if (Triad) { TriadEdges++; } } } return TriadEdges; } // Returns number of undirected triads a node participates in template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId) { int ClosedTriads=0, OpenTriads=0; return GetNodeTriads(Graph, NId, ClosedTriads, OpenTriads); } // Return number of undirected triads a node participates in template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId, int& ClosedTriads, int& OpenTriads) { const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId); ClosedTriads=0; OpenTriads=0; if (NI.GetDeg() < 2) { return 0; } // find neighborhood TIntSet NbrSet(NI.GetDeg()); for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges NbrSet.AddKey(NI.GetOutNId(e)); } } if (Graph->HasFlag(gfDirected)) { for (int e = 0; e < NI.GetInDeg(); e++) { if (NI.GetInNId(e) != NI.GetId()) { // exclude self edges NbrSet.AddKey(NI.GetInNId(e)); } } } // count connected neighbors for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) { const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrSet.GetKey(srcNbr)); for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) { const int dstNId = NbrSet.GetKey(dstNbr); if (SrcNode.IsNbrNId(dstNId)) { ClosedTriads++; } else { OpenTriads++; } } } return ClosedTriads; } // Node NId and a subset of its neighbors GroupSet // InGroupEdges ... triads (NId, g1, g2), where g1 and g2 are in GroupSet // InOutGroupEdges ... triads (NId, g1, o1), where g1 in GroupSet and o1 not in GroupSet // OutGroupEdges ... triads (NId, o1, o2), where o1 and o2 are not in GroupSet template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId, const TIntSet& GroupSet, int& InGroupEdges, int& InOutGroupEdges, int& OutGroupEdges) { const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId); const bool IsDir = Graph->HasFlag(gfDirected); InGroupEdges=0; InOutGroupEdges=0; OutGroupEdges=0; if (NI.GetDeg() < 2) { return 0; } // find neighborhood TIntSet NbrSet(NI.GetDeg()); for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges NbrSet.AddKey(NI.GetOutNId(e)); } } if (IsDir) { for (int e = 0; e < NI.GetInDeg(); e++) { if (NI.GetInNId(e) != NI.GetId()) { NbrSet.AddKey(NI.GetInNId(e)); } } } // count connected neighbors for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) { const int NbrId = NbrSet.GetKey(srcNbr); const bool NbrIn = GroupSet.IsKey(NbrId); const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrId); for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) { const int DstNId = NbrSet.GetKey(dstNbr); if (SrcNode.IsNbrNId(DstNId)) { // triad (NId, NbrId, DstNid) bool DstIn = GroupSet.IsKey(DstNId); if (NbrIn && DstIn) { InGroupEdges++; } else if (NbrIn || DstIn) { InOutGroupEdges++; } else { OutGroupEdges++; } } } } return InGroupEdges; } // For each node count how many triangles it participates in template <class PGraph> void GetTriadParticip(const PGraph& Graph, TIntPrV& TriadCntV) { TIntH TriadCntH; for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { const int Triads = GetNodeTriads(Graph, NI.GetId()); TriadCntH.AddDat(Triads) += 1; } TriadCntH.GetKeyDatPrV(TriadCntV); TriadCntV.Sort(); } template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2) { TIntV NbrV; return GetCmnNbrs(Graph, NId1, NId2, NbrV); } // Get common neighbors between a pair of nodes (undirected) template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) { if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; } typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId1); typename PGraph::TObj::TNodeI NI2 = Graph->GetNI(NId2); NbrV.Clr(false); NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg())); TIntSet NSet1(NI1.GetDeg()), NSet2(NI2.GetDeg()); for (int i = 0; i < NI1.GetDeg(); i++) { const int nid = NI1.GetNbrNId(i); if (nid!=NId1 && nid!=NId2) { NSet1.AddKey(nid); } } for (int i = 0; i < NI2.GetDeg(); i++) { const int nid = NI2.GetNbrNId(i); if (NSet1.IsKey(nid)) { NSet2.AddKey(nid); } } NSet2.GetKeyV(NbrV); return NbrV.Len(); } template<> inline int GetCmnNbrs<PUNGraph>(const PUNGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) { if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; } const TUNGraph::TNodeI NI1 = Graph->GetNI(NId1); const TUNGraph::TNodeI NI2 = Graph->GetNI(NId2); int i=0, j=0; NbrV.Clr(false); NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg())); while (i < NI1.GetDeg() && j < NI2.GetDeg()) { const int nid = NI1.GetNbrNId(i); while (j < NI2.GetDeg() && NI2.GetNbrNId(j) < nid) { j++; } if (j < NI2.GetDeg() && nid==NI2.GetNbrNId(j) && nid!=NId1 && nid!=NId2) { IAssert(NbrV.Empty() || NbrV.Last() < nid); NbrV.Add(nid); j++; } i++; } return NbrV.Len(); } // get number of length 2 directed paths between a pair of nodes // for a pair of nodes (i,j): |{u: (i,u) and (u,j) }| template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2) { TIntV NbrV; return GetLen2Paths(Graph, NId1, NId2, NbrV); } // get number of length 2 directed paths between a pair of nodes // for a pair of nodes (i,j): {u: (i,u) and (u,j) } template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) { const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId1); NbrV.Clr(false); NbrV.Reserve(NI.GetOutDeg()); for (int e = 0; e < NI.GetOutDeg(); e++) { const typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(NI.GetOutNId(e)); if (MidNI.IsOutNId(NId2)) { NbrV.Add(MidNI.GetId()); } } return NbrV.Len(); } template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int& NId, TIntV& NbrV) { typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId); NbrV.Reserve(NI.GetDeg()); NbrV.Reduce(0); int j = 0; int k = 0; int Prev = -1; int InDeg = NI.GetInDeg(); int OutDeg = NI.GetOutDeg(); if (InDeg > 0 && OutDeg > 0) { int v1 = NI.GetInNId(j); int v2 = NI.GetOutNId(k); while (1) { if (v1 <= v2) { if (Prev != v1) { if (v1 != NId) { NbrV.Add(v1); Prev = v1; } } j += 1; if (j >= InDeg) { break; } v1 = NI.GetInNId(j); } else { if (Prev != v2) { if (v2 != NId) { NbrV.Add(v2); } Prev = v2; } k += 1; if (k >= OutDeg) { break; } v2 = NI.GetOutNId(k); } } } while (j < InDeg) { int v = NI.GetInNId(j); if (Prev != v) { if (v != NId) { NbrV.Add(v); } Prev = v; } j += 1; } while (k < OutDeg) { int v = NI.GetOutNId(k); if (Prev != v) { if (v != NId) { NbrV.Add(v); } Prev = v; } k += 1; } } template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int64_t& NId, std::vector< int64_t>& NbrV) { typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId); int64_t j = 0; int64_t k = 0; int64_t Prev = -1; int64_t InDeg = NI.GetInDeg(); int64_t OutDeg = NI.GetOutDeg(); if (InDeg > 0 && OutDeg > 0) { int64_t v1 = NI.GetInNId(j); int64_t v2 = NI.GetOutNId(k); while (1) { if (v1 <= v2) { if (Prev != v1) { if (v1 != NId) { NbrV.push_back(v1); Prev = v1; } } j += 1; if (j >= InDeg) { break; } v1 = NI.GetInNId(j); } else { if (Prev != v2) { if (v2 != NId) { NbrV.push_back(v2); } Prev = v2; } k += 1; if (k >= OutDeg) { break; } v2 = NI.GetOutNId(k); } } } while (j < InDeg) { int64_t v = NI.GetInNId(j); if (Prev != v) { if (v != NId) { NbrV.push_back(v); } Prev = v; } j += 1; } while (k < OutDeg) { int64_t v = NI.GetOutNId(k); if (Prev != v) { if (v != NId) { NbrV.push_back(v); } Prev = v; } k += 1; } } }; // mamespace TSnap ///////////////////////////////////////////////// // Node and Edge Network Constraint (by Ron Burt) // works for directed and undirected graphs (but not for multigraphs) template <class PGraph> class TNetConstraint { public: PGraph Graph; THash<TIntPr, TFlt> NodePrCH; // pairs of nodes that have non-zero network constraint public: TNetConstraint(const PGraph& GraphPt, const bool& CalcaAll=true); int Len() const { return NodePrCH.Len(); } double GetC(const int& ConstraintN) const { return NodePrCH[ConstraintN]; } TIntPr GetNodePr(const int& ConstraintN) const { return NodePrCH.GetKey(ConstraintN); } double GetEdgeC(const int& NId1, const int& NId2) const; double GetNodeC(const int& NId) const; void AddConstraint(const int& NId1, const int& NId2); void CalcConstraints(); void CalcConstraints(const int& NId); void Dump() const; static void Test(); }; template <class PGraph> TNetConstraint<PGraph>::TNetConstraint(const PGraph& GraphPt, const bool& CalcaAll) : Graph(GraphPt) { CAssert(! HasGraphFlag(typename PGraph::TObj, gfMultiGraph)); // must not be multigraph if (CalcaAll) { CalcConstraints(); } } template <class PGraph> double TNetConstraint<PGraph>::GetEdgeC(const int& NId1, const int& NId2) const { if (NodePrCH.IsKey(TIntPr(NId1, NId2))) { return NodePrCH.GetDat(TIntPr(NId1, NId2)); } else { return 0.0; } } template <class PGraph> double TNetConstraint<PGraph>::GetNodeC(const int& NId) const { typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId); if (NI1.GetOutDeg() == 0) { return 0.0; } int KeyId = -1; for (int k = 0; k<NI1.GetOutDeg(); k++) { KeyId = NodePrCH.GetKeyId(TIntPr(NI1.GetId(), NI1.GetOutNId(k))); if (KeyId > -1) { break; } } if (KeyId < 0) { return 0.0; } double Constraint = NodePrCH[KeyId]; for (int i = KeyId-1; i >-1 && NodePrCH.GetKey(i).Val1()==NId; i--) { Constraint += NodePrCH[i]; } for (int i = KeyId+1; i < NodePrCH.Len() && NodePrCH.GetKey(i).Val1()==NId; i++) { Constraint += NodePrCH[i]; } return Constraint; } template <class PGraph> void TNetConstraint<PGraph>::AddConstraint(const int& NId1, const int& NId2) { if (NId1==NId2 || NodePrCH.IsKey(TIntPr(NId1, NId2))) { return; } typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId1); double Constraint = 0.0; if (NI1.IsOutNId(NId2)) { // is direct edge Constraint += 1.0/(double) NI1.GetOutDeg(); } const double SrcC = 1.0/(double) NI1.GetOutDeg(); for (int e = 0; e < NI1.GetOutDeg(); e++) { const int MidNId = NI1.GetOutNId(e); if (MidNId == NId1 || MidNId == NId2) { continue; } const typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(MidNId); if (MidNI.IsOutNId(NId2)) { Constraint += SrcC * (1.0/(double)MidNI.GetOutDeg()); } } if (Constraint==0) { return; } Constraint = TMath::Sqr(Constraint); NodePrCH.AddDat(TIntPr(NId1, NId2), Constraint); } template <class PGraph> void TNetConstraint<PGraph>::CalcConstraints() { // add edges for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { AddConstraint(EI.GetSrcNId(), EI.GetDstNId()); AddConstraint(EI.GetDstNId(), EI.GetSrcNId()); } // add open triads for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { for (int i = 0; i < NI.GetDeg(); i++) { const int NId1 = NI.GetNbrNId(i); for (int j = 0; j < NI.GetDeg(); j++) { const int NId2 = NI.GetNbrNId(j); AddConstraint(NId1, NId2); } } } NodePrCH.SortByKey(); } // calculate constraints around a node id template <class PGraph> void TNetConstraint<PGraph>::CalcConstraints(const int& NId) { typename PGraph::TObj::TNodeI StartNI = Graph->GetNI(NId); TIntSet SeenSet; for (int e = 0; e < StartNI.GetOutDeg(); e++) { typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(StartNI.GetOutNId(e)); AddConstraint(NId, MidNI.GetId()); for (int i = 0; i < MidNI.GetOutDeg(); i++) { const int EndNId = MidNI.GetOutNId(i); if (! SeenSet.IsKey(EndNId)) { AddConstraint(NId, EndNId); SeenSet.AddKey(EndNId); } } } } template <class PGraph> void TNetConstraint<PGraph>::Dump() const { printf("Edge network constraint: (%d, %d)\n", Graph->GetNodes(), Graph->GetEdges()); for (int e = 0; e < NodePrCH.Len(); e++) { printf(" %4d %4d : %f\n", NodePrCH.GetKey(e).Val1(), NodePrCH.GetKey(e).Val2(), NodePrCH[e].Val); } printf("\n"); } // example from page 56 of Structural Holes by Ronald S. Burt // (http://www.amazon.com/Structural-Holes-Social-Structure-Competition/dp/0674843711) template <class PGraph> void TNetConstraint<PGraph>::Test() { PUNGraph G = TUNGraph::New(); G->AddNode(0); G->AddNode(1); G->AddNode(2); G->AddNode(3); G->AddNode(4); G->AddNode(5); G->AddNode(6); G->AddEdge(0,1); G->AddEdge(0,2); G->AddEdge(0,3); G->AddEdge(0,4); G->AddEdge(0,5); G->AddEdge(0,6); G->AddEdge(1,2); G->AddEdge(1,5); G->AddEdge(1,6); G->AddEdge(2,4); TNetConstraint<PUNGraph> NetConstraint(G, true); // NetConstraint.CalcConstraints(0); NetConstraint.Dump(); printf("middle node network constraint: %f\n", NetConstraint.GetNodeC(0)); } #endif // TRIAD_H
pi_program.c
#include <stdio.h> #include "omp.h" /* Basado en el tutorial: http://openmp.org/mp-documents/omp-hands-on-SC08.pdf */ void main (){ int i; double x, pi, step, sum = 0.0; int num_steps = 10000; step = 1.0/(double) num_steps; #pragma omp parallel for reduction ( + : sum ) for (i = 0 ; i < num_steps; i++){ x = i * step; sum = sum + 4.0/(1.0+x*x); } pi = step * sum; printf("Pi: %f\n",pi); }
rsky.c
/* This code computes the separation of centers between the occulting and occulted objects. It takes as arguments an array of times t, eccentricity e, semi-major axis a (in units of stellar radii), inclination angle i, stellar radius r_s, longitude of periastron w, orbital period P, time of periastron t0, and an error tolerance eps for computing the eccentric anomaly. LK 9/14/12 */ #include <Python.h> #include<numpy/arrayobject.h> #define TWOPI 6.28318531 #define PI 3.14159265 #define IND(a,i) *((double *)(a->data+i*a->strides[0])) static PyObject *rsky(PyObject *self, PyObject *args); double getE(double M, double e) //determines the eccentric anomaly (Seager Exoplanets book: Murray & Correia eqn. 5 -- see section 3) { double E = M, eps = 1.0e-7; while((E - e*sin(E) - M) > eps) { E = E - (E - e*sin(E) - M)/(1.0 - e*cos(E)); } return E; } static PyObject *rsky(PyObject *self, PyObject *args) { double e, E, i, a, r, r_s, d, f, w, P, M, n, t0, eps; int ii; npy_intp dims[1]; PyArrayObject *z, *t; if(!PyArg_ParseTuple(args,"ddddddddO", &e, &a, &i, &r_s, &w, &P, &t0, &eps, &t)) { return NULL; } dims[0] = t->dimensions[0]; z = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_DOUBLE); n = TWOPI/P; // mean motion #pragma omp parallel for private(M,E,r,f,d) for(ii = 0; ii < dims[0]; ii++) { // t = t0 + 0.005*P*(double)ii/(double)npoints; if(e > eps) { M = n*(IND(t,ii) - t0); E = getE(M, e); r = a*(1.0 - e*cos(E)); f = acos(a*(1.0 - e*e)/(r*e) - 1.0/e); } else f = ((IND(t, ii)-t0)/P - (int)((IND(t,ii)-t0)/P))*TWOPI; d = a*(1.0-e*e)/(1.0+e*cos(f))*sqrt(1.0 - sin(w+f)*sin(w+f)*sin(i)*sin(i)); IND(z, ii) = d/r_s; } return PyArray_Return(z); } static char module_docstring[] = "\ This code computes the distance between the centers of the\n\ star and the planet in the plane of the sky. This parameter is\n\ denoted r_sky = sqrt(x^2 + y^2) in the Seager Exoplanets book\n\ (see the section by Murray, and Winn eq. 5). In the Mandel & Agol (2002) paper,\n\ this quantity is denoted d.\n\ \n\ Revisions\n\ ---------\n\ Created: 2012-09-12 Laura Kreidberg \n\ Updated: 2018-11-22 Jonathan Fraine Updated for Python, with support for Python2.7\n\ "; static PyMethodDef module_methods[] = { {"rsky", rsky,METH_VARARGS,module_docstring},{NULL}}; PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_rsky(void) #else initrsky(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "rsky", /* m_name */ module_docstring, /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); if (!module) return NULL; /* Load `numpy` functionality. */ import_array(); return module; #else PyObject *m = Py_InitModule3("rsky", module_methods, module_docstring); if (m == NULL) return; /* Load `numpy` functionality. */ import_array(); #endif }
deviceptr-4.c
/* { dg-additional-options "-fdump-tree-gimple" } */ void subr (int *a) { #pragma acc data deviceptr (a) #pragma acc parallel a[0] += 1.0; } /* { dg-final { scan-tree-dump-times "#pragma omp target oacc_parallel.*map\\(tofrom:a" 1 "gimple" } } */
LAGraph_dense_relabel.c
//------------------------------------------------------------------------------ // LAGraph_dense_relabel: dense relabeling of ids to matrix indices //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. //------------------------------------------------------------------------------ // FIXME: this is not yet included in the test coverage suite // LAGraph_dense_relabel: relabel sparse IDs to dense row/column indices // Contributed by Marton Elekes and Gabor Szarnyas, // Budapest University of Technology and Economics // (with accented characters: M\'{a}rton Elekes and G\'{a}bor Sz\'{a}rnyas. // Converts array of sparse IDs (ids) to row/column indices between 0...(nids-1). // The order of IDs is kept, therefore ids can be used for index -> ID // conversion: ids[index]=id. // // Gives back two binary matrices for conversion between ID- and index-based // vertices. // id2index vector can be used to look up for indices of chosen IDs. // id_dimension gives back the height of Id2index matrix and id2index vector. // (Same as width of Index2id_handle matrix.) // id_dimension is the size that can store the largest ID in the array. // Currently it is the largest valid dimension in GraphBLAS // (GrB_INDEX_MAX+1) // // Find usage example in /Test/DenseRelabel/dense_relabel_test.c #define LAGraph_FREE_ALL \ { \ LAGraph_Free ((void **)&indices) ; \ LAGraph_Free ((void **)&true_values) ; \ } #include <string.h> // for memset #include <LAGraph.h> #include <LAGraphX.h> #include <LG_internal.h> // from src/utility // These should be freed by the calling code // GrB_free (Id2index_handle) ; \ // GrB_free (Index2id_handle) ; \ // GrB_free (id2index_handle) ; \ //------------------------------------------------------------------------------ GrB_Info LAGraph_dense_relabel // relabel sparse IDs to dense row/column indices ( GrB_Matrix *Id2index_handle, // output matrix: A(id, index)=1 (unfilled if NULL) GrB_Matrix *Index2id_handle, // output matrix: B(index, id)=1 (unfilled if NULL) GrB_Vector *id2index_handle, // output vector: v(id)=index (unfilled if NULL) const GrB_Index *ids, // array of unique identifiers (<= GrB_INDEX_MAX) GrB_Index nids, // number of identifiers GrB_Index *id_dimension // number of rows in Id2index matrix, id2index vector (unfilled if NULL) ) { GrB_Info info; // needed for LAGRAPH_OK GrB_Index *indices = NULL; bool *true_values = NULL; // from LAGraph_1_to_n.c int nthreads; LAGRAPH_OK (LAGraph_GetNumThreads(&nthreads, NULL)) ; nthreads = LAGraph_MIN ((int64_t) (nids / 4096), nthreads); nthreads = LAGraph_MAX (nthreads, 1); //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- if (!Id2index_handle && !Index2id_handle && !id2index_handle) { LAGRAPH_ERROR ("All output mapping arguments are NULL", GrB_NULL_POINTER); } if (!ids) { LAGRAPH_ERROR ("ids is NULL", GrB_NULL_POINTER); } // the largest valid dimension in GraphBLAS GrB_Index id_max_dimension = GrB_INDEX_MAX+1; if (id_dimension) *id_dimension = id_max_dimension; // set indices 0..(nids-1) indices = LAGraph_Malloc(nids, sizeof(*indices)); if (!indices) { LAGRAPH_ERROR ("Out of Memory", GrB_OUT_OF_MEMORY); } #pragma omp parallel for num_threads(nthreads) schedule(static) for (size_t i = 0; i < nids; ++i) { indices[i] = i; } // build vector id2index(original_id) = index if (id2index_handle) { LAGRAPH_OK (GrB_Vector_new(id2index_handle, GrB_UINT64, id_max_dimension)); LAGRAPH_OK (GrB_Vector_build(*id2index_handle, ids, indices, nids, GrB_SECOND_UINT64)); } if (Id2index_handle || Index2id_handle) { // initialize true values of the matrix true_values = LAGraph_Malloc(nids, sizeof(*true_values)); if (!true_values) { LAGRAPH_ERROR ("Out of Memory", GrB_OUT_OF_MEMORY); } memset(true_values, true, nids * sizeof(*true_values)); // build matrix Index2id(index, original_id) = 1 if (Index2id_handle) { LAGRAPH_OK (GrB_Matrix_new(Index2id_handle, GrB_BOOL, nids, id_max_dimension)); LAGRAPH_OK (GrB_Matrix_build(*Index2id_handle, indices, ids, true_values, nids, GrB_SECOND_UINT64)); } // build matrix Id2index(original_id, index) = 1 if (Id2index_handle) { LAGRAPH_OK (GrB_Matrix_new(Id2index_handle, GrB_BOOL, id_max_dimension, nids)); LAGRAPH_OK (GrB_Matrix_build(*Id2index_handle, ids, indices, true_values, nids, GrB_SECOND_UINT64)); } } LAGraph_FREE_ALL; return GrB_SUCCESS; }
struct.c
// RUN: %libomptarget-compile-generic -fopenmp-extensions // RUN: %libomptarget-run-generic | %fcheck-generic -strict-whitespace // amdgcn does not have printf definition // XFAIL: amdgcn-amd-amdhsa // XFAIL: amdgcn-amd-amdhsa-newRTL #include <omp.h> #include <stdio.h> #define CHECK_PRESENCE(Var1, Var2, Var3) \ printf(" presence of %s, %s, %s: %d, %d, %d\n", \ #Var1, #Var2, #Var3, \ omp_target_is_present(&(Var1), omp_get_default_device()), \ omp_target_is_present(&(Var2), omp_get_default_device()), \ omp_target_is_present(&(Var3), omp_get_default_device())) #define CHECK_VALUES(Var1, Var2) \ printf(" values of %s, %s: %d, %d\n", \ #Var1, #Var2, (Var1), (Var2)) int main() { struct S { int i; int j; } s; // CHECK: presence of s, s.i, s.j: 0, 0, 0 CHECK_PRESENCE(s, s.i, s.j); // ======================================================================= // Check that ompx_hold keeps entire struct present. // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} printf("check: ompx_hold only on first member\n"); s.i = 20; s.j = 30; #pragma omp target data map(tofrom: s) map(ompx_hold,tofrom: s.i) \ map(tofrom: s.j) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(tofrom: s) { s.i = 21; s.j = 31; } #pragma omp target exit data map(delete: s, s.i) // ompx_hold on s.i applies to all of s. // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} printf("check: ompx_hold only on last member\n"); s.i = 20; s.j = 30; #pragma omp target data map(tofrom: s) map(tofrom: s.i) \ map(ompx_hold,tofrom: s.j) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(tofrom: s) { s.i = 21; s.j = 31; } #pragma omp target exit data map(delete: s, s.i) // ompx_hold on s.j applies to all of s. // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} printf("check: ompx_hold only on struct\n"); s.i = 20; s.j = 30; #pragma omp target data map(ompx_hold,tofrom: s) map(tofrom: s.i) \ map(tofrom: s.j) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(tofrom: s) { s.i = 21; s.j = 31; } #pragma omp target exit data map(delete: s, s.i) // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); // ======================================================================= // Check that transfer to/from host checks reference count correctly. // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} printf("check: parent DynRefCount=1 is not sufficient for transfer\n"); s.i = 20; s.j = 30; #pragma omp target data map(ompx_hold, tofrom: s) #pragma omp target data map(ompx_hold, tofrom: s) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(from: s.i, s.j) { s.i = 21; s.j = 31; } // No transfer here even though parent's DynRefCount=1. // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); #pragma omp target map(to: s.i, s.j) { // No transfer here even though parent's DynRefCount=1. // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_VALUES(s.i, s.j); } } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} printf("check: parent HoldRefCount=1 is not sufficient for transfer\n"); s.i = 20; s.j = 30; #pragma omp target data map(tofrom: s) #pragma omp target data map(tofrom: s) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(ompx_hold, from: s.i, s.j) { s.i = 21; s.j = 31; } // No transfer here even though parent's HoldRefCount=1. // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); #pragma omp target map(ompx_hold, to: s.i, s.j) { // No transfer here even though parent's HoldRefCount=1. // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_VALUES(s.i, s.j); } } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); // ----------------------------------------------------------------------- // CHECK-LABEL: check:{{.*}} // // At the beginning of a region, if the parent's TotalRefCount=1, then the // transfer should happen. // // At the end of a region, it also must be true that the reference count being // decremented is the reference count that is 1. printf("check: parent TotalRefCount=1 is not sufficient for transfer\n"); s.i = 20; s.j = 30; #pragma omp target data map(ompx_hold, tofrom: s) { // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 CHECK_PRESENCE(s, s.i, s.j); #pragma omp target map(ompx_hold, tofrom: s.i, s.j) { s.i = 21; s.j = 31; } #pragma omp target exit data map(from: s.i, s.j) // No transfer here even though parent's TotalRefCount=1. // CHECK-NEXT: presence of s, s.i, s.j: 1, 1, 1 // CHECK-NEXT: values of s.i, s.j: 20, 30 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); } // CHECK-NEXT: presence of s, s.i, s.j: 0, 0, 0 // CHECK-NEXT: values of s.i, s.j: 21, 31 CHECK_PRESENCE(s, s.i, s.j); CHECK_VALUES(s.i, s.j); return 0; }
GB_unop__ainv_uint32_uint32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__ainv_uint32_uint32) // op(A') function: GB (_unop_tran__ainv_uint32_uint32) // C type: uint32_t // A type: uint32_t // cast: uint32_t cij = aij // unaryop: cij = -aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CAST(z, aij) \ uint32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = aij ; \ Cx [pC] = -z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_uint32_uint32) ( uint32_t *Cx, // Cx and Ax may be aliased const uint32_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++) { uint32_t aij = Ax [p] ; uint32_t z = aij ; Cx [p] = -z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint32_t aij = Ax [p] ; uint32_t z = aij ; Cx [p] = -z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_uint32_uint32) ( 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
finalize-1.c
/* Test valid usage and processing of the finalize clause. */ /* { dg-additional-options "-fdump-tree-original -fdump-tree-gimple" } */ extern int del_r; extern float del_f[3]; extern char *del_f_p; extern double cpo_r[8]; extern long cpo_f; extern char *cpo_f_p; void f () { #pragma acc exit data delete (del_r) /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data map\\(release:del_r\\);$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data map\\(release:del_r \\\[len: \[0-9\]+\\\]\\)$" 1 "gimple" } } */ #pragma acc exit data finalize delete (del_f) /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data map\\(release:del_f\\) finalize;$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data map\\(delete:del_f \\\[len: \[0-9\]+\\\]\\) finalize$" 1 "gimple" } } */ #pragma acc exit data finalize delete (del_f_p[2:5]) /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data map\\(release:\\*\\(del_f_p \\+ 2\\) \\\[len: 5\\\]\\) map\\(firstprivate:del_f_p \\\[pointer assign, bias: 2\\\]\\) finalize;$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data map\\(delete:\[^ \]+ \\\[len: 5\\\]\\) finalize$" 1 "gimple" } } */ #pragma acc exit data copyout (cpo_r) /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data map\\(from:cpo_r\\);$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data map\\(from:cpo_r \\\[len: \[0-9\]+\\\]\\)$" 1 "gimple" } } */ #pragma acc exit data copyout (cpo_f) finalize /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data finalize map\\(from:cpo_f\\);$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data finalize map\\(force_from:cpo_f \\\[len: \[0-9\]+\\\]\\)$" 1 "gimple" } } */ #pragma acc exit data copyout (cpo_f_p[4:10]) finalize /* { dg-final { scan-tree-dump-times "(?n)#pragma acc exit data finalize map\\(from:\\*\\(cpo_f_p \\+ 4\\) \\\[len: 10\\\]\\) map\\(firstprivate:cpo_f_p \\\[pointer assign, bias: 4\\\]\\);$" 1 "original" } } { dg-final { scan-tree-dump-times "(?n)#pragma omp target oacc_enter_exit_data finalize map\\(force_from:\[^ \]+ \\\[len: 10\\\]\\)$" 1 "gimple" } } */ }
bigfile.c
#define _POSIX_C_SOURCE 200809L // FIXME: scandir needs this #include <stdio.h> #include <stdlib.h> #include <string.h> #include <alloca.h> #include <stdint.h> #include <stddef.h> #include <limits.h> #include <stdarg.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <dirent.h> #include "bigfile.h" #include "bigfile-internal.h" #define EXT_HEADER "header" #define EXT_ATTR "attr" #define EXT_ATTR_V2 "attr-v2" #define EXT_DATA "%06X" #define FILEID_ATTR -2 #define FILEID_ATTR_V2 -3 #define FILEID_HEADER -1 #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) #include <stdatomic.h> static char * volatile _Atomic ERRORSTR = NULL; #else static char * volatile ERRORSTR = NULL; #endif static size_t CHUNK_BYTES = 64 * 1024 * 1024; /* Internal AttrSet API */ struct BigAttrSet { /* All members are readonly */ int dirty; char * attrbuf; size_t bufused; size_t bufsize; BigAttr * attrlist; size_t listused; size_t listsize; }; static BigAttrSet * attrset_create(void); static void attrset_free(BigAttrSet * attrset); static int attrset_read_attr_set_v1(BigAttrSet * attrset, const char * basename); static int attrset_read_attr_set_v2(BigAttrSet * attrset, const char * basename); static int attrset_write_attr_set_v2(BigAttrSet * attrset, const char * basename); static BigAttr * attrset_lookup_attr(BigAttrSet * attrset, const char * attrname); static int attrset_remove_attr(BigAttrSet * attrset, const char * attrname); static BigAttr * attrset_list_attrs(BigAttrSet * attrset, size_t * count); static int attrset_set_attr(BigAttrSet * attrset, const char * attrname, const void * data, const char * dtype, int nmemb); static int attrset_get_attr(BigAttrSet * attrset, const char * attrname, void * data, const char * dtype, int nmemb); /* Internal dtype API */ static int dtype_convert_simple(void * dst, const char * dstdtype, const void * src, const char * srcdtype, size_t nmemb); /*Check dtype is valid*/ static int dtype_isvalid(const char * dtype); /* postfix detection, 1 if postfix is a postfix of str */ static int endswith(const char * str, const char * postfix) { const char * p = str + strlen(str) - 1; const char * q = postfix + strlen(postfix) - 1; for(; p >= str && q >= postfix; p --, q--) { if(*p != *q) return 0; } return 1; } /* global settings */ int big_file_set_buffer_size(size_t bytes) { CHUNK_BYTES = bytes; return 0; } /* Error handling */ char * big_file_get_error_message() { return ERRORSTR; } void big_file_set_error_message(char * msg) { char * errorstr; if(msg != NULL) msg = _strdup(msg); #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) errorstr = atomic_exchange(&ERRORSTR, msg); #elif defined(__ATOMIC_SEQ_CST) errorstr = __atomic_exchange_n(&ERRORSTR, msg, __ATOMIC_SEQ_CST); #elif _OPENMP >= 201307 /* openmp 4.0 supports swap capture*/ #pragma omp capture { errorstr = ERRORSTR; ERRORSTR = msg; } #else errorstr = ERRORSTR; ERRORSTR = msg; /* really should have propagated errors over the stack! */ #warning "enable -std=c11 or -std=gnu11, or luse gcc for thread friendly error handling" #endif if(errorstr) free(errorstr); } static char * _path_join(const char * part1, const char * part2) { size_t l1 = part1?strlen(part1):0; size_t l2 = strlen(part2); char * result = malloc(l1 + l2 + 10); if(l1 == 0) { sprintf(result, "%s", part2); } else if(part1[l1 - 1] == '/') { sprintf(result, "%s%s", part1, part2); } else { sprintf(result, "%s/%s", part1, part2); } return result; } static int _big_file_path_is_block(const char * basename) { FILE * fheader = _big_file_open_a_file(basename, FILEID_HEADER, "r", 0); if(fheader == NULL) { return 0; } fclose(fheader); return 1; } void _big_file_raise(const char * msg, const char * file, const int line, ...) { if(!msg) { if(ERRORSTR) { msg = ERRORSTR; } else { msg = "UNKNOWN ERROR"; } } size_t len = strlen(msg) + strlen(file) + 512; char * errorstr = malloc(len); char * fmtstr = alloca(len); sprintf(fmtstr, "%s @(%s:%d)", msg, file, line); va_list va; va_start(va, line); vsprintf(errorstr, fmtstr, va); va_end(va); big_file_set_error_message(errorstr); free(errorstr); } /* BigFile */ int big_file_open(BigFile * bf, const char * basename) { struct stat st; RAISEIF(0 != stat(basename, &st), ex_stat, "Big File `%s' does not exist (%s)", basename, strerror(errno)); bf->basename = _strdup(basename); return 0; ex_stat: return -1; } int big_file_create(BigFile * bf, const char * basename) { bf->basename = _strdup(basename); RAISEIF(0 != _big_file_mksubdir_r(NULL, basename), ex_subdir, NULL); return 0; ex_subdir: return -1; } struct bblist { struct bblist * next; char * blockname; }; static int (filter)(const struct dirent * ent) { if(ent->d_name[0] == '.') return 0; return 1; } /* taken from glibc not always there. e.g. with c99. */ static int _alphasort (const struct dirent **a, const struct dirent **b) { return strcoll ((*a)->d_name, (*b)->d_name); } static struct bblist * listbigfile_r(const char * basename, char * blockname, struct bblist * bblist) { struct dirent **namelist; int n; int i; char * current; current = _path_join(basename, blockname); n = scandir(current, &namelist, filter, _alphasort); free(current); if (n < 0) return bblist; for(i = 0; i < n ; i ++) { char * blockname1 = _path_join(blockname, namelist[i]->d_name); char * fullpath1 = _path_join(basename, blockname1); if(_big_file_path_is_block(fullpath1)) { struct bblist * n = malloc(sizeof(struct bblist) + strlen(blockname1) + 1); n->next = bblist; n->blockname = (char*) &n[1]; strcpy(n->blockname, blockname1); bblist = n; } else { bblist = listbigfile_r(basename, blockname1, bblist); } free(fullpath1); free(blockname1); free(namelist[i]); } free(namelist); return bblist; } int big_file_list(BigFile * bf, char *** blocknames, int * Nblocks) { struct bblist * bblist = listbigfile_r(bf->basename, "", NULL); struct bblist * p; int N = 0; int i; for(p = bblist; p; p = p->next) { N ++; } *Nblocks = N; *blocknames = malloc(sizeof(char*) * N); for(i = 0; i < N; i ++) { (*blocknames)[i] = _strdup(bblist->blockname); p = bblist; bblist = bblist->next; free(p); } return 0; } int big_file_open_block(BigFile * bf, BigBlock * block, const char * blockname) { char * basename = _path_join(bf->basename, blockname); int rt = _big_block_open(block, basename); free(basename); return rt; } int big_file_create_block(BigFile * bf, BigBlock * block, const char * blockname, const char * dtype, int nmemb, int Nfile, const size_t fsize[]) { RAISEIF(0 != _big_file_mksubdir_r(bf->basename, blockname), ex_subdir, NULL); char * basename = _path_join(bf->basename, blockname); int rt = _big_block_create(block, basename, dtype, nmemb, Nfile, fsize); free(basename); return rt; ex_subdir: return -1; } int big_file_close(BigFile * bf) { free(bf->basename); bf->basename = NULL; return 0; } static void sysvsum(unsigned int * sum, void * buf, size_t size); /* Bigblock */ int _big_block_open(BigBlock * bb, const char * basename) { memset(bb, 0, sizeof(bb[0])); if(basename == NULL) basename = "/."; bb->basename = _strdup(basename); bb->dirty = 0; bb->attrset = attrset_create(); /* COMPATIBLE WITH V1 ATTR FILES */ RAISEIF(0 != attrset_read_attr_set_v1(bb->attrset, bb->basename), ex_readattr, NULL); RAISEIF(0 != attrset_read_attr_set_v2(bb->attrset, bb->basename), ex_readattr, NULL); if (!endswith(bb->basename, "/.") && 0 != strcmp(bb->basename, ".")) { FILE * fheader = _big_file_open_a_file(bb->basename, FILEID_HEADER, "r", 1); RAISEIF (!fheader, ex_open, NULL); RAISEIF( (1 != fscanf(fheader, " DTYPE: %s", bb->dtype)) || (1 != fscanf(fheader, " NMEMB: %d", &(bb->nmemb))) || (1 != fscanf(fheader, " NFILE: %d", &(bb->Nfile))), ex_fscanf, "Failed to read header of block `%s' (%s)", bb->basename, strerror(errno)); RAISEIF(bb->Nfile < 0 || bb->Nfile >= INT_MAX-1, ex_fscanf, "Unreasonable value for Nfile in header of block `%s' (%d)",bb->basename,bb->Nfile); RAISEIF(bb->nmemb < 0, ex_fscanf, "Unreasonable value for nmemb in header of block `%s' (%d)",bb->basename,bb->nmemb); RAISEIF(!dtype_isvalid(bb->dtype), ex_fscanf, "Unreasonable value for dtype in header of block `%s' (%s)",bb->basename,bb->dtype); bb->fsize = calloc(bb->Nfile + 1, sizeof(size_t)); RAISEIF(!bb->fsize, ex_fsize, "Failed to alloc memory of block `%s'", bb->basename); bb->foffset = calloc(bb->Nfile + 1, sizeof(size_t)); RAISEIF(!bb->foffset, ex_foffset, "Failed to alloc memory of block `%s'", bb->basename); bb->fchecksum = calloc(bb->Nfile + 1, sizeof(int)); RAISEIF(!bb->fchecksum, ex_fchecksum, "Failed to alloc memory `%s'", bb->basename); int i; for(i = 0; i < bb->Nfile; i ++) { int fid; size_t size; unsigned int cksum; unsigned int sysv; RAISEIF(4 != fscanf(fheader, " " EXT_DATA ": %td : %u : %u", &fid, &size, &cksum, &sysv), ex_fscanf1, "Failed to readin physical file layout `%s' %d (%s)", bb->basename, fid, strerror(errno)); RAISEIF(fid < 0 || fid >= bb->Nfile, ex_fscanf1, "Non-existent file referenced: `%s' (%d)", bb->basename, fid); bb->fsize[fid] = size; bb->fchecksum[fid] = cksum; } bb->foffset[0] = 0; for(i = 0; i < bb->Nfile; i ++) { bb->foffset[i + 1] = bb->foffset[i] + bb->fsize[i]; } bb->size = bb->foffset[bb->Nfile]; fclose(fheader); return 0; ex_fscanf1: free(bb->fchecksum); ex_fchecksum: free(bb->foffset); ex_foffset: free(bb->fsize); ex_fsize: ex_fscanf: fclose(fheader); ex_open: return -1; } else { /* The meta block of a big file, has on extra files. */ bb->Nfile = 0; strcpy(bb->dtype, "####"); return 0; } ex_readattr: return -1; } int _big_block_grow_internal(BigBlock * bb, int Nfile_grow, const size_t fsize_grow[]) { int Nfile = Nfile_grow + bb->Nfile; size_t * fsize = calloc(Nfile + 1, sizeof(size_t)); size_t * foffset = calloc(Nfile + 1, sizeof(size_t)); unsigned int * fchecksum = calloc(Nfile + 1, sizeof(unsigned int)); int i; for(i = 0; i < bb->Nfile; i ++) { fsize[i] = bb->fsize[i]; fchecksum[i] = bb->fchecksum[i]; } for(i = bb->Nfile; i < Nfile; i ++) { fsize[i] = fsize_grow[i - bb->Nfile]; fchecksum[i] = 0; } foffset[0] = 0; for(i = 0; i < Nfile; i ++) { foffset[i + 1] = foffset[i] + fsize[i]; } free(bb->fsize); free(bb->foffset); free(bb->fchecksum); bb->fsize = fsize; bb->foffset = foffset; bb->fchecksum = fchecksum; bb->Nfile = Nfile; bb->size = bb->foffset[Nfile]; bb->dirty = 1; return 0; } int big_block_grow(BigBlock * bb, int Nfile_grow, const size_t fsize_grow[]) { int oldNfile = bb->Nfile; _big_block_grow_internal(bb, Nfile_grow, fsize_grow); int i; /* now truncate the new files */ for(i = oldNfile; i < bb->Nfile; i ++) { FILE * fp = _big_file_open_a_file(bb->basename, i, "w", 1); RAISEIF(fp == NULL, ex_fileio, NULL); fclose(fp); } return 0; ex_fileio: return -1; } int _big_block_create_internal(BigBlock * bb, const char * basename, const char * dtype, int nmemb, int Nfile, const size_t fsize[]) { memset(bb, 0, sizeof(bb[0])); if(basename == NULL) basename = "/."; RAISEIF ( strchr(basename, ' ') || strchr(basename, '\t') || strchr(basename, '\n'), ex_name, "Column name cannot contain blanks (space, tab or newline)" ); bb->basename = _strdup(basename); bb->attrset = attrset_create(); bb->attrset->dirty = 1; if (!endswith(bb->basename, "/.") && 0 != strcmp(bb->basename, ".")) { if(dtype == NULL) { dtype = "i8"; Nfile = 0; fsize = NULL; } /* always use normalized dtype in files. */ _dtype_normalize(bb->dtype, dtype); bb->Nfile = Nfile; bb->nmemb = nmemb; bb->fsize = calloc(bb->Nfile + 1, sizeof(size_t)); RAISEIF(!bb->fsize, ex_fsize, "No memory"); bb->fchecksum = calloc(bb->Nfile + 1, sizeof(int)); RAISEIF(!bb->fchecksum, ex_fchecksum, "No memory"); bb->foffset = calloc(bb->Nfile + 1, sizeof(size_t)); RAISEIF(!bb->foffset, ex_foffset, "No memory"); int i; bb->foffset[0] = 0; for(i = 0; i < bb->Nfile; i ++) { bb->fsize[i] = fsize[i]; bb->foffset[i + 1] = bb->foffset[i] + bb->fsize[i]; bb->fchecksum[i] = 0; } bb->size = bb->foffset[bb->Nfile]; bb->dirty = 1; RAISEIF(0 != big_block_flush(bb), ex_flush, NULL); bb->dirty = 0; return 0; ex_flush: attrset_free(bb->attrset); free(bb->foffset); ex_foffset: free(bb->fchecksum); ex_fchecksum: free(bb->fsize); ex_fsize: return -1; } else { /* special meta block of a file */ bb->Nfile = 0; /* never flush the header */ bb->dirty = 0; RAISEIF(0 != big_block_flush(bb), ex_flush2, NULL); bb->dirty = 0; return 0; ex_flush2: attrset_free(bb->attrset); return -1; } ex_name: return -1; } int _big_block_create(BigBlock * bb, const char * basename, const char * dtype, int nmemb, int Nfile, const size_t fsize[]) { int rt = _big_block_create_internal(bb, basename, dtype, nmemb, Nfile, fsize); int i; RAISEIF(rt != 0, ex_internal, NULL); /* now truncate all files */ for(i = 0; i < bb->Nfile; i ++) { FILE * fp = _big_file_open_a_file(bb->basename, i, "w", 1); RAISEIF(fp == NULL, ex_fileio, NULL); fclose(fp); } ex_internal: return rt; ex_fileio: _big_block_close_internal(bb); return -1; } void big_block_set_dirty(BigBlock * block, int value) { block->dirty = value; } int big_block_flush(BigBlock * block) { FILE * fheader = NULL; if(block->dirty) { int i; fheader = _big_file_open_a_file(block->basename, FILEID_HEADER, "w+", 1); RAISEIF(fheader == NULL, ex_fileio, NULL); RAISEIF( (0 > fprintf(fheader, "DTYPE: %s\n", block->dtype)) || (0 > fprintf(fheader, "NMEMB: %d\n", block->nmemb)) || (0 > fprintf(fheader, "NFILE: %d\n", block->Nfile)), ex_fprintf, "Writing file header"); for(i = 0; i < block->Nfile; i ++) { unsigned int s = block->fchecksum[i]; unsigned int r = (s & 0xffff) + ((s & 0xffffffff) >> 16); unsigned int checksum = (r & 0xffff) + (r >> 16); RAISEIF(0 > fprintf(fheader, EXT_DATA ": %td : %u : %u\n", i, block->fsize[i], block->fchecksum[i], checksum), ex_fprintf, "Writing file information to header"); } fclose(fheader); block->dirty = 0; } if(block->attrset->dirty) { RAISEIF(0 != attrset_write_attr_set_v2(block->attrset, block->basename), ex_write_attr, NULL); block->attrset->dirty = 0; } return 0; ex_fprintf: fclose(fheader); ex_write_attr: ex_fileio: return -1; } void _big_block_close_internal(BigBlock * block) { attrset_free(block->attrset); free(block->basename); free(block->fchecksum); free(block->fsize); free(block->foffset); memset(block, 0, sizeof(BigBlock)); } int big_block_close(BigBlock * block) { int rt = 0; RAISEIF(0 != big_block_flush(block), ex_flush, NULL); finalize: _big_block_close_internal(block); return rt; ex_flush: rt = -1; goto finalize; } BigAttr * big_block_lookup_attr(BigBlock * block, const char * attrname) { BigAttr * attr = attrset_lookup_attr(block->attrset, attrname); return attr; } int big_block_remove_attr(BigBlock * block, const char * attrname) { return attrset_remove_attr(block->attrset, attrname); } BigAttr * big_block_list_attrs(BigBlock * block, size_t * count) { return attrset_list_attrs(block->attrset, count); } int big_block_set_attr(BigBlock * block, const char * attrname, const void * data, const char * dtype, int nmemb) { return attrset_set_attr(block->attrset, attrname, data, dtype, nmemb); } int big_block_get_attr(BigBlock * block, const char * attrname, void * data, const char * dtype, int nmemb) { return attrset_get_attr(block->attrset, attrname, data, dtype, nmemb); } /* * * seek ptr to offset, on bb * * offset: 0 : Start * -1 : End * -2 : End - 1 * * returns 0 * * 0 4 5 10 140 * */ int big_block_seek(BigBlock * bb, BigBlockPtr * ptr, ptrdiff_t offset) { /* handle 0 sized files */ if(bb->size == 0 && offset == 0) { ptr->fileid = 0; ptr->roffset = 0; ptr->aoffset = 0; return 0; } /* handle negatives */ if(offset < 0) offset += bb->foffset[bb->Nfile]; RAISEIF(offset > bb->size, ex_eof, /* over the end of file */ /* note that we allow seeking at the end of file */ "Over the end of file %td of %td", offset, bb->size); { int left = 0; int right = bb->Nfile; while(right > left + 1) { int mid = ((right - left) >> 1) + left; if(bb->foffset[mid] <= offset) { left = mid; } else { right = mid; } } ptr->fileid = left; ptr->roffset = offset - bb->foffset[left]; ptr->aoffset = offset; return 0; } ex_eof: return -1; } int big_block_seek_rel(BigBlock * bb, BigBlockPtr * ptr, ptrdiff_t rel) { ptrdiff_t abs = bb->foffset[ptr->fileid] + ptr->roffset + rel; return big_block_seek(bb, ptr, abs); } int big_block_eof(BigBlock * bb, BigBlockPtr * ptr) { ptrdiff_t abs = bb->foffset[ptr->fileid] + ptr->roffset; return abs >= bb->size; } /* * this function will alloc memory in array and read from offset start * size of rows from the block. * free(array->data) after using it. * * at most size rows are read, array.dims[0] has the number that's read. * * if dtype is NULL use the dtype of the block. * otherwise cast the array to the dtype * */ int big_block_read_simple(BigBlock * bb, ptrdiff_t start, ptrdiff_t size, BigArray * array, const char * dtype) { BigBlockPtr ptr = {0}; if(dtype == NULL) { dtype = bb->dtype; } void * buffer; size_t dims[2]; RAISEIF(0 != big_block_seek(bb, &ptr, start), ex_seek, "failed to seek" ); if(start + size > bb->size){ size = bb->size - start; } RAISEIF(size < 0, ex_seek, "failed to seek"); buffer = malloc(size * big_file_dtype_itemsize(dtype) * bb->nmemb); dims[0] = size; dims[1] = bb->nmemb; big_array_init(array, buffer, dtype, 2, dims, NULL); RAISEIF(0 != big_block_read(bb, &ptr, array), ex_read, "failed to read"); return 0; ex_read: free(buffer); array->data = NULL; ex_seek: return -1; } int big_block_read(BigBlock * bb, BigBlockPtr * ptr, BigArray * array) { char * chunkbuf = malloc(CHUNK_BYTES); int nmemb = bb->nmemb ? bb->nmemb : 1; int felsize = big_file_dtype_itemsize(bb->dtype) * nmemb; size_t CHUNK_SIZE = CHUNK_BYTES / felsize; BigArray chunk_array = {0}; size_t dims[2]; dims[0] = CHUNK_SIZE; dims[1] = bb->nmemb; BigArrayIter chunk_iter; BigArrayIter array_iter; FILE * fp = NULL; ptrdiff_t toread = 0; RAISEIF(chunkbuf == NULL, ex_malloc, "Not enough memory for chunkbuf"); big_array_init(&chunk_array, chunkbuf, bb->dtype, 2, dims, NULL); big_array_iter_init(&array_iter, array); toread = array->size / nmemb; ptrdiff_t abs = bb->foffset[ptr->fileid] + ptr->roffset + toread; RAISEIF(abs > bb->size, ex_eof, "Reading beyond the block `%s` at (%d:%td)", bb->basename, ptr->fileid, ptr->roffset * felsize); while(toread > 0 && ! big_block_eof(bb, ptr)) { size_t chunk_size = CHUNK_SIZE; /* remaining items in the file */ if(chunk_size > bb->fsize[ptr->fileid] - ptr->roffset) { chunk_size = bb->fsize[ptr->fileid] - ptr->roffset; } /* remaining items to read */ if(chunk_size > toread) { chunk_size = toread; } RAISEIF(chunk_size == 0, ex_insuf, "Insufficient number of items in file `%s' at (%d:%td)", bb->basename, ptr->fileid, ptr->roffset * felsize); /* read to the beginning of chunk */ big_array_iter_init(&chunk_iter, &chunk_array); fp = _big_file_open_a_file(bb->basename, ptr->fileid, "r", 1); RAISEIF(fp == NULL, ex_open, NULL); RAISEIF(0 > fseek(fp, ptr->roffset * felsize, SEEK_SET), ex_seek, "Failed to seek in block `%s' at (%d:%td) (%s)", bb->basename, ptr->fileid, ptr->roffset * felsize, strerror(errno)); RAISEIF(chunk_size != fread(chunkbuf, felsize, chunk_size, fp), ex_read, "Failed to read in block `%s' at (%d:%td) (%s)", bb->basename, ptr->fileid, ptr->roffset * felsize, strerror(errno)); fclose(fp); fp = NULL; /* now translate the data from chunkbuf to mptr */ RAISEIF(0 != _dtype_convert(&array_iter, &chunk_iter, chunk_size * bb->nmemb), ex_convert, NULL); toread -= chunk_size; RAISEIF(0 != big_block_seek_rel(bb, ptr, chunk_size), ex_blockseek, NULL); } free(chunkbuf); return 0; ex_read: ex_seek: fclose(fp); ex_insuf: ex_convert: ex_blockseek: ex_open: ex_eof: free(chunkbuf); ex_malloc: return -1; } int big_block_write(BigBlock * bb, BigBlockPtr * ptr, BigArray * array) { if(array->size == 0) return 0; /* the file header is modified */ bb->dirty = 1; char * chunkbuf = malloc(CHUNK_BYTES); int nmemb = bb->nmemb ? bb->nmemb : 1; int felsize = big_file_dtype_itemsize(bb->dtype) * nmemb; size_t CHUNK_SIZE = CHUNK_BYTES / felsize; BigArray chunk_array = {0}; size_t dims[2]; dims[0] = CHUNK_SIZE; dims[1] = bb->nmemb; BigArrayIter chunk_iter; BigArrayIter array_iter; ptrdiff_t towrite = 0; FILE * fp; RAISEIF(chunkbuf == NULL, ex_malloc, "not enough memory for chunkbuf of size %d bytes", CHUNK_BYTES); big_array_init(&chunk_array, chunkbuf, bb->dtype, 2, dims, NULL); big_array_iter_init(&array_iter, array); towrite = array->size / nmemb; ptrdiff_t abs = bb->foffset[ptr->fileid] + ptr->roffset + towrite; RAISEIF(abs > bb->size, ex_eof, "Writing beyond the block `%s` at (%d:%td)", bb->basename, ptr->fileid, ptr->roffset * felsize); while(towrite > 0 && ! big_block_eof(bb, ptr)) { size_t chunk_size = CHUNK_SIZE; /* remaining items in the file */ if(chunk_size > bb->fsize[ptr->fileid] - ptr->roffset) { chunk_size = bb->fsize[ptr->fileid] - ptr->roffset; } /* remaining items to read */ if(chunk_size > towrite) { chunk_size = towrite; } /* write from the beginning of chunk */ big_array_iter_init(&chunk_iter, &chunk_array); /* now translate the data to format in the file*/ RAISEIF(0 != _dtype_convert(&chunk_iter, &array_iter, chunk_size * bb->nmemb), ex_convert, NULL); sysvsum(&bb->fchecksum[ptr->fileid], chunkbuf, chunk_size * felsize); fp = _big_file_open_a_file(bb->basename, ptr->fileid, "r+", 1); RAISEIF(fp == NULL, ex_open, NULL); RAISEIF(0 > fseek(fp, ptr->roffset * felsize, SEEK_SET), ex_seek, "Failed to seek in block `%s' at (%d:%td) (%s)", bb->basename, ptr->fileid, ptr->roffset * felsize, strerror(errno)); RAISEIF(chunk_size != fwrite(chunkbuf, felsize, chunk_size, fp), ex_write, "Failed to write in block `%s' at (%d:%td) (%s)", bb->basename, ptr->fileid, ptr->roffset * felsize, strerror(errno)); fclose(fp); towrite -= chunk_size; RAISEIF(0 != big_block_seek_rel(bb, ptr, chunk_size), ex_blockseek, NULL); } free(chunkbuf); return 0; ex_write: ex_seek: fclose(fp); ex_convert: ex_open: ex_blockseek: ex_eof: free(chunkbuf); ex_malloc: return -1; } /** * dtype stuff * */ #define MACHINE_ENDIANNESS MACHINE_ENDIAN_F() static char MACHINE_ENDIAN_F(void) { uint32_t i = 0x01234567; return ((*((uint8_t*)(&i))) == 0x67)?'<':'>'; } int _dtype_normalize(char * dst, const char * src) { /* normalize a dtype, so that * dst[0] is the endian-ness * dst[1] is the type kind char * dtype[2:] is the width * */ memset(dst, 0, 8); switch(src[0]) { case '<': case '>': case '|': case '=': strncpy(dst, src, 8); break; default: dst[0] = '='; strncpy(dst + 1, src, 7); } dst[7]='\0'; if(dst[0] == '=') { dst[0] = MACHINE_ENDIANNESS; } if(dst[0] == '|') { dst[0] = MACHINE_ENDIANNESS; } return 0; } /*Check that the passed dtype is valid. * Returns 1 if valid, 0 if invalid*/ static int dtype_isvalid(const char * dtype) { if(!dtype) return 0; switch(dtype[0]) { case '<': case '>': case '|': case '=': break; default: return 0; } switch(dtype[1]) { case 'S': case 'b': case 'i': case 'f': case 'u': case 'c': break; default: return 0; } int width = atoi(&dtype[2]); if(width > 16 || width <= 0) return 0; return 1; } int big_file_dtype_itemsize(const char * dtype) { char ndtype[8]; _dtype_normalize(ndtype, dtype); return atoi(&ndtype[2]); } int big_file_dtype_kind(const char * dtype) { char ndtype[8]; _dtype_normalize(ndtype, dtype); return ndtype[1]; } int big_array_init(BigArray * array, void * buf, const char * dtype, int ndim, const size_t dims[], const ptrdiff_t strides[]) { memset(array, 0, sizeof(array[0])); _dtype_normalize(array->dtype, dtype); array->data = buf; array->ndim = ndim; int i; memset(array->dims, 0, sizeof(ptrdiff_t) * 32); memset(array->strides, 0, sizeof(ptrdiff_t) * 32); array->size = 1; for(i = 0; i < ndim; i ++) { array->dims[i] = dims[i]; array->size *= dims[i]; } if(strides != NULL) { for(i = 0; i < ndim; i ++) { array->strides[i] = strides[i]; } } else { array->strides[ndim - 1] = big_file_dtype_itemsize(dtype); for(i = ndim - 2; i >= 0; i --) { array->strides[i] = array->strides[i + 1] * array->dims[i + 1]; } } return 0; } int big_array_iter_init(BigArrayIter * iter, BigArray * array) { memset(iter, 0, sizeof(iter[0])); iter->array = array; memset(iter->pos, 0, sizeof(ptrdiff_t) * 32); iter->dataptr = array->data; /* see if the iter is contiguous */ size_t elsize = big_file_dtype_itemsize(array->dtype); int i = 0; ptrdiff_t stride_contiguous = elsize; iter->contiguous = 1; for(i = array->ndim - 1; i >= 0; i --) { if(array->strides[i] != stride_contiguous) { iter->contiguous = 0; break; } stride_contiguous *= array->dims[i]; } return 0; } void big_array_iter_advance(BigArrayIter * iter) { BigArray * array = iter->array; if(iter->contiguous) { iter->dataptr = (char*) iter->dataptr + array->strides[array->ndim - 1]; return; } int k; iter->pos[array->ndim - 1] ++; iter->dataptr = ((char*) iter->dataptr) + array->strides[array->ndim - 1]; for(k = array->ndim - 1; k >= 0; k --) { if(iter->pos[k] == array->dims[k]) { iter->dataptr = ((char*) iter->dataptr) - array->strides[k] * iter->pos[k]; iter->pos[k] = 0; if(k > 0) { iter->pos[k - 1] ++; iter->dataptr = ((char*) iter->dataptr) + array->strides[k - 1]; } } else { break; } } } typedef struct {double r; double i;} cplx128_t; typedef struct {float r; float i;} cplx64_t; typedef union { char *a1; char *b1; int64_t *i8; uint64_t *u8; double *f8; int32_t *i4; uint32_t *u4; float *f4; cplx128_t * c16; cplx64_t * c8; void * v; } variant_t; /* format data in dtype to a string in buffer */ void big_file_dtype_format(char * buffer, const char * dtype, const void * data, const char * fmt) { char ndtype[8]; char ndtype2[8]; variant_t p; /* handle the endianness stuff in case it is not machine */ char converted[128]; _dtype_normalize(ndtype2, dtype); ndtype2[0] = '='; _dtype_normalize(ndtype, ndtype2); dtype_convert_simple(converted, ndtype, data, dtype, 1); p.v = converted; #define FORMAT1(dtype, defaultfmt) \ if(0 == strcmp(ndtype + 1, # dtype)) { \ if(fmt == NULL) fmt = defaultfmt; \ sprintf(buffer, fmt, *p.dtype); \ } else #define FORMAT2(dtype, defaultfmt) \ if(0 == strcmp(ndtype + 1, # dtype)) { \ if(fmt == NULL) fmt = defaultfmt; \ sprintf(buffer, fmt, p.dtype->r, p.dtype->i); \ } else FORMAT1(a1, "%c") FORMAT1(b1, "%d") FORMAT1(i8, "%ld") FORMAT1(i4, "%d") FORMAT1(u8, "%lu") FORMAT1(u4, "%u") FORMAT1(f8, "%g") FORMAT1(f4, "%g") FORMAT2(c8, "%g+%gI") FORMAT2(c16, "%g+%gI") { sprintf(buffer, "<%s>", ndtype); } } /* parse data in dtype to a string in buffer */ int big_file_dtype_parse(const char * buffer, const char * dtype, void * data, const char * fmt) { char ndtype[8]; char ndtype2[8]; variant_t p; /* handle the endianness stuff in case it is not machine */ char converted[128]; _dtype_normalize(ndtype2, dtype); ndtype2[0] = '='; _dtype_normalize(ndtype, ndtype2); p.v = converted; #define PARSE1(dtype, defaultfmt) \ if(0 == strcmp(ndtype + 1, # dtype)) { \ if(fmt == NULL) fmt = defaultfmt; \ sscanf(buffer, fmt, p.dtype); \ } #define PARSE2(dtype, defaultfmt) \ if(0 == strcmp(ndtype + 1, # dtype)) { \ if(fmt == NULL) fmt = defaultfmt; \ sscanf(buffer, fmt, &p.dtype->r, &p.dtype->i); \ } PARSE1(a1, "%c") else PARSE1(i8, "%ld") else PARSE1(i4, "%d") else PARSE1(u8, "%lu") else PARSE1(u4, "%u") else PARSE1(f8, "%lf") else PARSE1(f4, "%f") else PARSE2(c8, "%f + %f I") else PARSE2(c16, "%lf + %lf I") else return -1; dtype_convert_simple(data, dtype, converted, ndtype, 1); return 0; } static int dtype_convert_simple(void * dst, const char * dstdtype, const void * src, const char * srcdtype, size_t nmemb) { BigArray dst_array, src_array; BigArrayIter dst_iter, src_iter; big_array_init(&dst_array, dst, dstdtype, 1, &nmemb, NULL); big_array_init(&src_array, (void*) src, srcdtype, 1, &nmemb, NULL); big_array_iter_init(&dst_iter, &dst_array); big_array_iter_init(&src_iter, &src_array); return _dtype_convert(&dst_iter, &src_iter, nmemb); } static int cast(BigArrayIter * dst, BigArrayIter * src, size_t nmemb); static void byte_swap(BigArrayIter * array, size_t nmemb); int _dtype_convert(BigArrayIter * dst, BigArrayIter * src, size_t nmemb) { /* cast buf2 of dtype2 into buf1 of dtype1 */ /* match src to machine endianness */ if(src->array->dtype[0] != MACHINE_ENDIANNESS) { BigArrayIter iter = *src; byte_swap(&iter, nmemb); } BigArrayIter iter1 = *dst; BigArrayIter iter2 = *src; if(0 != cast(&iter1, &iter2, nmemb)) { /* cast is not supported */ return -1; } /* match dst to machine endianness */ if(dst->array->dtype[0] != MACHINE_ENDIANNESS) { BigArrayIter iter = *dst; byte_swap(&iter, nmemb); } *dst = iter1; *src = iter2; return 0; } static void byte_swap(BigArrayIter * iter, size_t nmemb) { /* swap a buffer in-place */ int elsize = big_file_dtype_itemsize(iter->array->dtype); if(elsize == 1) return; /* need byte swap; do it now on buf2 */ /* XXX: this may still be wrong. */ ptrdiff_t i; int half = elsize >> 1; for(i = 0; i < nmemb; i ++) { int j; char * ptr = iter->dataptr; for(j = 0; j < half; j ++) { char tmp = ptr[j]; ptr[j] = ptr[elsize - j - 1]; ptr[elsize - j - 1] = tmp; } big_array_iter_advance(iter); } } #define CAST(d1, t1, d2, t2) \ if((0 == strcmp(d1, dst->array->dtype + 1)) && (0 == strcmp(d2, src->array->dtype + 1))) { \ for(i = 0; i < nmemb; i ++) { \ t1 * p1 = dst->dataptr; t2 * p2 = src->dataptr; \ * p1 = * p2; \ big_array_iter_advance(dst); big_array_iter_advance(src); \ } \ return 0; \ } #define CAST2(d1, t1, d2, t2) \ if((0 == strcmp(d1, dst->array->dtype + 1)) && (0 == strcmp(d2, src->array->dtype + 1))) { \ for(i = 0; i < nmemb; i ++) { \ t1 * p1 = dst->dataptr; t2 * p2 = src->dataptr; \ p1->r = p2->r; p1->i = p2->i; \ big_array_iter_advance(dst); big_array_iter_advance(src); \ } \ return 0; \ } static int cast(BigArrayIter * dst, BigArrayIter * src, size_t nmemb) { /* doing cast assuming native byte order */ /* convert buf2 to buf1, both are native; * dtype has no endian-ness prefix * */ ptrdiff_t i; /* same type, no need for casting. */ if (0 == strcmp(dst->array->dtype + 1, src->array->dtype + 1)) { if(dst->contiguous && src->contiguous) { /* directly copy of memory chunks; FIXME: use memmove? */ memcpy(dst->dataptr, src->dataptr, nmemb * dst->array->strides[dst->array->ndim-1]); dst->dataptr = (char*) dst->dataptr + nmemb * dst->array->strides[dst->array->ndim - 1]; src->dataptr = (char*) src->dataptr + nmemb * src->array->strides[src->array->ndim - 1]; return 0; } else { /* copy one by one, discontinuous */ size_t elsize = big_file_dtype_itemsize(dst->array->dtype); for(i = 0; i < nmemb; i ++) { void * p1 = dst->dataptr; void * p2 = src->dataptr; memcpy(p1, p2, elsize); big_array_iter_advance(dst); big_array_iter_advance(src); } return 0; } } if(0 == strcmp(dst->array->dtype + 1, "i8")) { CAST("i8", int64_t, "i4", int32_t); CAST("i8", int64_t, "u4", uint32_t); CAST("i8", int64_t, "u8", uint64_t); CAST("i8", int64_t, "f8", double); CAST("i8", int64_t, "f4", float); CAST("i8", int64_t, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "u8")) { CAST("u8", uint64_t, "u4", uint32_t); CAST("u8", uint64_t, "i4", int32_t); CAST("u8", uint64_t, "i8", int64_t); CAST("u8", uint64_t, "f8", double); CAST("u8", uint64_t, "f4", float); CAST("u8", uint64_t, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "f8")) { CAST("f8", double, "f4", float); CAST("f8", double, "i4", int32_t); CAST("f8", double, "i8", int64_t); CAST("f8", double, "u4", uint32_t); CAST("f8", double, "u8", uint64_t); CAST("f8", double, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "i4")) { CAST("i4", int32_t, "i8", int64_t); CAST("i4", int32_t, "u4", uint32_t); CAST("i4", int32_t, "u8", uint64_t); CAST("i4", int32_t, "f8", double); CAST("i4", int32_t, "f4", float); CAST("i4", int32_t, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "u4")) { CAST("u4", uint32_t, "u8", uint64_t); CAST("u4", uint32_t, "i4", int32_t); CAST("u4", uint32_t, "i8", int64_t); CAST("u4", uint32_t, "f8", double); CAST("u4", uint32_t, "f4", float); CAST("u4", uint32_t, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "f4")) { CAST("f4", float, "f8", double); CAST("f4", float, "i4", int32_t); CAST("f4", float, "i8", int64_t); CAST("f4", float, "u4", uint32_t); CAST("f4", float, "u8", uint64_t); CAST("f4", float, "b1", char); } else if(0 == strcmp(dst->array->dtype + 1, "c8")) { CAST2("c8", cplx64_t, "c16", cplx128_t); } else if(0 == strcmp(dst->array->dtype + 1, "c16")) { CAST2("c16", cplx128_t, "c8", cplx64_t); } RAISE(ex, "Unsupported conversion from %s to %s. ", src->array->dtype, dst->array->dtype); ex: return -1; } static void sysvsum(unsigned int * sum, void * buf, size_t size) { unsigned int thisrun = *sum; unsigned char * cp = buf; while(size --) thisrun += *(cp++); *sum = thisrun; } /* * Internal API for AttrSet objects; * */ static int attrset_read_attr_set_v1(BigAttrSet * attrset, const char * basename) { attrset->dirty = 0; FILE * fattr = _big_file_open_a_file(basename, FILEID_ATTR, "r", 0); if(fattr == NULL) { return 0; } int nmemb; int lname; char dtype[9]={0}; char * data; char * name; while(!feof(fattr)) { if(1 != fread(&nmemb, sizeof(int), 1, fattr)) break; RAISEIF( (1 != fread(&lname, sizeof(int), 1, fattr)) || (1 != fread(&dtype, 8, 1, fattr)) || (!dtype_isvalid(dtype)), ex_fread, "Failed to read from file" ) int ldata = big_file_dtype_itemsize(dtype) * nmemb; data = alloca(ldata); name = alloca(lname + 1); RAISEIF( (1 != fread(name, lname, 1, fattr)) || (1 != fread(data, ldata, 1, fattr)), ex_fread, "Failed to read from file"); name[lname] = 0; RAISEIF(0 != attrset_set_attr(attrset, name, data, dtype, nmemb), ex_set_attr, NULL); } attrset->dirty = 0; fclose(fattr); return 0; ex_set_attr: ex_fread: attrset->dirty = 0; fclose(fattr); return -1; } static int _isblank(int ch) { return ch == ' ' || ch == '\t'; } static int attrset_read_attr_set_v2(BigAttrSet * attrset, const char * basename) { attrset->dirty = 0; FILE * fattr = _big_file_open_a_file(basename, FILEID_ATTR_V2, "r", 0); if(fattr == NULL) { return 0; } fseek(fattr, 0, SEEK_END); long size = ftell(fattr); /*ftell may fail*/ RAISEIF(size < 0, ex_init, "ftell error: %s",strerror(errno)); char * buffer = (char*) malloc(size + 1); RAISEIF(!buffer, ex_init, "Could not allocate memory for buffer: %ld bytes",size+1); unsigned char * data = (unsigned char * ) malloc(size + 1); RAISEIF(!data, ex_data, "Could not allocate memory for data: %ld bytes",size+1); fseek(fattr, 0, SEEK_SET); RAISEIF(size != fread(buffer, 1, size, fattr), ex_read_file, "Failed to read attribute file\n"); buffer[size] = 0; /* now parse the v2 attr file.*/ long i = 0; #define ATTRV2_EXPECT(variable) while(_isblank(buffer[i])) i++; \ char * variable = buffer + i; \ while(!_isblank(buffer[i])) i++; buffer[i] = 0; i++; while(buffer[i]) { ATTRV2_EXPECT(name); ATTRV2_EXPECT(dtype); ATTRV2_EXPECT(rawlength); ATTRV2_EXPECT(rawdata); /* skip the reset of the line */ while(buffer[i] != '\n' && buffer[i]) i ++; if(buffer[i] == '\n') i++; int nmemb = atoi(rawlength); int itemsize = big_file_dtype_itemsize(dtype); RAISEIF(nmemb * itemsize * 2!= strlen(rawdata), ex_parse_attr, "NMEMB and data mismiatch: %d x %d (%s) * 2 != %d", nmemb, itemsize, dtype, strlen(rawdata)); int j, k; for(k = 0, j = 0; k < nmemb * itemsize; k ++, j += 2) { char buf[3]; buf[0] = rawdata[j]; buf[1] = rawdata[j+1]; buf[2] = 0; unsigned int byte = strtoll(buf, NULL, 16); data[k] = byte; } RAISEIF(0 != attrset_set_attr(attrset, name, data, dtype, nmemb), ex_set_attr, NULL); } fclose(fattr); free(data); free(buffer); attrset->dirty = 0; return 0; ex_read_file: ex_parse_attr: ex_set_attr: attrset->dirty = 0; free(data); ex_data: free(buffer); ex_init: fclose(fattr); return -1; } static int attrset_write_attr_set_v2(BigAttrSet * attrset, const char * basename) { static char conv[] = "0123456789ABCDEF"; attrset->dirty = 0; FILE * fattr = _big_file_open_a_file(basename, FILEID_ATTR_V2, "w", 1); RAISEIF(fattr == NULL, ex_open, NULL); ptrdiff_t i; for(i = 0; i < attrset->listused; i ++) { BigAttr * a = & attrset->attrlist[i]; int itemsize = big_file_dtype_itemsize(a->dtype); int ldata = itemsize * a->nmemb; char * rawdata = malloc(ldata * 2 + 1); unsigned char * adata = (unsigned char*) a->data; int j, k; for(j = 0, k = 0; k < ldata; k ++, j+=2) { rawdata[j] = conv[adata[k] / 16]; rawdata[j + 1] = conv[adata[k] % 16]; } rawdata[j] = 0; char * textual; /* skip textual representation for very long columns */ if(ldata > 128) { textual = _strdup("... (Too Long) "); } else { textual = malloc(a->nmemb * 32 + 1); textual[0] = 0; for(j = 0; j < a->nmemb; j ++) { if(a->dtype[1] != 'a' && !(a->dtype[1] == 'S' && big_file_dtype_itemsize(a->dtype) == 1)) { char buf[128]; big_file_dtype_format(buf, a->dtype, &adata[j * itemsize], NULL); strcat(textual, buf); if(j != a->nmemb - 1) { strcat(textual, " "); } } else { /* pretty print string encoded as a1 or S1. */ char buf[] = {adata[j], 0}; if(buf[0] == '\n') { strcat(textual, "..."); break; } if(buf[0] == 0) { break; } strcat(textual, buf); } } } int rt = fprintf(fattr, "%s %s %d %s #HUMANE [ %s ]\n", a->name, a->dtype, a->nmemb, rawdata, textual ); free(rawdata); free(textual); RAISEIF(rt <= 0, ex_write, "Failed to write to file"); } fclose(fattr); return 0; ex_write: fclose(fattr); ex_open: return -1; } static int attr_cmp(const void * p1, const void * p2) { const BigAttr * c1 = p1; const BigAttr * c2 = p2; return strcmp(c1->name, c2->name); } static BigAttr * attrset_append_attr(BigAttrSet * attrset) { while(attrset->listsize - attrset->listused < 1) { attrset->attrlist = realloc(attrset->attrlist, attrset->listsize * 2 * sizeof(BigAttr)); attrset->listsize *= 2; } BigAttr * a = & (attrset->attrlist[attrset->listused++]); memset(a, 0, sizeof(BigAttr)); return a; } static int attrset_add_attr(BigAttrSet * attrset, const char * attrname, const char * dtype, int nmemb) { size_t size = big_file_dtype_itemsize(dtype) * nmemb + strlen(attrname) + 1; while(attrset->bufsize - attrset->bufused < size) { int i; for(i = 0; i < attrset->listused; i ++) { attrset->attrlist[i].data -= (ptrdiff_t) attrset->attrbuf; attrset->attrlist[i].name -= (ptrdiff_t) attrset->attrbuf; } attrset->attrbuf = realloc(attrset->attrbuf, attrset->bufsize * 2); attrset->bufsize *= 2; for(i = 0; i < attrset->listused; i ++) { attrset->attrlist[i].data += (ptrdiff_t) attrset->attrbuf; attrset->attrlist[i].name += (ptrdiff_t) attrset->attrbuf; } } char * free = attrset->attrbuf + attrset->bufused; attrset->bufused += size; BigAttr * n = attrset_append_attr(attrset); n->nmemb = nmemb; memset(n->dtype, 0, 8); _dtype_normalize(n->dtype, dtype); n->name = free; strcpy(free, attrname); free += strlen(attrname) + 1; n->data = free; qsort(attrset->attrlist, attrset->listused, sizeof(BigAttr), attr_cmp); return 0; } static BigAttr * attrset_lookup_attr(BigAttrSet * attrset, const char * attrname) { BigAttr lookup = {0}; lookup.name = (char*) attrname; BigAttr * found = bsearch(&lookup, attrset->attrlist, attrset->listused, sizeof(BigAttr), attr_cmp); return found; } static int attrset_remove_attr(BigAttrSet * attrset, const char * attrname) { BigAttr *attr = attrset_lookup_attr(attrset, attrname); RAISEIF(attr == NULL, ex_notfound, "Attribute name '%s' is not found.", attrname ) ptrdiff_t ind = attr - attrset->attrlist; memmove(&attrset->attrlist[ind], &attrset->attrlist[ind + 1], (attrset->listused - ind - 1) * sizeof(BigAttr)); attrset->listused -= 1; return 0; ex_notfound: return -1; } static BigAttr * attrset_list_attrs(BigAttrSet * attrset, size_t * count) { *count = attrset->listused; return attrset->attrlist; } static int attrset_set_attr(BigAttrSet * attrset, const char * attrname, const void * data, const char * dtype, int nmemb) { BigAttr * attr; attrset->dirty = 1; RAISEIF ( strchr(attrname, ' ') || strchr(attrname, '\t') || strchr(attrname, '\n'), ex_name, "Attribute name cannot contain blanks (space, tab or newline)" ); /* Remove it if it exists*/ attr = attrset_lookup_attr(attrset, attrname); if(attr) attrset_remove_attr(attrset, attrname); /* add ensures the dtype has been normalized! */ RAISEIF(0 != attrset_add_attr(attrset, attrname, dtype, nmemb), ex_add, "Failed to add attr"); attr = attrset_lookup_attr(attrset, attrname); RAISEIF(attr->nmemb != nmemb, ex_mismatch, "attr nmemb mismatch"); return dtype_convert_simple(attr->data, attr->dtype, data, dtype, attr->nmemb); ex_name: ex_mismatch: ex_add: return -1; } static int attrset_get_attr(BigAttrSet * attrset, const char * attrname, void * data, const char * dtype, int nmemb) { BigAttr * found = attrset_lookup_attr(attrset, attrname); RAISEIF(!found, ex_notfound, "attr not found"); RAISEIF(found->nmemb != nmemb, ex_mismatch, "attr nmemb mismatch"); return dtype_convert_simple(data, dtype, found->data, found->dtype, found->nmemb); ex_mismatch: ex_notfound: return -1; } static BigAttrSet * attrset_create(void) { BigAttrSet * attrset = calloc(1, sizeof(BigAttrSet)); attrset->attrbuf = malloc(128); attrset->bufsize = 128; attrset->bufused = 0; attrset->attrlist = malloc(sizeof(BigAttr) * 16); attrset->listsize = 16; attrset->listused = 0; return attrset; } static void attrset_free(BigAttrSet * attrset) { free(attrset->attrbuf); free(attrset->attrlist); free(attrset); } void big_attrset_set_dirty(BigAttrSet * attrset, int dirty) { attrset->dirty = dirty; } static void * _big_attrset_pack(BigAttrSet * attrset, size_t * bytes) { size_t n = 0; n += sizeof(BigAttrSet); n += attrset->bufused; n += sizeof(BigAttr) * attrset->listused; char * buf = calloc(n, 1); char * p = buf; char * attrbuf = (char*) (p + sizeof(BigAttrSet)); BigAttr * attrlist = (BigAttr *) (attrbuf + attrset->bufused); memcpy(p, attrset, sizeof(BigAttrSet)); memcpy(attrbuf, attrset->attrbuf, attrset->bufused); memcpy(attrlist, attrset->attrlist, attrset->listused * sizeof(BigAttr)); int i = 0; for(i = 0; i < attrset->listused; i ++) { attrlist[i].data -= (ptrdiff_t) attrset->attrbuf; attrlist[i].name -= (ptrdiff_t) attrset->attrbuf; } *bytes = n; return (void*) p; } static BigAttrSet * _big_attrset_unpack(void * p) { BigAttrSet * attrset = calloc(1, sizeof(attrset[0])); memcpy(attrset, p, sizeof(BigAttrSet)); p += sizeof(BigAttrSet); attrset->attrbuf = malloc(attrset->bufsize); attrset->attrlist = malloc(attrset->listsize * sizeof(BigAttr)); memcpy(attrset->attrbuf, p, attrset->bufused); p += attrset->bufused; memcpy(attrset->attrlist, p, attrset->listused * sizeof(BigAttr)); int i = 0; for(i = 0; i < attrset->listused; i ++) { attrset->attrlist[i].data += (ptrdiff_t) attrset->attrbuf; attrset->attrlist[i].name += (ptrdiff_t) attrset->attrbuf; } return attrset; } void * _big_block_pack(BigBlock * block, size_t * bytes) { size_t attrsize = 0; void * attrset = _big_attrset_pack(block->attrset, &attrsize); int Nfile = block->Nfile; * bytes = sizeof(block[0]) + strlen(block->basename) + 1 + (Nfile + 1) * sizeof(block->fsize[0]) + (Nfile + 1) * sizeof(block->foffset[0]) + (Nfile + 1) * sizeof(block->fchecksum[0]) + attrsize; void * buf = malloc(*bytes); char * ptr = (char *) buf; memcpy(ptr, block, sizeof(block[0])); ptr += sizeof(block[0]); memcpy(ptr, block->basename, strlen(block->basename) + 1); ptr += strlen(block->basename) + 1; if(block->fsize) memcpy(ptr, block->fsize, (Nfile + 1) * sizeof(block->fsize[0])); ptr += (Nfile + 1) * sizeof(block->fsize[0]); if(block->foffset) memcpy(ptr, block->foffset, (Nfile + 1) * sizeof(block->foffset[0])); ptr += (Nfile + 1) * sizeof(block->foffset[0]); if(block->fchecksum) memcpy(ptr, block->fchecksum, (Nfile + 1) * sizeof(block->fchecksum[0])); ptr += (Nfile + 1) * sizeof(block->fchecksum[0]); memcpy(ptr, attrset, attrsize); free(attrset); ptr += attrsize; return buf; } void _big_block_unpack(BigBlock * block, void * buf) { char * ptr = (char*)buf; memcpy(block, ptr, sizeof(block[0])); ptr += sizeof(block[0]); int Nfile = block->Nfile; block->fsize = calloc(Nfile + 1, sizeof(size_t)); block->foffset = calloc(Nfile + 1, sizeof(size_t)); block->fchecksum = calloc(Nfile + 1, sizeof(int)); block->basename = _strdup(ptr); ptr += strlen(ptr) + 1; if(block->fsize) memcpy(block->fsize, ptr, (Nfile + 1) * sizeof(block->fsize[0])); ptr += (Nfile + 1) * sizeof(block->fsize[0]); if(block->foffset) memcpy(block->foffset, ptr, (Nfile + 1) * sizeof(block->foffset[0])); ptr += (Nfile + 1) * sizeof(block->foffset[0]); if(block->fchecksum) memcpy(block->fchecksum, ptr, (Nfile + 1) * sizeof(block->fchecksum[0])); ptr += (Nfile + 1) * sizeof(block->fchecksum[0]); block->attrset = _big_attrset_unpack(ptr); } /* File Path */ FILE * _big_file_open_a_file(const char * basename, int fileid, char * mode, int raise) { char * filename; int unbuffered = 0; if(fileid == FILEID_HEADER) { filename = _path_join(basename, EXT_HEADER); } else if(fileid == FILEID_ATTR) { filename = _path_join(basename, EXT_ATTR); } else if(fileid == FILEID_ATTR_V2) { filename = _path_join(basename, EXT_ATTR_V2); } else { char d[128]; sprintf(d, EXT_DATA, fileid); filename = _path_join(basename, d); unbuffered = 1; } FILE * fp = fopen(filename, mode); if(!raise && fp == NULL) { goto ex_fopen; } RAISEIF(fp == NULL, ex_fopen, "Failed to open physical file `%s' with mode `%s' (%s)", filename, mode, strerror(errno)); if(unbuffered) { setbuf(fp, NULL); } ex_fopen: free(filename); return fp; } static int _big_file_mkdir(const char * dirname) { struct stat buf; int mkdirret; mkdirret = mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); /* stat is to make sure the dir doesn't exist; it could be owned by others and stopped * by a permission error, but we are still OK, as the dir is created*/ /* already exists; only check stat after mkdir fails with EACCES, avoid meta data calls. */ RAISEIF((mkdirret !=0 && errno != EEXIST && stat(dirname, &buf)), ex_mkdir, "Failed to create directory structure at `%s' (%s)", dirname, strerror(errno) ); /* Attempt to update the time stamp */ utimes(dirname, NULL); return 0; ex_mkdir: return -1; } /* make subdir rel to pathname, recursively making parents */ int _big_file_mksubdir_r(const char * pathname, const char * subdir) { char * subdirname = _strdup(subdir); char * p; char * mydirname; for(p = subdirname; *p; p ++) { if(*p != '/') continue; *p = 0; mydirname = _path_join(pathname, subdirname); if(strlen(mydirname) != 0) { RAISEIF(0 != _big_file_mkdir(mydirname), ex_mkdir, NULL); } free(mydirname); *p = '/'; } mydirname = _path_join(pathname, subdirname); RAISEIF(0 != _big_file_mkdir(mydirname), ex_mkdir, NULL); free(subdirname); free(mydirname); return 0; ex_mkdir: free(subdirname); free(mydirname); return -1; }
parallel.c
// OpenMP version. Edit and submit only this file. /* Enter your details below * Name : Qingwei Zeng * UCLA ID : 005181694 * Email : zenn@ucla.edu */ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include "utils.h" /* This function takes in two 3-d matrices: long *old, long *new. * It only updates the **non-boundary entries (NBE)** of the two matrices. * * It does the following: * - calculate the sum of old matrix's NBEs * we_need_the_var / gimmie_the_var * - make new matrix's NBEs the sum of the 9 neighboring entries in old matrix * - Record a histogram of new matrix's NBEs constant */ void work_it_par(long *old, long *new) { long aggregate = 1; const int DIM2 = DIM * DIM; /* size of one layer */ const int DIM3 = DIM2 * DIM; /* size of the whole cube */ const long we_need_the_var = we_need_the_func(); const long gimmie_the_var = gimmie_the_func(); const int num_procs = omp_get_num_procs(); omp_set_num_threads(num_procs); /* we first need to assign the workload evenly to each core. */ const int chunk_size = (DIM - 2) / num_procs; const int chunk_rmdr = (DIM - 2) % num_procs; #pragma omp parallel { int proc_id; int chunk_start, chunk_end; int i, j, k, u; long tmp; int aggregate_private; int histogrammy_private[10] = {0}; #pragma omp for reduction(+ : aggregate) for (proc_id = 0; proc_id < num_procs; ++proc_id) { chunk_start = 1 + proc_id * chunk_size + (proc_id < chunk_rmdr ? proc_id : chunk_rmdr); chunk_end = chunk_start + chunk_size + (proc_id < chunk_rmdr ? 1 : 0); /* the first chunk_rmdr cores works on an extra layer */ for (i = chunk_start * DIM2; i < chunk_end * DIM2; i += DIM2) for (j = i + DIM; j < i + DIM2 - DIM; j += DIM) for (k = j + 1; k < j + DIM - 1; ++k) { aggregate_private += old[k] * we_need_the_var / gimmie_the_var; tmp = 0; /* sum up neighboring NBEs without for loop (unrolling) */ u = k - DIM2; tmp += old[u - DIM - 1] + old[u - DIM] + old[u - DIM + 1]; tmp += old[u - 1] + old[u] + old[u + 1]; tmp += old[u + DIM - 1] + old[u + DIM] + old[u + DIM + 1]; u = k; tmp += old[u - DIM - 1] + old[u - DIM] + old[u - DIM + 1]; tmp += old[u - 1] + old[u] + old[u + 1]; tmp += old[u + DIM - 1] + old[u + DIM] + old[u + DIM + 1]; u = k + DIM2; tmp += old[u - DIM - 1] + old[u - DIM] + old[u - DIM + 1]; tmp += old[u - 1] + old[u] + old[u + 1]; tmp += old[u + DIM - 1] + old[u + DIM] + old[u + DIM + 1]; tmp /= 27; u = tmp / 100; new[k] = tmp; u = u <= 0 ? 0 : (u >= 9 ? 9 : u); histogrammy_private[u]++; } aggregate += aggregate_private; } #pragma omp critical { for (i = 0; i < 10; ++i) histogrammy[i] += histogrammy_private[i]; } } printf("AGGR:%ld\n", aggregate); }
convolution_3x3_pack4to1_bf16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_winograd64_pack4to1_bf16s_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; //size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); bottom_blob_tm.create(tiles, 64, inch, 4u * elempack, elempack, opt.workspace_allocator); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8][4]; // tile for (int i = 0; i < h_tm / 8; i++) { for (int j = 0; j < w_tm / 8; j++) { const unsigned short* r0 = img0.row<const unsigned short>(i * 6) + (j * 6) * 4; for (int m = 0; m < 8; m++) { float32x4_t _r00 = vcvt_f32_bf16(vld1_u16(r0)); float32x4_t _r01 = vcvt_f32_bf16(vld1_u16(r0 + 4)); float32x4_t _r02 = vcvt_f32_bf16(vld1_u16(r0 + 8)); float32x4_t _r03 = vcvt_f32_bf16(vld1_u16(r0 + 12)); float32x4_t _r04 = vcvt_f32_bf16(vld1_u16(r0 + 16)); float32x4_t _r05 = vcvt_f32_bf16(vld1_u16(r0 + 20)); float32x4_t _r06 = vcvt_f32_bf16(vld1_u16(r0 + 24)); float32x4_t _r07 = vcvt_f32_bf16(vld1_u16(r0 + 28)); float32x4_t _tmp0m = vmlaq_n_f32(vsubq_f32(_r00, _r06), vsubq_f32(_r04, _r02), 5.25f); float32x4_t _tmp7m = vmlaq_n_f32(vsubq_f32(_r07, _r01), vsubq_f32(_r03, _r05), 5.25f); vst1q_f32(tmp[0][m], _tmp0m); vst1q_f32(tmp[7][m], _tmp7m); // tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; // tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_r02, _r06), _r04, 4.25f); float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_r01, _r05), _r03, 4.25f); // float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); // float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); float32x4_t _tmp1m = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _tmp2m = vsubq_f32(_tmp12a, _tmp12b); vst1q_f32(tmp[1][m], _tmp1m); vst1q_f32(tmp[2][m], _tmp2m); // tmp[1][m] = tmp12a + tmp12b; // tmp[2][m] = tmp12a - tmp12b; float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_r06, _r02, 0.25f), _r04, 1.25f); float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 0.5f), _r03, 2.5f), _r05, 2.f); // float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); // float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); float32x4_t _tmp3m = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _tmp4m = vsubq_f32(_tmp34a, _tmp34b); vst1q_f32(tmp[3][m], _tmp3m); vst1q_f32(tmp[4][m], _tmp4m); // tmp[3][m] = tmp34a + tmp34b; // tmp[4][m] = tmp34a - tmp34b; float32x4_t _tmp56a = vmlaq_n_f32(_r06, vmlsq_n_f32(_r02, _r04, 1.25f), 4.f); float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 2.f), _r03, 2.5f), _r05, 0.5f); // float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); // float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); float32x4_t _tmp5m = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _tmp6m = vsubq_f32(_tmp56a, _tmp56b); vst1q_f32(tmp[5][m], _tmp5m); vst1q_f32(tmp[6][m], _tmp6m); // tmp[5][m] = tmp56a + tmp56b; // tmp[6][m] = tmp56a - tmp56b; r0 += w * 4; } float* r0_tm_0 = (float*)img0_tm + (i * w_tm / 8 + j) * 4; float* r0_tm_1 = r0_tm_0 + tiles * 4; float* r0_tm_2 = r0_tm_0 + tiles * 8; float* r0_tm_3 = r0_tm_0 + tiles * 12; float* r0_tm_4 = r0_tm_0 + tiles * 16; float* r0_tm_5 = r0_tm_0 + tiles * 20; float* r0_tm_6 = r0_tm_0 + tiles * 24; float* r0_tm_7 = r0_tm_0 + tiles * 28; for (int m = 0; m < 8; m++) { float32x4_t _tmp00 = vld1q_f32(tmp[m][0]); float32x4_t _tmp01 = vld1q_f32(tmp[m][1]); float32x4_t _tmp02 = vld1q_f32(tmp[m][2]); float32x4_t _tmp03 = vld1q_f32(tmp[m][3]); float32x4_t _tmp04 = vld1q_f32(tmp[m][4]); float32x4_t _tmp05 = vld1q_f32(tmp[m][5]); float32x4_t _tmp06 = vld1q_f32(tmp[m][6]); float32x4_t _tmp07 = vld1q_f32(tmp[m][7]); float32x4_t _r0tm0 = vmlaq_n_f32(vsubq_f32(_tmp00, _tmp06), vsubq_f32(_tmp04, _tmp02), 5.25f); float32x4_t _r0tm7 = vmlaq_n_f32(vsubq_f32(_tmp07, _tmp01), vsubq_f32(_tmp03, _tmp05), 5.25f); // r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; // r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_tmp02, _tmp06), _tmp04, 4.25f); float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_tmp01, _tmp05), _tmp03, 4.25f); // float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); // float tmp12b = (tmp0[1] + tmp0[5] - tmp0[3] * 4.25); float32x4_t _r0tm1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _r0tm2 = vsubq_f32(_tmp12a, _tmp12b); // r0_tm[1] = tmp12a + tmp12b; // r0_tm[2] = tmp12a - tmp12b; float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_tmp06, _tmp02, 0.25f), _tmp04, 1.25f); float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 0.5f), _tmp03, 2.5f), _tmp05, 2.f); // float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); // float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); float32x4_t _r0tm3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _r0tm4 = vsubq_f32(_tmp34a, _tmp34b); // r0_tm[3] = tmp34a + tmp34b; // r0_tm[4] = tmp34a - tmp34b; float32x4_t _tmp56a = vmlaq_n_f32(_tmp06, vmlsq_n_f32(_tmp02, _tmp04, 1.25f), 4.f); float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 2.f), _tmp03, 2.5f), _tmp05, 0.5f); // float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); // float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); float32x4_t _r0tm5 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _r0tm6 = vsubq_f32(_tmp56a, _tmp56b); // r0_tm[5] = tmp56a + tmp56b; // r0_tm[6] = tmp56a - tmp56b; vst1q_f32(r0_tm_0, _r0tm0); vst1q_f32(r0_tm_1, _r0tm1); vst1q_f32(r0_tm_2, _r0tm2); vst1q_f32(r0_tm_3, _r0tm3); vst1q_f32(r0_tm_4, _r0tm4); vst1q_f32(r0_tm_5, _r0tm5); vst1q_f32(r0_tm_6, _r0tm6); vst1q_f32(r0_tm_7, _r0tm7); r0_tm_0 += tiles * 32; r0_tm_1 += tiles * 32; r0_tm_2 += tiles * 32; r0_tm_3 += tiles * 32; r0_tm_4 += tiles * 32; r0_tm_5 += tiles * 32; r0_tm_6 += tiles * 32; r0_tm_7 += tiles * 32; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __aarch64__ if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + tiles % 12 % 4, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 64, 4u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, 4u * elempack, elempack, opt.workspace_allocator); #else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 64, 4u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, 4u * elempack, elempack, opt.workspace_allocator); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { float* tm2p = tm2.row(i / 12); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0] \n" "sub %0, %0, #128 \n" "st1 {v0.4s}, [%1], #16 \n" "st1 {v4.4s}, [%1], #16 \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v1.4s}, [%1], #16 \n" "st1 {v5.4s}, [%1], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "st1 {v2.4s}, [%1], #16 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v18.4s}, [%1], #16 \n" "st1 {v3.4s}, [%1], #16 \n" "st1 {v7.4s}, [%1], #16 \n" "st1 {v19.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19"); r0 += bottom_blob_tm.cstep * 4; } } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8); #else float* tm2p = tm2.row(i / 8); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n" "sub %0, %0, #64 \n" "st1 {v0.4s}, [%1], #16 \n" "st1 {v4.4s}, [%1], #16 \n" "st1 {v1.4s}, [%1], #16 \n" "st1 {v5.4s}, [%1], #16 \n" "st1 {v2.4s}, [%1], #16 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v3.4s}, [%1], #16 \n" "st1 {v7.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"); #else asm volatile( "pld [%0, #256] \n" "vld4.f32 {d0-d3}, [%0 :128]! \n" "pld [%0, #256] \n" "vld4.f32 {d4-d7}, [%0 :128]! \n" "pld [%0, #256] \n" "vld4.f32 {d16-d19}, [%0 :128]! \n" "pld [%0, #256] \n" "vld4.f32 {d20-d23}, [%0 :128] \n" "sub %0, %0, #96 \n" "vswp d1, d4 \n" "vswp d3, d6 \n" "vswp d17, d20 \n" "vswp d19, d22 \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" "vst1.f32 {d4-d5}, [%1 :128]! \n" "vst1.f32 {d20-d21}, [%1 :128]! \n" "vst1.f32 {d2-d3}, [%1 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "vst1.f32 {d6-d7}, [%1 :128]! \n" "vst1.f32 {d22-d23}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11"); #endif r0 += bottom_blob_tm.cstep * 4; } } for (; i + 3 < tiles; i += 4) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); #else asm volatile( "pld [%0, #256] \n" "vld4.f32 {d0-d3}, [%0 :128]! \n" "pld [%0, #256] \n" "vld4.f32 {d4-d7}, [%0 :128] \n" "sub %0, %0, #32 \n" "vswp d1, d4 \n" "vswp d3, d6 \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" "vst1.f32 {d4-d5}, [%1 :128]! \n" "vst1.f32 {d2-d3}, [%1 :128]! \n" "vst1.f32 {d6-d7}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } for (; i < tiles; i++) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + i % 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.4s}, [%0] \n" "st1 {v0.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0"); #else asm volatile( "pld [%0, #128] \n" "vld1.f32 {d0-d1}, [%0 :128] \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator); int nn_outch = 0; int remain_outch_start = 0; #if __aarch64__ nn_outch = outch >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); float* output4_tm = top_blob_tm.channel(p + 4); float* output5_tm = top_blob_tm.channel(p + 5); float* output6_tm = top_blob_tm.channel(p + 6); float* output7_tm = top_blob_tm.channel(p + 7); const Mat kernel01_tm = kernel_tm.channel(p / 8); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v11.4s, v0.4s, v4.s[1] \n" "fmla v14.4s, v0.4s, v4.s[2] \n" "fmla v17.4s, v0.4s, v4.s[3] \n" "fmla v20.4s, v0.4s, v5.s[0] \n" "fmla v23.4s, v0.4s, v5.s[1] \n" "fmla v26.4s, v0.4s, v5.s[2] \n" "fmla v29.4s, v0.4s, v5.s[3] \n" "fmla v9.4s, v1.4s, v4.s[0] \n" "fmla v12.4s, v1.4s, v4.s[1] \n" "fmla v15.4s, v1.4s, v4.s[2] \n" "fmla v18.4s, v1.4s, v4.s[3] \n" "fmla v21.4s, v1.4s, v5.s[0] \n" "fmla v24.4s, v1.4s, v5.s[1] \n" "fmla v27.4s, v1.4s, v5.s[2] \n" "fmla v30.4s, v1.4s, v5.s[3] \n" "fmla v10.4s, v2.4s, v4.s[0] \n" "fmla v13.4s, v2.4s, v4.s[1] \n" "fmla v16.4s, v2.4s, v4.s[2] \n" "fmla v19.4s, v2.4s, v4.s[3] \n" "fmla v22.4s, v2.4s, v5.s[0] \n" "fmla v25.4s, v2.4s, v5.s[1] \n" "fmla v28.4s, v2.4s, v5.s[2] \n" "fmla v31.4s, v2.4s, v5.s[3] \n" "fmla v8.4s, v3.4s, v6.s[0] \n" "fmla v11.4s, v3.4s, v6.s[1] \n" "fmla v14.4s, v3.4s, v6.s[2] \n" "fmla v17.4s, v3.4s, v6.s[3] \n" "fmla v20.4s, v3.4s, v7.s[0] \n" "fmla v23.4s, v3.4s, v7.s[1] \n" "fmla v26.4s, v3.4s, v7.s[2] \n" "fmla v29.4s, v3.4s, v7.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v9.4s, v0.4s, v6.s[0] \n" "fmla v12.4s, v0.4s, v6.s[1] \n" "fmla v15.4s, v0.4s, v6.s[2] \n" "fmla v18.4s, v0.4s, v6.s[3] \n" "fmla v21.4s, v0.4s, v7.s[0] \n" "fmla v24.4s, v0.4s, v7.s[1] \n" "fmla v27.4s, v0.4s, v7.s[2] \n" "fmla v30.4s, v0.4s, v7.s[3] \n" "fmla v10.4s, v1.4s, v6.s[0] \n" "fmla v13.4s, v1.4s, v6.s[1] \n" "fmla v16.4s, v1.4s, v6.s[2] \n" "fmla v19.4s, v1.4s, v6.s[3] \n" "fmla v22.4s, v1.4s, v7.s[0] \n" "fmla v25.4s, v1.4s, v7.s[1] \n" "fmla v28.4s, v1.4s, v7.s[2] \n" "fmla v31.4s, v1.4s, v7.s[3] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n" "fmla v8.4s, v2.4s, v4.s[0] \n" "fmla v11.4s, v2.4s, v4.s[1] \n" "fmla v14.4s, v2.4s, v4.s[2] \n" "fmla v17.4s, v2.4s, v4.s[3] \n" "fmla v20.4s, v2.4s, v5.s[0] \n" "fmla v23.4s, v2.4s, v5.s[1] \n" "fmla v26.4s, v2.4s, v5.s[2] \n" "fmla v29.4s, v2.4s, v5.s[3] \n" "fmla v9.4s, v3.4s, v4.s[0] \n" "fmla v12.4s, v3.4s, v4.s[1] \n" "fmla v15.4s, v3.4s, v4.s[2] \n" "fmla v18.4s, v3.4s, v4.s[3] \n" "fmla v21.4s, v3.4s, v5.s[0] \n" "fmla v24.4s, v3.4s, v5.s[1] \n" "fmla v27.4s, v3.4s, v5.s[2] \n" "fmla v30.4s, v3.4s, v5.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v10.4s, v0.4s, v4.s[0] \n" "fmla v13.4s, v0.4s, v4.s[1] \n" "fmla v16.4s, v0.4s, v4.s[2] \n" "fmla v19.4s, v0.4s, v4.s[3] \n" "fmla v22.4s, v0.4s, v5.s[0] \n" "fmla v25.4s, v0.4s, v5.s[1] \n" "fmla v28.4s, v0.4s, v5.s[2] \n" "fmla v31.4s, v0.4s, v5.s[3] \n" "fmla v8.4s, v1.4s, v6.s[0] \n" "fmla v11.4s, v1.4s, v6.s[1] \n" "fmla v14.4s, v1.4s, v6.s[2] \n" "fmla v17.4s, v1.4s, v6.s[3] \n" "fmla v20.4s, v1.4s, v7.s[0] \n" "fmla v23.4s, v1.4s, v7.s[1] \n" "fmla v26.4s, v1.4s, v7.s[2] \n" "fmla v29.4s, v1.4s, v7.s[3] \n" "fmla v9.4s, v2.4s, v6.s[0] \n" "fmla v12.4s, v2.4s, v6.s[1] \n" "fmla v15.4s, v2.4s, v6.s[2] \n" "fmla v18.4s, v2.4s, v6.s[3] \n" "fmla v21.4s, v2.4s, v7.s[0] \n" "fmla v24.4s, v2.4s, v7.s[1] \n" "fmla v27.4s, v2.4s, v7.s[2] \n" "fmla v30.4s, v2.4s, v7.s[3] \n" "fmla v10.4s, v3.4s, v6.s[0] \n" "fmla v13.4s, v3.4s, v6.s[1] \n" "fmla v16.4s, v3.4s, v6.s[2] \n" "fmla v19.4s, v3.4s, v6.s[3] \n" "fmla v22.4s, v3.4s, v7.s[0] \n" "fmla v25.4s, v3.4s, v7.s[1] \n" "fmla v28.4s, v3.4s, v7.s[2] \n" "fmla v31.4s, v3.4s, v7.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n" "st1 {v11.4s, v12.4s, v13.4s}, [%2], #48 \n" "st1 {v14.4s, v15.4s, v16.4s}, [%3], #48 \n" "st1 {v17.4s, v18.4s, v19.4s}, [%4], #48 \n" "st1 {v20.4s, v21.4s, v22.4s}, [%5], #48 \n" "st1 {v23.4s, v24.4s, v25.4s}, [%6], #48 \n" "st1 {v26.4s, v27.4s, v28.4s}, [%7], #48 \n" "st1 {v29.4s, v30.4s, v31.4s}, [%8], #48 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(output4_tm), // %5 "=r"(output5_tm), // %6 "=r"(output6_tm), // %7 "=r"(output7_tm), // %8 "=r"(r0), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(output4_tm), "6"(output5_tm), "7"(output6_tm), "8"(output7_tm), "9"(r0), "10"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8); const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v0.4s, v4.s[0] \n" "fmla v18.4s, v0.4s, v4.s[1] \n" "fmla v20.4s, v0.4s, v4.s[2] \n" "fmla v22.4s, v0.4s, v4.s[3] \n" "fmla v24.4s, v0.4s, v5.s[0] \n" "fmla v26.4s, v0.4s, v5.s[1] \n" "fmla v28.4s, v0.4s, v5.s[2] \n" "fmla v30.4s, v0.4s, v5.s[3] \n" "fmla v17.4s, v1.4s, v4.s[0] \n" "fmla v19.4s, v1.4s, v4.s[1] \n" "fmla v21.4s, v1.4s, v4.s[2] \n" "fmla v23.4s, v1.4s, v4.s[3] \n" "fmla v25.4s, v1.4s, v5.s[0] \n" "fmla v27.4s, v1.4s, v5.s[1] \n" "fmla v29.4s, v1.4s, v5.s[2] \n" "fmla v31.4s, v1.4s, v5.s[3] \n" "fmla v16.4s, v2.4s, v6.s[0] \n" "fmla v18.4s, v2.4s, v6.s[1] \n" "fmla v20.4s, v2.4s, v6.s[2] \n" "fmla v22.4s, v2.4s, v6.s[3] \n" "fmla v24.4s, v2.4s, v7.s[0] \n" "fmla v26.4s, v2.4s, v7.s[1] \n" "fmla v28.4s, v2.4s, v7.s[2] \n" "fmla v30.4s, v2.4s, v7.s[3] \n" "fmla v17.4s, v3.4s, v6.s[0] \n" "fmla v19.4s, v3.4s, v6.s[1] \n" "fmla v21.4s, v3.4s, v6.s[2] \n" "fmla v23.4s, v3.4s, v6.s[3] \n" "fmla v25.4s, v3.4s, v7.s[0] \n" "fmla v27.4s, v3.4s, v7.s[1] \n" "fmla v29.4s, v3.4s, v7.s[2] \n" "fmla v31.4s, v3.4s, v7.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n" "fmla v16.4s, v12.4s, v8.s[0] \n" "fmla v18.4s, v12.4s, v8.s[1] \n" "fmla v20.4s, v12.4s, v8.s[2] \n" "fmla v22.4s, v12.4s, v8.s[3] \n" "fmla v24.4s, v12.4s, v9.s[0] \n" "fmla v26.4s, v12.4s, v9.s[1] \n" "fmla v28.4s, v12.4s, v9.s[2] \n" "fmla v30.4s, v12.4s, v9.s[3] \n" "fmla v17.4s, v13.4s, v8.s[0] \n" "fmla v19.4s, v13.4s, v8.s[1] \n" "fmla v21.4s, v13.4s, v8.s[2] \n" "fmla v23.4s, v13.4s, v8.s[3] \n" "fmla v25.4s, v13.4s, v9.s[0] \n" "fmla v27.4s, v13.4s, v9.s[1] \n" "fmla v29.4s, v13.4s, v9.s[2] \n" "fmla v31.4s, v13.4s, v9.s[3] \n" "fmla v16.4s, v14.4s, v10.s[0] \n" "fmla v18.4s, v14.4s, v10.s[1] \n" "fmla v20.4s, v14.4s, v10.s[2] \n" "fmla v22.4s, v14.4s, v10.s[3] \n" "fmla v24.4s, v14.4s, v11.s[0] \n" "fmla v26.4s, v14.4s, v11.s[1] \n" "fmla v28.4s, v14.4s, v11.s[2] \n" "fmla v30.4s, v14.4s, v11.s[3] \n" "fmla v17.4s, v15.4s, v10.s[0] \n" "fmla v19.4s, v15.4s, v10.s[1] \n" "fmla v21.4s, v15.4s, v10.s[2] \n" "fmla v23.4s, v15.4s, v10.s[3] \n" "fmla v25.4s, v15.4s, v11.s[0] \n" "fmla v27.4s, v15.4s, v11.s[1] \n" "fmla v29.4s, v15.4s, v11.s[2] \n" "fmla v31.4s, v15.4s, v11.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" "st1 {v18.4s, v19.4s}, [%2], #32 \n" "st1 {v20.4s, v21.4s}, [%3], #32 \n" "st1 {v22.4s, v23.4s}, [%4], #32 \n" "st1 {v24.4s, v25.4s}, [%5], #32 \n" "st1 {v26.4s, v27.4s}, [%6], #32 \n" "st1 {v28.4s, v29.4s}, [%7], #32 \n" "st1 {v30.4s, v31.4s}, [%8], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(output4_tm), // %5 "=r"(output5_tm), // %6 "=r"(output6_tm), // %7 "=r"(output7_tm), // %8 "=r"(r0), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(output4_tm), "6"(output5_tm), "7"(output6_tm), "8"(output7_tm), "9"(r0), "10"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v0.4s, v4.s[0] \n" "fmla v17.4s, v0.4s, v4.s[1] \n" "fmla v18.4s, v0.4s, v4.s[2] \n" "fmla v19.4s, v0.4s, v4.s[3] \n" "fmla v20.4s, v0.4s, v5.s[0] \n" "fmla v21.4s, v0.4s, v5.s[1] \n" "fmla v22.4s, v0.4s, v5.s[2] \n" "fmla v23.4s, v0.4s, v5.s[3] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n" "fmla v16.4s, v1.4s, v6.s[0] \n" "fmla v17.4s, v1.4s, v6.s[1] \n" "fmla v18.4s, v1.4s, v6.s[2] \n" "fmla v19.4s, v1.4s, v6.s[3] \n" "fmla v20.4s, v1.4s, v7.s[0] \n" "fmla v21.4s, v1.4s, v7.s[1] \n" "fmla v22.4s, v1.4s, v7.s[2] \n" "fmla v23.4s, v1.4s, v7.s[3] \n" "fmla v16.4s, v2.4s, v8.s[0] \n" "fmla v17.4s, v2.4s, v8.s[1] \n" "fmla v18.4s, v2.4s, v8.s[2] \n" "fmla v19.4s, v2.4s, v8.s[3] \n" "fmla v20.4s, v2.4s, v9.s[0] \n" "fmla v21.4s, v2.4s, v9.s[1] \n" "fmla v22.4s, v2.4s, v9.s[2] \n" "fmla v23.4s, v2.4s, v9.s[3] \n" "fmla v16.4s, v3.4s, v10.s[0] \n" "fmla v17.4s, v3.4s, v10.s[1] \n" "fmla v18.4s, v3.4s, v10.s[2] \n" "fmla v19.4s, v3.4s, v10.s[3] \n" "fmla v20.4s, v3.4s, v11.s[0] \n" "fmla v21.4s, v3.4s, v11.s[1] \n" "fmla v22.4s, v3.4s, v11.s[2] \n" "fmla v23.4s, v3.4s, v11.s[3] \n" "bne 0b \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" "st1 {v18.4s}, [%3], #16 \n" "st1 {v19.4s}, [%4], #16 \n" "st1 {v20.4s}, [%5], #16 \n" "st1 {v21.4s}, [%6], #16 \n" "st1 {v22.4s}, [%7], #16 \n" "st1 {v23.4s}, [%8], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(output4_tm), // %5 "=r"(output5_tm), // %6 "=r"(output6_tm), // %7 "=r"(output7_tm), // %8 "=r"(r0), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(output4_tm), "6"(output5_tm), "7"(output6_tm), "8"(output7_tm), "9"(r0), "10"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4); const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.4s}, [%9], #16 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v4.4s, v0.s[0] \n" "fmla v17.4s, v5.4s, v0.s[0] \n" "fmla v18.4s, v6.4s, v0.s[1] \n" "fmla v19.4s, v7.4s, v0.s[1] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n" "fmla v16.4s, v8.4s, v0.s[2] \n" "fmla v17.4s, v9.4s, v0.s[2] \n" "fmla v18.4s, v10.4s, v0.s[3] \n" "fmla v19.4s, v11.4s, v0.s[3] \n" "bne 0b \n" "fadd v16.4s, v16.4s, v18.4s \n" "fadd v17.4s, v17.4s, v19.4s \n" "st1 {v16.s}[0], [%1], #4 \n" "st1 {v16.s}[1], [%2], #4 \n" "st1 {v16.s}[2], [%3], #4 \n" "st1 {v16.s}[3], [%4], #4 \n" "st1 {v17.s}[0], [%5], #4 \n" "st1 {v17.s}[1], [%6], #4 \n" "st1 {v17.s}[2], [%7], #4 \n" "st1 {v17.s}[3], [%8], #4 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(output4_tm), // %5 "=r"(output5_tm), // %6 "=r"(output6_tm), // %7 "=r"(output7_tm), // %8 "=r"(r0), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(output4_tm), "6"(output5_tm), "7"(output6_tm), "8"(output7_tm), "9"(r0), "10"(kptr) : "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"); } } } remain_outch_start += nn_outch << 3; nn_outch = (outch - remain_outch_start) >> 2; #else // __aarch64__ nn_outch = outch >> 2; #endif // __aarch64__ #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); #if __aarch64__ const Mat kernel01_tm = kernel_tm.channel(p / 8 + (p % 8) / 4); #else const Mat kernel01_tm = kernel_tm.channel(p / 4); #endif for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v11.4s, v0.4s, v4.s[1] \n" "fmla v14.4s, v0.4s, v4.s[2] \n" "fmla v17.4s, v0.4s, v4.s[3] \n" "fmla v9.4s, v1.4s, v4.s[0] \n" "fmla v12.4s, v1.4s, v4.s[1] \n" "fmla v15.4s, v1.4s, v4.s[2] \n" "fmla v18.4s, v1.4s, v4.s[3] \n" "fmla v10.4s, v2.4s, v4.s[0] \n" "fmla v13.4s, v2.4s, v4.s[1] \n" "fmla v16.4s, v2.4s, v4.s[2] \n" "fmla v19.4s, v2.4s, v4.s[3] \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%5], #64 \n" "fmla v8.4s, v3.4s, v5.s[0] \n" "fmla v11.4s, v3.4s, v5.s[1] \n" "fmla v14.4s, v3.4s, v5.s[2] \n" "fmla v17.4s, v3.4s, v5.s[3] \n" "fmla v9.4s, v20.4s, v5.s[0] \n" "fmla v12.4s, v20.4s, v5.s[1] \n" "fmla v15.4s, v20.4s, v5.s[2] \n" "fmla v18.4s, v20.4s, v5.s[3] \n" "fmla v10.4s, v21.4s, v5.s[0] \n" "fmla v13.4s, v21.4s, v5.s[1] \n" "fmla v16.4s, v21.4s, v5.s[2] \n" "fmla v19.4s, v21.4s, v5.s[3] \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%5], #64 \n" "fmla v8.4s, v22.4s, v6.s[0] \n" "fmla v11.4s, v22.4s, v6.s[1] \n" "fmla v14.4s, v22.4s, v6.s[2] \n" "fmla v17.4s, v22.4s, v6.s[3] \n" "fmla v9.4s, v23.4s, v6.s[0] \n" "fmla v12.4s, v23.4s, v6.s[1] \n" "fmla v15.4s, v23.4s, v6.s[2] \n" "fmla v18.4s, v23.4s, v6.s[3] \n" "fmla v10.4s, v24.4s, v6.s[0] \n" "fmla v13.4s, v24.4s, v6.s[1] \n" "fmla v16.4s, v24.4s, v6.s[2] \n" "fmla v19.4s, v24.4s, v6.s[3] \n" "fmla v8.4s, v25.4s, v7.s[0] \n" "fmla v11.4s, v25.4s, v7.s[1] \n" "fmla v14.4s, v25.4s, v7.s[2] \n" "fmla v17.4s, v25.4s, v7.s[3] \n" "fmla v9.4s, v26.4s, v7.s[0] \n" "fmla v12.4s, v26.4s, v7.s[1] \n" "fmla v15.4s, v26.4s, v7.s[2] \n" "fmla v18.4s, v26.4s, v7.s[3] \n" "fmla v10.4s, v27.4s, v7.s[0] \n" "fmla v13.4s, v27.4s, v7.s[1] \n" "fmla v16.4s, v27.4s, v7.s[2] \n" "fmla v19.4s, v27.4s, v7.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n" "st1 {v11.4s, v12.4s, v13.4s}, [%2], #48 \n" "st1 {v14.4s, v15.4s, v16.4s}, [%3], #48 \n" "st1 {v17.4s, v18.4s, v19.4s}, [%4], #48 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); } #endif // __aarch64__ for (; i + 7 < tiles; i += 8) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8); #else const float* r0 = bb2.row(i / 8); #endif const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v10.4s, v0.4s, v4.s[1] \n" "fmla v12.4s, v0.4s, v4.s[2] \n" "fmla v14.4s, v0.4s, v4.s[3] \n" "fmla v9.4s, v1.4s, v4.s[0] \n" "fmla v11.4s, v1.4s, v4.s[1] \n" "fmla v13.4s, v1.4s, v4.s[2] \n" "fmla v15.4s, v1.4s, v4.s[3] \n" "fmla v8.4s, v2.4s, v5.s[0] \n" "fmla v10.4s, v2.4s, v5.s[1] \n" "fmla v12.4s, v2.4s, v5.s[2] \n" "fmla v14.4s, v2.4s, v5.s[3] \n" "fmla v9.4s, v3.4s, v5.s[0] \n" "fmla v11.4s, v3.4s, v5.s[1] \n" "fmla v13.4s, v3.4s, v5.s[2] \n" "fmla v15.4s, v3.4s, v5.s[3] \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%5], #64 \n" "fmla v8.4s, v16.4s, v6.s[0] \n" "fmla v10.4s, v16.4s, v6.s[1] \n" "fmla v12.4s, v16.4s, v6.s[2] \n" "fmla v14.4s, v16.4s, v6.s[3] \n" "fmla v9.4s, v17.4s, v6.s[0] \n" "fmla v11.4s, v17.4s, v6.s[1] \n" "fmla v13.4s, v17.4s, v6.s[2] \n" "fmla v15.4s, v17.4s, v6.s[3] \n" "fmla v8.4s, v18.4s, v7.s[0] \n" "fmla v10.4s, v18.4s, v7.s[1] \n" "fmla v12.4s, v18.4s, v7.s[2] \n" "fmla v14.4s, v18.4s, v7.s[3] \n" "fmla v9.4s, v19.4s, v7.s[0] \n" "fmla v11.4s, v19.4s, v7.s[1] \n" "fmla v13.4s, v19.4s, v7.s[2] \n" "fmla v15.4s, v19.4s, v7.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"); #else // __aarch64__ asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "veor q12, q12 \n" "veor q13, q13 \n" "veor q14, q14 \n" "veor q15, q15 \n" "0: \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" "pld [%6, #512] \n" "vldm %6!, {d8-d15} \n" "vmla.f32 q8, q0, d8[0] \n" "vmla.f32 q10, q0, d8[1] \n" "vmla.f32 q12, q0, d9[0] \n" "vmla.f32 q14, q0, d9[1] \n" "vmla.f32 q9, q1, d8[0] \n" "vmla.f32 q11, q1, d8[1] \n" "vmla.f32 q13, q1, d9[0] \n" "vmla.f32 q15, q1, d9[1] \n" "vmla.f32 q8, q2, d10[0] \n" "vmla.f32 q10, q2, d10[1] \n" "vmla.f32 q12, q2, d11[0] \n" "vmla.f32 q14, q2, d11[1] \n" "vmla.f32 q9, q3, d10[0] \n" "vmla.f32 q11, q3, d10[1] \n" "vmla.f32 q13, q3, d11[0] \n" "vmla.f32 q15, q3, d11[1] \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" "vmla.f32 q8, q0, d12[0] \n" "vmla.f32 q10, q0, d12[1] \n" "vmla.f32 q12, q0, d13[0] \n" "vmla.f32 q14, q0, d13[1] \n" "vmla.f32 q9, q1, d12[0] \n" "vmla.f32 q11, q1, d12[1] \n" "vmla.f32 q13, q1, d13[0] \n" "vmla.f32 q15, q1, d13[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q2, d14[0] \n" "vmla.f32 q10, q2, d14[1] \n" "vmla.f32 q12, q2, d15[0] \n" "vmla.f32 q14, q2, d15[1] \n" "vmla.f32 q9, q3, d14[0] \n" "vmla.f32 q11, q3, d14[1] \n" "vmla.f32 q13, q3, d15[0] \n" "vmla.f32 q15, q3, d15[1] \n" "bne 0b \n" "vst1.f32 {d16-d19}, [%1]! \n" "vst1.f32 {d20-d23}, [%2]! \n" "vst1.f32 {d24-d27}, [%3]! \n" "vst1.f32 {d28-d31}, [%4]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ } for (; i + 3 < tiles; i += 4) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4); #endif const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v9.4s, v0.4s, v4.s[1] \n" "fmla v10.4s, v0.4s, v4.s[2] \n" "fmla v11.4s, v0.4s, v4.s[3] \n" "fmla v8.4s, v1.4s, v5.s[0] \n" "fmla v9.4s, v1.4s, v5.s[1] \n" "fmla v10.4s, v1.4s, v5.s[2] \n" "fmla v11.4s, v1.4s, v5.s[3] \n" "fmla v8.4s, v2.4s, v6.s[0] \n" "fmla v9.4s, v2.4s, v6.s[1] \n" "fmla v10.4s, v2.4s, v6.s[2] \n" "fmla v11.4s, v2.4s, v6.s[3] \n" "fmla v8.4s, v3.4s, v7.s[0] \n" "fmla v9.4s, v3.4s, v7.s[1] \n" "fmla v10.4s, v3.4s, v7.s[2] \n" "fmla v11.4s, v3.4s, v7.s[3] \n" "bne 0b \n" "st1 {v8.4s}, [%1], #16 \n" "st1 {v9.4s}, [%2], #16 \n" "st1 {v10.4s}, [%3], #16 \n" "st1 {v11.4s}, [%4], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"); #else // __aarch64__ asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" "pld [%6, #512] \n" "vldm %6!, {d8-d15} \n" "vmla.f32 q8, q0, d8[0] \n" "vmla.f32 q9, q0, d8[1] \n" "vmla.f32 q10, q0, d9[0] \n" "vmla.f32 q11, q0, d9[1] \n" "vmla.f32 q8, q1, d10[0] \n" "vmla.f32 q9, q1, d10[1] \n" "vmla.f32 q10, q1, d11[0] \n" "vmla.f32 q11, q1, d11[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q2, d12[0] \n" "vmla.f32 q9, q2, d12[1] \n" "vmla.f32 q10, q2, d13[0] \n" "vmla.f32 q11, q2, d13[1] \n" "vmla.f32 q8, q3, d14[0] \n" "vmla.f32 q9, q3, d14[1] \n" "vmla.f32 q10, q3, d15[0] \n" "vmla.f32 q11, q3, d15[1] \n" "bne 0b \n" "vst1.f32 {d16-d17}, [%1]! \n" "vst1.f32 {d18-d19}, [%2]! \n" "vst1.f32 {d20-d21}, [%3]! \n" "vst1.f32 {d22-d23}, [%4]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"); #endif // __aarch64__ } for (; i < tiles; i++) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); #endif const float* kptr = kernel01_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "0: \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "prfm pldl1keep, [%6, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[1] \n" "fmla v10.4s, v6.4s, v0.s[2] \n" "fmla v11.4s, v7.4s, v0.s[3] \n" "bne 0b \n" "fadd v8.4s, v8.4s, v9.4s \n" "fadd v10.4s, v10.4s, v11.4s \n" "fadd v8.4s, v8.4s, v10.4s \n" "st1 {v8.s}[0], [%1], #4 \n" "st1 {v8.s}[1], [%2], #4 \n" "st1 {v8.s}[2], [%3], #4 \n" "st1 {v8.s}[3], [%4], #4 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"); #else // __aarch64__ asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5]! \n" "pld [%6, #512] \n" "vldm %6!, {d8-d15} \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q5, d0[1] \n" "vmla.f32 q10, q6, d1[0] \n" "vmla.f32 q11, q7, d1[1] \n" "bne 0b \n" "vadd.f32 q8, q8, q9 \n" "vadd.f32 q10, q10, q11 \n" "vadd.f32 q8, q8, q10 \n" "vst1.f32 {d16[0]}, [%1]! \n" "vst1.f32 {d16[1]}, [%2]! \n" "vst1.f32 {d17[0]}, [%3]! \n" "vst1.f32 {d17[1]}, [%4]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(kptr) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(kptr) : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"); #endif // __aarch64__ } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); #if __aarch64__ const Mat kernel0_tm = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4); #else const Mat kernel0_tm = kernel_tm.channel(p / 4 + p % 4); #endif for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* kptr = kernel0_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v5.16b, v5.16b, v5.16b \n" "eor v6.16b, v6.16b, v6.16b \n" "eor v7.16b, v7.16b, v7.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.4s}, [%3], #16 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v9.4s, v1.4s, v4.s[0] \n" "fmla v10.4s, v2.4s, v4.s[0] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%2], #64 \n" "fmla v5.4s, v3.4s, v4.s[1] \n" "fmla v6.4s, v12.4s, v4.s[1] \n" "fmla v7.4s, v13.4s, v4.s[1] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%2], #64 \n" "fmla v8.4s, v14.4s, v4.s[2] \n" "fmla v9.4s, v15.4s, v4.s[2] \n" "fmla v10.4s, v16.4s, v4.s[2] \n" "fmla v5.4s, v17.4s, v4.s[3] \n" "fmla v6.4s, v18.4s, v4.s[3] \n" "fmla v7.4s, v19.4s, v4.s[3] \n" "bne 0b \n" "fadd v8.4s, v8.4s, v5.4s \n" "fadd v9.4s, v9.4s, v6.4s \n" "fadd v10.4s, v10.4s, v7.4s \n" "st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"); } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8); #else const float* r0 = bb2.row(i / 8); #endif const float* kptr = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.4s}, [%3], #16 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v9.4s, v1.4s, v4.s[0] \n" "fmla v10.4s, v2.4s, v4.s[1] \n" "fmla v11.4s, v3.4s, v4.s[1] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%2], #64 \n" "fmla v8.4s, v12.4s, v4.s[2] \n" "fmla v9.4s, v13.4s, v4.s[2] \n" "fmla v10.4s, v14.4s, v4.s[3] \n" "fmla v11.4s, v15.4s, v4.s[3] \n" "bne 0b \n" "fadd v8.4s, v8.4s, v10.4s \n" "fadd v9.4s, v9.4s, v11.4s \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); #else // __aarch64__ asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #128] \n" "vld1.f32 {d8-d9}, [%3]! \n" "vmla.f32 q8, q0, d8[0] \n" "vmla.f32 q9, q1, d8[0] \n" "vmla.f32 q10, q2, d8[1] \n" "vmla.f32 q11, q3, d8[1] \n" "pld [%2, #512] \n" "vldm %2!, {d24-d31} \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q12, d9[0] \n" "vmla.f32 q9, q13, d9[0] \n" "vmla.f32 q10, q14, d9[1] \n" "vmla.f32 q11, q15, d9[1] \n" "bne 0b \n" "vadd.f32 q8, q8, q10 \n" "vadd.f32 q9, q9, q11 \n" "vst1.f32 {d16-d19}, [%1]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ } for (; i + 3 < tiles; i += 4) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4); #endif const float* kptr = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.4s}, [%3], #16 \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v9.4s, v1.4s, v4.s[1] \n" "fmla v10.4s, v2.4s, v4.s[2] \n" "fmla v11.4s, v3.4s, v4.s[3] \n" "bne 0b \n" "fadd v8.4s, v8.4s, v9.4s \n" "fadd v10.4s, v10.4s, v11.4s \n" "fadd v8.4s, v8.4s, v10.4s \n" "st1 {v8.4s}, [%1], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11"); #else // __aarch64__ asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #128] \n" "vld1.f32 {d8-d9}, [%3]! \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q0, d8[0] \n" "vmla.f32 q9, q1, d8[1] \n" "vmla.f32 q10, q2, d9[0] \n" "vmla.f32 q11, q3, d9[1] \n" "bne 0b \n" "vadd.f32 q8, q8, q9 \n" "vadd.f32 q10, q10, q11 \n" "vadd.f32 q8, q8, q10 \n" "vst1.f32 {d16-d17}, [%1]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11"); #endif // __aarch64__ } for (; i < tiles; i++) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); #endif const float* kptr = kernel0_tm.row(r); float32x4_t _sum0 = vdupq_n_f32(0.f); for (int q = 0; q < inch; q++) { float32x4_t _r0 = vld1q_f32(r0); float32x4_t _k0 = vld1q_f32(kptr); _sum0 = vmlaq_f32(_sum0, _r0, _k0); kptr += 4; r0 += 4; } #if __aarch64__ float sum0 = vaddvq_f32(_sum0); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss2 = vpadd_f32(_ss, _ss); float sum0 = vget_lane_f32(_ss2, 0); #endif output0_tm[0] = sum0; output0_tm++; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 2u, 1, opt.workspace_allocator); } { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; // float32x2_t _bias0 = vdup_n_f32(bias0); float tmp[6][8]; // tile for (int i = 0; i < outh / 6; i++) { for (int j = 0; j < outw / 6; j++) { // top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator); const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm / 8 + j) * 1; const float* output0_tm_1 = output0_tm_0 + tiles * 1; const float* output0_tm_2 = output0_tm_0 + tiles * 2; const float* output0_tm_3 = output0_tm_0 + tiles * 3; const float* output0_tm_4 = output0_tm_0 + tiles * 4; const float* output0_tm_5 = output0_tm_0 + tiles * 5; const float* output0_tm_6 = output0_tm_0 + tiles * 6; const float* output0_tm_7 = output0_tm_0 + tiles * 7; // TODO neon optimize for (int m = 0; m < 8; m++) { float tmp024a = output0_tm_1[0] + output0_tm_2[0]; float tmp135a = output0_tm_1[0] - output0_tm_2[0]; float tmp024b = output0_tm_3[0] + output0_tm_4[0]; float tmp135b = output0_tm_3[0] - output0_tm_4[0]; float tmp024c = output0_tm_5[0] + output0_tm_6[0]; float tmp135c = output0_tm_5[0] - output0_tm_6[0]; tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm_7[0] + tmp135a + tmp135b * 32 + tmp135c; output0_tm_0 += tiles * 8; output0_tm_1 += tiles * 8; output0_tm_2 += tiles * 8; output0_tm_3 += tiles * 8; output0_tm_4 += tiles * 8; output0_tm_5 += tiles * 8; output0_tm_6 += tiles * 8; output0_tm_7 += tiles * 8; } unsigned short* output0 = out0.row<unsigned short>(i * 6) + j * 6; for (int m = 0; m < 6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = float32_to_bfloat16(bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32); output0[2] = float32_to_bfloat16(bias0 + tmp024a + tmp024b * 4 + tmp024c * 8); output0[4] = float32_to_bfloat16(bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c); output0[1] = float32_to_bfloat16(bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16); output0[3] = float32_to_bfloat16(bias0 + tmp135a + tmp135b * 8 + tmp135c * 4); output0[5] = float32_to_bfloat16(bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c); output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
GB_binop__rminus_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__rminus_uint32 // A.*B function (eWiseMult): GB_AemultB__rminus_uint32 // A*D function (colscale): GB_AxD__rminus_uint32 // D*A function (rowscale): GB_DxB__rminus_uint32 // C+=B function (dense accum): GB_Cdense_accumB__rminus_uint32 // C+=b function (dense accum): GB_Cdense_accumb__rminus_uint32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rminus_uint32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rminus_uint32 // C=scalar+B GB_bind1st__rminus_uint32 // C=scalar+B' GB_bind1st_tran__rminus_uint32 // C=A+scalar GB_bind2nd__rminus_uint32 // C=A'+scalar GB_bind2nd_tran__rminus_uint32 // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (y - x) ; // 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_RMINUS || GxB_NO_UINT32 || GxB_NO_RMINUS_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__rminus_uint32 ( 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__rminus_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__rminus_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__rminus_uint32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__rminus_uint32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__rminus_uint32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__rminus_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__rminus_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__rminus_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)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t bij = Bx [p] ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rminus_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 ; uint32_t y = (*((uint32_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] = (y - aij) ; } 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) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB_bind1st_tran__rminus_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 \ uint32_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] = (y - aij) ; \ } GrB_Info GB_bind2nd_tran__rminus_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 uint32_t y = (*((const uint32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
trmv_c_csr_u_hi_conj.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include<stdlib.h> static alphasparse_status_t trmv_x_csr_u_hi_conj_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mule(y[i], beta); alpha_madde(y[i], alpha, x[i]); } ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT); for(ALPHA_INT i = 0; i < num_threads; i++) { y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); memset(y_local[i], '\0', sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_Number tmp; for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col <= i) { continue; } else { alpha_setzero(tmp); cmp_conj(tmp, A->values[ai]); alpha_mul(tmp, alpha, tmp); alpha_madde(y_local[tid][col], tmp, x[i]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT row = 0; row < m; row++) for(ALPHA_INT i = 0; i < num_threads; i++) alpha_adde(y[row], y_local[i][row]); for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_free(y_local[i]); } alpha_free(y_local); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return trmv_x_csr_u_hi_conj_omp(alpha, A, x, beta, y); }
GB_unaryop__identity_uint32_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_uint32_fp64 // op(A') function: GB_tran__identity_uint32_fp64 // C type: uint32_t // A type: double // cast: uint32_t cij ; GB_CAST_UNSIGNED(cij,aij,32) // unaryop: cij = aij #define GB_ATYPE \ double #define GB_CTYPE \ uint32_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, aij) \ uint32_t z ; GB_CAST_UNSIGNED(z,aij,32) ; // 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_UINT32 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint32_fp64 ( uint32_t *Cx, // Cx and Ax may be aliased double *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_uint32_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nodal_residualbased_block_builder_and_solver.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // // #if !defined(KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER) #define KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* #include <unordered_set> */ /* #ifdef USE_GOOGLE_HASH */ /* #include "sparsehash/dense_hash_set" //included in external libraries */ /* #endif */ #ifdef USE_GOOGLE_HASH #include "sparsehash/dense_hash_set" //included in external libraries #else #include <unordered_set> #endif /* Project includes */ #include "utilities/timer.h" #include "includes/define.h" #include "includes/key_hash.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "utilities/openmp_utils.h" #include "includes/kratos_flags.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class NodalResidualBasedBlockBuilderAndSolver * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @author Riccardo Rossi */ template <class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class NodalResidualBasedBlockBuilderAndSolver : public BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedBlockBuilderAndSolver); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef Node<3> NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef Vector VectorType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ NodalResidualBasedBlockBuilderAndSolver( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pNewLinearSystemSolver) { } /** Destructor. */ ~NodalResidualBasedBlockBuilderAndSolver() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Function to perform the build of the RHS. The vector could be sized as the total number * of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param b The RHS vector */ void Build( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) override { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; // Getting the elements from the model const int nelements = static_cast<int>(rModelPart.Elements().size()); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements // double start_build = OpenMPUtils::GetCurrentTime(); #pragma omp parallel firstprivate(nelements, nconditions, LHS_Contribution, RHS_Contribution, EquationId) { #pragma omp for schedule(guided, 512) nowait for (int k = 0; k < nelements; k++) { ModelPart::ElementsContainerType::iterator it = el_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if ((it)->IsDefined(ACTIVE)) element_is_active = (it)->Is(ACTIVE); if (element_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } //#pragma omp parallel for firstprivate(nconditions, LHS_Contribution, RHS_Contribution, EquationId ) schedule(dynamic, 1024) #pragma omp for schedule(guided, 512) for (int k = 0; k < nconditions; k++) { ModelPart::ConditionsContainerType::iterator it = cond_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if ((it)->IsDefined(ACTIVE)) condition_is_active = (it)->Is(ACTIVE); if (condition_is_active) { //calculate elemental contribution pScheme->Condition_CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } // const double stop_build = OpenMPUtils::GetCurrentTime(); // KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Build time: " << stop_build - start_build << std::endl; //for (int i = 0; i < A_size; i++) // omp_destroy_lock(&lock_array[i]); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl; KRATOS_CATCH("") } void BuildNodally( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; std::cout << "Build Nodally Continuity Equation" << std::endl; //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); /* const double start_build = OpenMPUtils::GetCurrentTime(); */ /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { VectorType nodalSFDneighboursId = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); const unsigned int neighSize = nodalSFDneighboursId.size(); if (neighSize > 1) { const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; noalias(LHS_Contribution) = ZeroMatrix(neighSize, neighSize); noalias(RHS_Contribution) = ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double volumetricCoeff = itNode->FastGetSolutionStepValue(VOLUMETRIC_COEFFICIENT) + 2.0 * deviatoricCoeff / 3.0; const unsigned int xpos = itNode->GetDofPosition(VELOCITY_X); double deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); double volumetricDefRate = itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += (-deltaPressure / volumetricCoeff + volumetricDefRate) * nodalVolume; bool stabilizationNeeded = false; if ((itNode->Is(FLUID) || (itNode->Is(SOLID) && itNode->FastGetSolutionStepValue(POISSON_RATIO) > 0.49999))) { stabilizationNeeded = true; } else { for (unsigned int i = 0; i < neighSize; i++) { unsigned int idNode = nodalSFDneighboursId[i]; EquationId[i] = rModelPart.Nodes()[idNode].GetDof(PRESSURE, xpos).EquationId(); } } if (stabilizationNeeded == true) { /* Vector& rNodalSFDneigh = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS); */ unsigned int firstRow = 0; unsigned int firstCol = 0; double meanMeshSize = itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); double characteristicLength = 2.0 * meanMeshSize; /* double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); */ double density = itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ double nodalVelocity = 0; if (dimension == 2) { nodalVelocity = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if (dimension == 3) { nodalVelocity = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z) * itNode->FastGetSolutionStepValue(VELOCITY_Z)); } double tauStab = 1.0 * (characteristicLength * characteristicLength * timeInterval) / (density * nodalVelocity * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval); /* tauStab*=10.0; */ /* tauStab=0.0000001; */ /* tauStab=100.0; */ LHS_Contribution(0, 0) += +nodalVolume * tauStab * density / (volumetricCoeff * timeInterval); RHS_Contribution[0] += -nodalVolume * tauStab * density / (volumetricCoeff * timeInterval) * (deltaPressure - itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) * timeInterval); if (itNode->Is(FREE_SURFACE)) { /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ /* double boundLHScontribution=4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); */ /* std::cout<<"boundLHScontribution "<<boundLHScontribution<<std::endl; */ /* if(itNode->IsNot(RIGID)){ */ LHS_Contribution(0, 0) += +4.0 * 2.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += -4.0 * 2.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE, 0); /* } */ /* else { */ /* LHS_Contribution(0,0) += + 4.0/3.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); */ /* RHS_Contribution[0] += - 4.0/3.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); */ /* } */ const array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector &SpatialDefRate = itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration = 0.5 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration = 0; double nodalNormalProjDefRate = 0; if (dimension == 2) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + 2 * Normal[0] * SpatialDefRate[2] * Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ /* nodalNormalAcceleration=(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))*Normal[0]/timeInterval + */ /* (itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))*Normal[1]/timeInterval; */ nodalNormalAcceleration = Normal[0] * nodalAcceleration[0] + Normal[1] * nodalAcceleration[1]; } else if (dimension == 3) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + Normal[2] * SpatialDefRate[2] * Normal[2] + 2 * Normal[0] * SpatialDefRate[3] * Normal[1] + 2 * Normal[0] * SpatialDefRate[4] * Normal[2] + 2 * Normal[1] * SpatialDefRate[5] * Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } /* RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; */ double accelerationContribution = 2.0 * density * nodalNormalAcceleration / meanMeshSize; double deviatoricContribution = 8.0 * deviatoricCoeff * nodalNormalProjDefRate / (meanMeshSize * meanMeshSize); /* std::cout<<"nodalNormalAcceleration= "<<nodalNormalAcceleration<<std::endl; */ /* std::cout<<"nodalNormalProjDefRate= "<<nodalNormalProjDefRate<<std::endl; */ /* std::cout<<"meanMeshSize "<<meanMeshSize<<std::endl; */ /* accelerationContribution=0; */ /* deviatoricContribution=0; */ /* if(itNode->IsNot(RIGID)){ */ RHS_Contribution[0] += 2.0 * tauStab * (accelerationContribution + deviatoricContribution) * nodalVolume; /* }else{ */ /* RHS_Contribution[0] += 1.0/3.0* tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; */ /* } */ } for (unsigned int i = 0; i < neighSize; i++) { unsigned int idNode = nodalSFDneighboursId[i]; EquationId[i] = rModelPart.Nodes()[idNode].GetDof(PRESSURE, xpos).EquationId(); double Density = rModelPart.Nodes()[idNode].FastGetSolutionStepValue(DENSITY); array_1d<double, 3> &VolumeAcceleration = rModelPart.Nodes()[idNode].FastGetSolutionStepValue(VOLUME_ACCELERATION); double dNdXi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; double dNdYi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 1]; double dNdZi = 0; if (dimension == 2) { RHS_Contribution[i] += -tauStab * Density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1]) * nodalVolume; } else if (dimension == 3) { dNdZi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 2]; RHS_Contribution[i] += -tauStab * Density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1] + dNdZi * VolumeAcceleration[2]) * nodalVolume; } firstRow = 0; for (unsigned int j = 0; j < neighSize; j++) { unsigned int idNodeJ = nodalSFDneighboursId[j]; double dNdXj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; double dNdYj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 1]; if (dimension == 2) { ////////////////// Laplacian term for LHS LHS_Contribution(i, j) += +tauStab * (dNdXi * dNdXj + dNdYi * dNdYj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += -tauStab * (dNdXi * dNdXj + dNdYi * dNdYj) * nodalVolume * rModelPart.Nodes()[idNodeJ].FastGetSolutionStepValue(PRESSURE, 0); } else if (dimension == 3) { double dNdZj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 2]; ////////////////// Laplacian term for LHS LHS_Contribution(i, j) += +tauStab * (dNdXi * dNdXj + dNdYi * dNdYj + dNdZi * dNdZj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += -tauStab * (dNdXi * dNdXj + dNdYi * dNdYj + dNdZi * dNdZj) * nodalVolume * rModelPart.Nodes()[idNodeJ].FastGetSolutionStepValue(PRESSURE, 0); } /* std::cout << "dNdXi= " <<dNdXi<< "dNdYi= " <<dNdYi<< "dNdYj= " <<dNdYj<< "dNdXj= " <<dNdXj<< std::endl; */ firstRow += dimension; } firstCol += dimension; } } //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif /* AssembleLHS(A, LHS_Contribution, EquationId); */ /* AssembleRHS(b, RHS_Contribution, EquationId); */ } } } /* /\* std::cout<<".... Build Nodally Continuity Equation DONE!"<<std::endl; *\/ */ /* const double stop_build = OpenMPUtils::GetCurrentTime(); */ /* KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Build time: " << stop_build - start_build << std::endl; */ /* //for (int i = 0; i < A_size; i++) */ /* // omp_destroy_lock(&lock_array[i]); */ /* KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl; */ KRATOS_CATCH("") } /** * @brief Function to perform the building of the LHS * @details Depending on the implementation choosen the size of the matrix could * be equal to the total number of Dofs or to the number of unrestrained dofs * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A) override { KRATOS_TRY TSystemVectorType tmp(A.size1(), 0.0); this->Build(pScheme, rModelPart, A, tmp); KRATOS_CATCH("") } /** * @brief Build a rectangular matrix of size n*N where "n" is the number of unrestrained degrees of freedom * and "N" is the total number of degrees of freedom involved. * @details This matrix is obtained by building the total matrix without the lines corresponding to the fixed * degrees of freedom (but keeping the columns!!) * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS_CompleteOnFreeRows( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A) override { KRATOS_TRY TSystemVectorType tmp(A.size1(), 0.0); this->Build(pScheme, rModelPart, A, tmp); KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); //prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b, ModelPart &rModelPart) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if (BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded()) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING("NodalResidualBasedBlockBuilderAndSolver") << "ATTENTION! setting the RHS to zero!" << std::endl; } //prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY std::cout << "CONTINUITY EQ: buildAndSolve " << std::endl; Timer::Start("Build"); /* Build(pScheme, rModelPart, A, b); */ //boost::timer build_time; BuildNodally(pScheme, rModelPart, A, b); //std::cout << "CONTINUITY EQ: build_time : " << build_time.elapsed() << std::endl; Timer::Stop("Build"); ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; // const double start_solve = OpenMPUtils::GetCurrentTime(); // Timer::Start("Solve"); //boost::timer solve_time; SystemSolveWithPhysics(A, Dx, b, rModelPart); //std::cout << "CONTINUITY EQ: solve_time : " << solve_time.elapsed() << std::endl; // Timer::Stop("Solve"); // const double stop_solve = OpenMPUtils::GetCurrentTime(); // KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } /** * @brief Corresponds to the previews, but the System's matrix is considered already built and only the RHS is built again * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildRHSAndSolve( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY BuildRHS(pScheme, rModelPart, b); SystemSolve(A, Dx, b); KRATOS_CATCH("") } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemVectorType &b) override { KRATOS_TRY BuildRHSNoDirichlet(pScheme, rModelPart, b); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k < ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; const std::size_t i = dof_iterator->EquationId(); if (dof_iterator->IsFixed()) b[i] = 0.0f; } KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart) override { KRATOS_TRY; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType &pElements = rModelPart.Elements(); const int nelements = static_cast<int>(pElements.size()); Element::DofsVectorType ElementalDofList; ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); unsigned int nthreads = ParallelUtilities::GetNumThreads(); // typedef boost::fast_pool_allocator< NodeType::DofType::Pointer > allocator_type; // typedef std::unordered_set < NodeType::DofType::Pointer, // DofPointerHasher, // DofPointerComparor, // allocator_type > set_type; #ifdef USE_GOOGLE_HASH typedef google::dense_hash_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #else typedef std::unordered_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #endif // std::vector<set_type> dofs_aux_list(nthreads); // std::vector<allocator_type> allocators(nthreads); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Number of threads" << nthreads << "\n" << std::endl; for (int i = 0; i < static_cast<int>(nthreads); i++) { #ifdef USE_GOOGLE_HASH dofs_aux_list[i].set_empty_key(NodeType::DofType::Pointer()); #else // dofs_aux_list[i] = set_type( allocators[i]); dofs_aux_list[i].reserve(nelements); #endif } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Initializing element loop" << std::endl; #pragma omp parallel firstprivate(nelements, ElementalDofList) { #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < nelements; i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetElementalDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Initializing condition loop" << std::endl; ConditionsArrayType &pConditions = rModelPart.Conditions(); const int nconditions = static_cast<int>(pConditions.size()); #pragma omp for schedule(guided, 512) for (int i = 0; i < nconditions; i++) { typename ConditionsArrayType::iterator it = pConditions.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Initializing tree reduction\n" << std::endl; // Here we do a reduction in a tree so to have everything on thread 0 unsigned int old_max = nthreads; unsigned int new_max = ceil(0.5 * static_cast<double>(old_max)); while (new_max >= 1 && new_max != old_max) { if (this->GetEchoLevel() > 2) { //just for debugging std::cout << "old_max" << old_max << " new_max:" << new_max << std::endl; for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { std::cout << i << " - " << i + new_max << std::endl; } } std::cout << "********************" << std::endl; } #pragma omp parallel for for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { dofs_aux_list[i].insert(dofs_aux_list[i + new_max].begin(), dofs_aux_list[i + new_max].end()); dofs_aux_list[i + new_max].clear(); } } old_max = new_max; new_max = ceil(0.5 * static_cast<double>(old_max)); } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl; DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dofs_aux_list[0].size()); for (auto it = dofs_aux_list[0].begin(); it != dofs_aux_list[0].end(); it++) { Doftemp.push_back((*it)); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; //Throws an exception if there are no Degrees Of Freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "Initializing lock array" << std::endl; #ifdef _OPENMP if (mlock_array.size() != 0) { for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) { omp_destroy_lock(&mlock_array[i]); } } mlock_array.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) { omp_init_lock(&mlock_array[i]); } #endif KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2)) << "End of setup dof set\n" << std::endl; // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if (BaseType::GetCalculateReactionsFlag()) { for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " << std::endl << "Node : " << dof_iterator->Id() << std::endl << "Dof : " << (*dof_iterator) << std::endl << "Not possible to calculate reactions." << std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart &rModelPart) override { //int free_id = 0; BaseType::mEquationSystemSize = BaseType::mDofSet.size(); int ndofs = static_cast<int>(BaseType::mDofSet.size()); #pragma omp parallel for firstprivate(ndofs) for (int i = 0; i < static_cast<int>(ndofs); i++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + i; dof_iterator->SetEquationId(i); } //for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) // dof_iterator->SetEquationId(free_id++); } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType &pA, TSystemVectorPointerType &pDx, TSystemVectorPointerType &pb, ModelPart &rModelPart) override { KRATOS_TRY //boost::timer contruct_matrix; if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } TSystemMatrixType &A = *pA; TSystemVectorType &Dx = *pDx; TSystemVectorType &b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH(" it should not come here!!!!!!!! ... this is SLOW"); KRATOS_ERROR << "The equation system size has changed during the simulation. This is not permited." << std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //std::cout << "CONTINUITY EQ: contruct_matrix : " << contruct_matrix.elapsed() << std::endl; KRATOS_CATCH("") } //************************************************************************** //************************************************************************** void InitializeSolutionStep( ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY std::cout << "Initialize Solution Step in nodal res based " << std::endl; KRATOS_CATCH("") } //************************************************************************** //************************************************************************** void FinalizeSolutionStep( ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { } //************************************************************************** //************************************************************************** void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { TSparseSpace::SetToZero(b); //refresh RHS to have the correct reactions BuildRHSNoDirichlet(pScheme, rModelPart, b); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k < ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; const int i = (dof_iterator)->EquationId(); (dof_iterator)->GetSolutionStepReactionValue() = -b[i]; } //KRATOS_WATCH(__LINE__) } /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { std::size_t system_size = A.size1(); std::vector<double> scaling_factors(system_size, 0.0f); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k < ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; if (dof_iterator->IsFixed()) scaling_factors[k] = 0.0f; else scaling_factors[k] = 1.0f; } double *Avalues = A.value_data().begin(); std::size_t *Arow_indices = A.index1_data().begin(); std::size_t *Acol_indices = A.index2_data().begin(); //detect if there is a line of all zeros and set the diagonal to a 1 if this happens #pragma omp parallel for firstprivate(system_size) for (int k = 0; k < static_cast<int>(system_size); ++k) { std::size_t col_begin = Arow_indices[k]; std::size_t col_end = Arow_indices[k + 1]; bool empty = true; for (std::size_t j = col_begin; j < col_end; ++j) { if (Avalues[j] != 0.0) { empty = false; break; } } if (empty == true) { A(k, k) = 1.0; b[k] = 0.0; } } #pragma omp parallel for for (int k = 0; k < static_cast<int>(system_size); ++k) { std::size_t col_begin = Arow_indices[k]; std::size_t col_end = Arow_indices[k + 1]; double k_factor = scaling_factors[k]; if (k_factor == 0) { // zero out the whole row, except the diagonal for (std::size_t j = col_begin; j < col_end; ++j) if (static_cast<int>(Acol_indices[j]) != k) Avalues[j] = 0.0; // zero out the RHS b[k] = 0.0; } else { // zero out the column which is associated with the zero'ed row for (std::size_t j = col_begin; j < col_end; ++j) if (scaling_factors[Acol_indices[j]] == 0) Avalues[j] = 0.0; } } } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { #ifdef _OPENMP for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_destroy_lock(&mlock_array[i]); mlock_array.resize(0); #endif BaseType::Clear(); } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart &rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ #ifdef _OPENMP std::vector<omp_lock_t> mlock_array; #endif ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType &A, ModelPart &rModelPart) { std::cout << " ConstructMatrixStructure for Continuity equation " << std::endl; //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); const std::size_t equation_size = BaseType::mEquationSystemSize; #ifdef USE_GOOGLE_HASH std::vector<google::dense_hash_set<std::size_t>> indices(equation_size); const std::size_t empty_key = 2 * equation_size + 10; #else std::vector<std::unordered_set<std::size_t>> indices(equation_size); #endif #pragma omp parallel for firstprivate(equation_size) for (int iii = 0; iii < static_cast<int>(equation_size); iii++) { #ifdef USE_GOOGLE_HASH indices[iii].set_empty_key(empty_key); #else indices[iii].reserve(40); #endif } Element::EquationIdVectorType EquationId; /* #pragma omp parallel */ /* { */ ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { /* VectorType nodalSFDneighboursId=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); */ /* const unsigned int neighSize = nodalSFDneighboursId.size(); */ const unsigned int neighSize = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER).size(); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); /* const unsigned int xpos = itNode->GetDofPosition(VELOCITY_X); */ const unsigned int xpos = itNode->GetDofPosition(PRESSURE); for (unsigned int i = 0; i < neighSize; i++) { /* unsigned int idNode=nodalSFDneighboursId[i]; */ unsigned int idNode = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER)[i]; EquationId[i] = rModelPart.Nodes()[idNode].GetDof(PRESSURE, xpos).EquationId(); } for (std::size_t i = 0; i < EquationId.size(); i++) { if (EquationId[i] < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&mlock_array[EquationId[i]]); #endif auto &row_indices = indices[EquationId[i]]; for (auto it = EquationId.begin(); it != EquationId.end(); it++) { if (*it < BaseType::mEquationSystemSize) row_indices.insert(*it); } #ifdef _OPENMP omp_unset_lock(&mlock_array[EquationId[i]]); #endif } } /* for (std::size_t i = 0; i < EquationId.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[EquationId[i]]); */ /* #endif */ /* auto& row_indices = indices[EquationId[i]]; */ /* row_indices.insert(EquationId.begin(), EquationId.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[EquationId[i]]); */ /* #endif */ /* } */ } /* } */ Element::EquationIdVectorType ids(3, 0); #pragma omp parallel for firstprivate(nconditions, ids) for (int iii = 0; iii < nconditions; iii++) { typename ConditionsArrayType::iterator i_condition = cond_begin + iii; pScheme->Condition_EquationId(*(i_condition.base()), ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) { #ifdef _OPENMP omp_set_lock(&mlock_array[ids[i]]); #endif auto &row_indices = indices[ids[i]]; row_indices.insert(ids.begin(), ids.end()); #ifdef _OPENMP omp_unset_lock(&mlock_array[ids[i]]); #endif } } //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) nnz += indices[i].size(); A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); double *Avalues = A.value_data().begin(); std::size_t *Arow_indices = A.index1_data().begin(); std::size_t *Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) Arow_indices[i + 1] = Arow_indices[i] + indices[i].size(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(A.size1()); i++) { const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i + 1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } indices[i].clear(); //deallocating the memory std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); } A.set_filled(indices.size() + 1, nnz); Timer::Stop("MatrixStructure"); /* std::cout<<"..... ConstructMatrixStructure for Continuity equation DONE"<<std::endl; */ } /* virtual void ConstructMatrixStructure( */ /* typename TSchemeType::Pointer pScheme, */ /* TSystemMatrixType& A, */ /* ModelPart& rModelPart) */ /* { */ /* //filling with zero the matrix (creating the structure) */ /* Timer::Start("MatrixStructure"); */ /* // Getting the elements from the model */ /* const int nelements = static_cast<int>(rModelPart.Elements().size()); */ /* // Getting the array of the conditions */ /* const int nconditions = static_cast<int>(rModelPart.Conditions().size()); */ /* ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); */ /* ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); */ /* ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); */ /* const std::size_t equation_size = BaseType::mEquationSystemSize; */ /* #ifdef USE_GOOGLE_HASH */ /* std::vector<google::dense_hash_set<std::size_t> > indices(equation_size); */ /* const std::size_t empty_key = 2*equation_size + 10; */ /* #else */ /* std::vector<std::unordered_set<std::size_t> > indices(equation_size); */ /* #endif */ /* #pragma omp parallel for firstprivate(equation_size) */ /* for (int iii = 0; iii < static_cast<int>(equation_size); iii++) */ /* { */ /* #ifdef USE_GOOGLE_HASH */ /* indices[iii].set_empty_key(empty_key); */ /* #else */ /* indices[iii].reserve(40); */ /* #endif */ /* } */ /* Element::EquationIdVectorType ids(3, 0); */ /* #pragma omp parallel for firstprivate(nelements, ids) */ /* for(int iii=0; iii<nelements; iii++) */ /* { */ /* typename ElementsContainerType::iterator i_element = el_begin + iii; */ /* pScheme->EquationId( *(i_element.base()) , ids, CurrentProcessInfo); */ /* for (std::size_t i = 0; i < ids.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[ids[i]]); */ /* #endif */ /* auto& row_indices = indices[ids[i]]; */ /* row_indices.insert(ids.begin(), ids.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[ids[i]]); */ /* #endif */ /* } */ /* } */ /* #pragma omp parallel for firstprivate(nconditions, ids) */ /* for (int iii = 0; iii<nconditions; iii++) */ /* { */ /* typename ConditionsArrayType::iterator i_condition = cond_begin + iii; */ /* pScheme->Condition_EquationId( *(i_condition.base()), ids, CurrentProcessInfo); */ /* for (std::size_t i = 0; i < ids.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[ids[i]]); */ /* #endif */ /* auto& row_indices = indices[ids[i]]; */ /* row_indices.insert(ids.begin(), ids.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[ids[i]]); */ /* #endif */ /* } */ /* } */ /* //count the row sizes */ /* unsigned int nnz = 0; */ /* for (unsigned int i = 0; i < indices.size(); i++) */ /* nnz += indices[i].size(); */ /* A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); */ /* double* Avalues = A.value_data().begin(); */ /* std::size_t* Arow_indices = A.index1_data().begin(); */ /* std::size_t* Acol_indices = A.index2_data().begin(); */ /* //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! */ /* Arow_indices[0] = 0; */ /* for (int i = 0; i < static_cast<int>(A.size1()); i++) */ /* Arow_indices[i+1] = Arow_indices[i] + indices[i].size(); */ /* #pragma omp parallel for */ /* for (int i = 0; i < static_cast<int>(A.size1()); i++) */ /* { */ /* const unsigned int row_begin = Arow_indices[i]; */ /* const unsigned int row_end = Arow_indices[i+1]; */ /* unsigned int k = row_begin; */ /* for (auto it = indices[i].begin(); it != indices[i].end(); it++) */ /* { */ /* Acol_indices[k] = *it; */ /* Avalues[k] = 0.0; */ /* k++; */ /* } */ /* indices[i].clear(); //deallocating the memory */ /* std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); */ /* } */ /* A.set_filled(indices.size()+1, nnz); */ /* Timer::Stop("MatrixStructure"); */ /* } */ //************************************************************************** void AssembleLHS( TSystemMatrixType &A, LocalSystemMatrixType &LHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } void Assemble( TSystemMatrixType &A, TSystemVectorType &b, const LocalSystemMatrixType &LHS_Contribution, const LocalSystemVectorType &RHS_Contribution, Element::EquationIdVectorType &EquationId #ifdef USE_LOCKS_IN_ASSEMBLY , std::vector<omp_lock_t> &lock_array #endif ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; #ifdef USE_LOCKS_IN_ASSEMBLY omp_set_lock(&lock_array[i_global]); b[i_global] += RHS_Contribution(i_local); #else double &r_a = b[i_global]; const double &v_a = RHS_Contribution(i_local); #pragma omp atomic r_a += v_a; #endif AssembleRowContribution(A, LHS_Contribution, i_global, i_local, EquationId); #ifdef USE_LOCKS_IN_ASSEMBLY omp_unset_lock(&lock_array[i_global]); #endif //note that computation of reactions is not performed here! } } //************************************************************************** void AssembleRHS( TSystemVectorType &b, LocalSystemVectorType &RHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = RHS_Contribution.size(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; // ASSEMBLING THE SYSTEM VECTOR double &b_value = b[i_global]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t> &v, const std::size_t &candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } void BuildRHSNoDirichlet( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemVectorType &b) { KRATOS_TRY //Getting the Elements ElementsArrayType &pElements = rModelPart.Elements(); //getting the array of the conditions ConditionsArrayType &ConditionsArray = rModelPart.Conditions(); ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements //for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) const int nelements = static_cast<int>(pElements.size()); #pragma omp parallel firstprivate(nelements, RHS_Contribution, EquationId) { #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < nelements; i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if ((it)->IsDefined(ACTIVE)) element_is_active = (it)->Is(ACTIVE); if (element_is_active) { //calculate elemental Right Hand Side Contribution pScheme->Calculate_RHS_Contribution(*(it.base()), RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } LHS_Contribution.resize(0, 0, false); RHS_Contribution.resize(0, false); // assemble all conditions //for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) const int nconditions = static_cast<int>(ConditionsArray.size()); //#pragma omp parallel for firstprivate(nconditions, RHS_Contribution, EquationId) schedule(dynamic, 1024) #pragma omp for schedule(guided, 512) for (int i = 0; i < nconditions; i++) { auto it = ConditionsArray.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if ((it)->IsDefined(ACTIVE)) condition_is_active = (it)->Is(ACTIVE); if (condition_is_active) { //calculate elemental contribution pScheme->Condition_Calculate_RHS_Contribution(*(it.base()), RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } } KRATOS_CATCH("") } //****************************************************************************************** //****************************************************************************************** inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, vector<unsigned int> &partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } inline void AssembleRowContribution(TSystemMatrixType &A, const Matrix &Alocal, const unsigned int i, const unsigned int i_local, Element::EquationIdVectorType &EquationId) { double *values_vector = A.value_data().begin(); std::size_t *index1_vector = A.index1_data().begin(); std::size_t *index2_vector = A.index2_data().begin(); size_t left_limit = index1_vector[i]; // size_t right_limit = index1_vector[i+1]; //find the first entry size_t last_pos = ForwardFind(EquationId[0], left_limit, index2_vector); size_t last_found = EquationId[0]; #ifndef USE_LOCKS_IN_ASSEMBLY double &r_a = values_vector[last_pos]; const double &v_a = Alocal(i_local, 0); #pragma omp atomic r_a += v_a; #else values_vector[last_pos] += Alocal(i_local, 0); #endif //now find all of the other entries size_t pos = 0; for (unsigned int j = 1; j < EquationId.size(); j++) { unsigned int id_to_find = EquationId[j]; if (id_to_find > last_found) pos = ForwardFind(id_to_find, last_pos + 1, index2_vector); else pos = BackwardFind(id_to_find, last_pos - 1, index2_vector); #ifndef USE_LOCKS_IN_ASSEMBLY double &r = values_vector[pos]; const double &v = Alocal(i_local, j); #pragma omp atomic r += v; #else values_vector[pos] += Alocal(i_local, j); #endif last_found = id_to_find; last_pos = pos; } } inline unsigned int ForwardFind(const unsigned int id_to_find, const unsigned int start, const size_t *index_vector) { unsigned int pos = start; while (id_to_find != index_vector[pos]) pos++; return pos; } inline unsigned int BackwardFind(const unsigned int id_to_find, const unsigned int start, const size_t *index_vector) { unsigned int pos = start; while (id_to_find != index_vector[pos]) pos--; return pos; } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class NodalResidualBasedBlockBuilderAndSolver */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
GB_binop__min_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_int16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__min_int16) // A.*B function (eWiseMult): GB (_AemultB_03__min_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int16) // A*D function (colscale): GB (_AxD__min_int16) // D*A function (rowscale): GB (_DxB__min_int16) // C+=B function (dense accum): GB (_Cdense_accumB__min_int16) // C+=b function (dense accum): GB (_Cdense_accumb__min_int16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int16) // C=scalar+B GB (_bind1st__min_int16) // C=scalar+B' GB (_bind1st_tran__min_int16) // C=A+scalar GB (_bind2nd__min_int16) // C=A'+scalar GB (_bind2nd_tran__min_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_INT16 || GxB_NO_MIN_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__min_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__min_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__min_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_int16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__min_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__min_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__min_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__min_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = Bx [p] ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = Ax [p] ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
relu1_ref.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: bzhang@openailab.com */ #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" int ref_relu1_fp32(struct tensor* input_tensor, struct tensor* output_tensor, int num_thread) { int w = input_tensor->dims[3]; int h = output_tensor->dims[2]; int channels = input_tensor->dims[1]; int size = h * w; int c_step = h * w; float* input_data = (float*)input_tensor->data; float* out_data = (float*)output_tensor->data; #pragma omp parallel for num_threads(num_thread) for (int q = 0; q < channels; q++) { float* src = input_data + c_step * q; float* dst = out_data + c_step * q; for (int i = 0; i < size; i++) { dst[i] = src[i]; if (dst[i] > 1) dst[i] = 1; if (dst[i] < -1) dst[i] = -1; } } return 0; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct node* ir_node = exec_node->ir_node; struct graph* ir_graph = ir_node->graph; struct tensor* input_tensor; struct tensor* output_tensor; input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); ref_relu1_fp32(input_tensor, output_tensor, exec_graph->num_thread); return 0; } static int reshape(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct node* node = exec_node->ir_node; struct graph* ir_graph = node->graph; struct tensor* input = get_ir_graph_tensor(ir_graph, node->input_tensors[0]); struct tensor* output = get_ir_graph_tensor(ir_graph, node->output_tensors[0]); int ret = set_ir_tensor_shape(output, input->dims, input->dim_num); return ret; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct node* exec_node) { return OPS_SCORE_CANDO; } static struct node_ops hcl_node_ops = {.prerun = NULL, .run = run, .reshape = reshape, .postrun = NULL, .init_node = init_node, .release_node = release_node, .score = score}; int register_relu1_ref_op() { return register_builtin_node_ops(OP_RELU1, &hcl_node_ops); } int unregister_relu1_ref_op() { return unregister_builtin_node_ops(OP_RELU1, &hcl_node_ops); }
9511.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "covariance.h" /* Array initialization. */ static void init_array (int m, int n, DATA_TYPE *float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n)) { int i, j; *float_n = 1.2; for (i = 0; i < M; i++) for (j = 0; j < N; j++) data[i][j] = ((DATA_TYPE) i*j) / M; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int m, DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m)) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < m; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, symmat[i][j]); if ((i * m + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_covariance(int m, int n, DATA_TYPE float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n), DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m), DATA_TYPE POLYBENCH_1D(mean,M,m)) { int i, j, j1, j2; #pragma scop /* Determine mean of column vectors of input data matrix */ { #pragma omp target teams distribute thread_limit(64) for (j = 0; j < _PB_M; j++) { mean[j] = 0.0; for (i = 0; i < _PB_N; i++) mean[j] += data[i][j]; mean[j] /= float_n; } /* Center the column vectors. */ #pragma omp target teams distribute thread_limit(64) for (i = 0; i < _PB_N; i++) { #pragma omp target teams distribute thread_limit(64) for (j = 0; j < _PB_M; j++) { data[i][j] -= mean[j]; } } /* Calculate the m * m covariance matrix. */ #pragma omp target teams distribute thread_limit(64) for (j1 = 0; j1 < _PB_M; j1++) { #pragma omp target teams distribute thread_limit(64) for (j2 = j1; j2 < _PB_M; j2++) { symmat[j1][j2] = 0.0; for (i = 0; i < _PB_N; i++) symmat[j1][j2] += data[i][j1] * data[i][j2]; symmat[j2][j1] = symmat[j1][j2]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int n = N; int m = M; /* Variable declaration/allocation. */ DATA_TYPE float_n; POLYBENCH_2D_ARRAY_DECL(data,DATA_TYPE,M,N,m,n); POLYBENCH_2D_ARRAY_DECL(symmat,DATA_TYPE,M,M,m,m); POLYBENCH_1D_ARRAY_DECL(mean,DATA_TYPE,M,m); /* Initialize array(s). */ init_array (m, n, &float_n, POLYBENCH_ARRAY(data)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_covariance (m, n, float_n, POLYBENCH_ARRAY(data), POLYBENCH_ARRAY(symmat), POLYBENCH_ARRAY(mean)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(m, POLYBENCH_ARRAY(symmat))); /* Be clean. */ POLYBENCH_FREE_ARRAY(data); POLYBENCH_FREE_ARRAY(symmat); POLYBENCH_FREE_ARRAY(mean); return 0; }
sp.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - SP This benchmark is an OpenMP C version of the NPB SP code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. 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 OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Author: R. Van der Wijngaart W. Saphir OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ #include "npb-C.h" /* global variables */ #include "header.h" /* PMC */ #include <signal.h> #include <unistd.h> /* function declarations */ static void add(void); static void adi(void); static void error_norm(double rms[5]); static void rhs_norm(double rms[5]); static void exact_rhs(void); static void exact_solution(double xi, double eta, double zeta, double dtemp[5]); static void initialize(void); static void lhsinit(void); static void lhsx(void); static void lhsy(void); static void lhsz(void); static void ninvr(void); static void pinvr(void); static void compute_rhs(void); static void set_constants(void); static void txinvr(void); static void tzetar(void); static void verify(int no_time_steps, char *class, boolean *verified); static void x_solve(void); static void y_solve(void); static void z_solve(void); /*-------------------------------------------------------------------- program SP c-------------------------------------------------------------------*/ int main(int argc, char **argv) { int niter, step; double mflops, tmax; int nthreads = 1; boolean verified; char class; FILE *fp; /*-------------------------------------------------------------------- c Read input file (if it exists), else take c defaults from parameters c-------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - SP Benchmark\n\n"); fp = fopen("inputsp.data", "r"); if (fp != NULL) { printf(" Reading from input file inputsp.data\n"); fscanf(fp, "%d", &niter); while (fgetc(fp) != '\n'); fscanf(fp, "%lf", &dt); while (fgetc(fp) != '\n'); fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]); fclose(fp); } else { printf(" No input file inputsp.data. Using compiled defaults"); niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; } printf(" Size: %3dx%3dx%3d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %3d dt: %10.6f\n", niter, dt); if ( (grid_points[0] > IMAX) || (grid_points[1] > JMAX) || (grid_points[2] > KMAX) ) { printf("%d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); exit(1); } set_constants(); initialize(); lhsinit(); exact_rhs(); /*-------------------------------------------------------------------- c do one time step to touch all code, and reinitialize c-------------------------------------------------------------------*/ adi(); initialize(); timer_clear(1); //PMC long cpid = getpid(); if(argc>=2){ printf("PID:%ld \n",cpid); kill(cpid, SIGSTOP); } timer_start(1); for (step = 1; step <= niter; step++) { if (step % 20 == 0 || step == 1) { printf(" Time step %4d\n", step); } adi(); } #pragma omp parallel { #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop(1); //PMC if(argc>=2){ printf("BENCH COMPLETE!\n"); kill(cpid, SIGSTOP); } tmax = timer_read(1); verify(niter, &class, &verified); if (tmax != 0) { mflops = ( 881.174 * pow((double)PROBLEM_SIZE, 3.0) - 4683.91 * pow2((double)PROBLEM_SIZE) + 11484.5 * (double)PROBLEM_SIZE - 19272.4) * (double)niter / (tmax*1000000.0); } else { mflops = 0.0; } c_print_results("SP", class, grid_points[0], grid_points[1], grid_points[2], niter, nthreads, tmax, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void add(void) { int i, j, k, m; /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c addition of update to the vector u c-------------------------------------------------------------------*/ #pragma omp for for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { u[m][i][j][k] = u[m][i][j][k] + rhs[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void adi(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ compute_rhs(); txinvr(); x_solve(); y_solve(); z_solve(); add(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void error_norm(double rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function computes the norm of the difference between the c computed solution and the exact solution c-------------------------------------------------------------------*/ int i, j, k, m, d; double xi, eta, zeta, u_exact[5], add; for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, u_exact); for (m = 0; m < 5; m++) { add = u[m][i][j][k] - u_exact[m]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void rhs_norm(double rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, d, m; double add; for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 0; i <= grid_points[0]-2; i++) { for (j = 0; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-2; k++) { for (m = 0; m < 5; m++) { add = rhs[m][i][j][k]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_rhs(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute the right hand side based on exact solution c-------------------------------------------------------------------*/ double dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; /*-------------------------------------------------------------------- c initialize c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k= 0; k <= grid_points[2]-1; k++) { forcing[m][i][j][k] = 0.0; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)k * dnzm1; for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)j * dnym1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][i] = dtemp[m]; } dtpp = 1.0 / dtemp[0]; for (m = 1; m < 5; m++) { buf[m][i] = dtpp * dtemp[m]; } cuf[i] = buf[1][i] * buf[1][i]; buf[0][i] = cuf[i] + buf[2][i] * buf[2][i] + buf[3][i] * buf[3][i]; q[i] = 0.5 * (buf[1][i]*ue[1][i] + buf[2][i]*ue[2][i] + buf[3][i]*ue[3][i]); } for (i = 1; i <= grid_points[0]-2; i++) { im1 = i-1; ip1 = i+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tx2*( ue[1][ip1]-ue[1][im1] )+ dx1tx1*(ue[0][ip1]-2.0*ue[0][i]+ue[0][im1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tx2 * ((ue[1][ip1]*buf[1][ip1]+c2*(ue[4][ip1]-q[ip1]))- (ue[1][im1]*buf[1][im1]+c2*(ue[4][im1]-q[im1])))+ xxcon1*(buf[1][ip1]-2.0*buf[1][i]+buf[1][im1])+ dx2tx1*( ue[1][ip1]-2.0* ue[1][i]+ue[1][im1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tx2 * (ue[2][ip1]*buf[1][ip1]-ue[2][im1]*buf[1][im1])+ xxcon2*(buf[2][ip1]-2.0*buf[2][i]+buf[2][im1])+ dx3tx1*( ue[2][ip1]-2.0*ue[2][i] +ue[2][im1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tx2*(ue[3][ip1]*buf[1][ip1]-ue[3][im1]*buf[1][im1])+ xxcon2*(buf[3][ip1]-2.0*buf[3][i]+buf[3][im1])+ dx4tx1*( ue[3][ip1]-2.0* ue[3][i]+ ue[3][im1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tx2*(buf[1][ip1]*(c1*ue[4][ip1]-c2*q[ip1])- buf[1][im1]*(c1*ue[4][im1]-c2*q[im1]))+ 0.5*xxcon3*(buf[0][ip1]-2.0*buf[0][i]+ buf[0][im1])+ xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+ xxcon5*(buf[4][ip1]-2.0*buf[4][i]+buf[4][im1])+ dx5tx1*( ue[4][ip1]-2.0* ue[4][i]+ ue[4][im1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { i = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][i] - 4.0*ue[m][i+1] +ue[m][i+2]); i = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1] + ue[m][i+2]); } for (m = 0; m < 5; m++) { for (i = 3; i <= grid_points[0]-4; i++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][i-2] - 4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1] + ue[m][i+2]); } } for (m = 0; m < 5; m++) { i = grid_points[0]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - 4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1]); i = grid_points[0]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - 4.0*ue[m][i-1] + 5.0*ue[m][i]); } } } /*-------------------------------------------------------------------- c eta-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)k * dnzm1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][j] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][j] = dtpp * dtemp[m]; } cuf[j] = buf[2][j] * buf[2][j]; buf[0][j] = cuf[j] + buf[1][j] * buf[1][j] + buf[3][j] * buf[3][j]; q[j] = 0.5*(buf[1][j]*ue[1][j] + buf[2][j]*ue[2][j] + buf[3][j]*ue[3][j]); } for (j = 1; j <= grid_points[1]-2; j++) { jm1 = j-1; jp1 = j+1; forcing[0][i][j][k] = forcing[0][i][j][k] - ty2*( ue[2][jp1]-ue[2][jm1] )+ dy1ty1*(ue[0][jp1]-2.0*ue[0][j]+ue[0][jm1]); forcing[1][i][j][k] = forcing[1][i][j][k] - ty2*(ue[1][jp1]*buf[2][jp1]-ue[1][jm1]*buf[2][jm1])+ yycon2*(buf[1][jp1]-2.0*buf[1][j]+buf[1][jm1])+ dy2ty1*( ue[1][jp1]-2.0* ue[1][j]+ ue[1][jm1]); forcing[2][i][j][k] = forcing[2][i][j][k] - ty2*((ue[2][jp1]*buf[2][jp1]+c2*(ue[4][jp1]-q[jp1]))- (ue[2][jm1]*buf[2][jm1]+c2*(ue[4][jm1]-q[jm1])))+ yycon1*(buf[2][jp1]-2.0*buf[2][j]+buf[2][jm1])+ dy3ty1*( ue[2][jp1]-2.0*ue[2][j] +ue[2][jm1]); forcing[3][i][j][k] = forcing[3][i][j][k] - ty2*(ue[3][jp1]*buf[2][jp1]-ue[3][jm1]*buf[2][jm1])+ yycon2*(buf[3][jp1]-2.0*buf[3][j]+buf[3][jm1])+ dy4ty1*( ue[3][jp1]-2.0*ue[3][j]+ ue[3][jm1]); forcing[4][i][j][k] = forcing[4][i][j][k] - ty2*(buf[2][jp1]*(c1*ue[4][jp1]-c2*q[jp1])- buf[2][jm1]*(c1*ue[4][jm1]-c2*q[jm1]))+ 0.5*yycon3*(buf[0][jp1]-2.0*buf[0][j]+ buf[0][jm1])+ yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+ yycon5*(buf[4][jp1]-2.0*buf[4][j]+buf[4][jm1])+ dy5ty1*(ue[4][jp1]-2.0*ue[4][j]+ue[4][jm1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { j = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][j] - 4.0*ue[m][j+1] +ue[m][j+2]); j = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1] + ue[m][j+2]); } for (m = 0; m < 5; m++) { for (j = 3; j <= grid_points[1]-4; j++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][j-2] - 4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1] + ue[m][j+2]); } } for (m = 0; m < 5; m++) { j = grid_points[1]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - 4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1]); j = grid_points[1]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - 4.0*ue[m][j-1] + 5.0*ue[m][j]); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)j * dnym1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)i * dnxm1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][k] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][k] = dtpp * dtemp[m]; } cuf[k] = buf[3][k] * buf[3][k]; buf[0][k] = cuf[k] + buf[1][k] * buf[1][k] + buf[2][k] * buf[2][k]; q[k] = 0.5*(buf[1][k]*ue[1][k] + buf[2][k]*ue[2][k] + buf[3][k]*ue[3][k]); } for (k = 1; k <= grid_points[2]-2; k++) { km1 = k-1; kp1 = k+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tz2*( ue[3][kp1]-ue[3][km1] )+ dz1tz1*(ue[0][kp1]-2.0*ue[0][k]+ue[0][km1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tz2 * (ue[1][kp1]*buf[3][kp1]-ue[1][km1]*buf[3][km1])+ zzcon2*(buf[1][kp1]-2.0*buf[1][k]+buf[1][km1])+ dz2tz1*( ue[1][kp1]-2.0* ue[1][k]+ ue[1][km1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tz2 * (ue[2][kp1]*buf[3][kp1]-ue[2][km1]*buf[3][km1])+ zzcon2*(buf[2][kp1]-2.0*buf[2][k]+buf[2][km1])+ dz3tz1*(ue[2][kp1]-2.0*ue[2][k]+ue[2][km1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tz2 * ((ue[3][kp1]*buf[3][kp1]+c2*(ue[4][kp1]-q[kp1]))- (ue[3][km1]*buf[3][km1]+c2*(ue[4][km1]-q[km1])))+ zzcon1*(buf[3][kp1]-2.0*buf[3][k]+buf[3][km1])+ dz4tz1*( ue[3][kp1]-2.0*ue[3][k] +ue[3][km1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tz2 * (buf[3][kp1]*(c1*ue[4][kp1]-c2*q[kp1])- buf[3][km1]*(c1*ue[4][km1]-c2*q[km1]))+ 0.5*zzcon3*(buf[0][kp1]-2.0*buf[0][k] +buf[0][km1])+ zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+ zzcon5*(buf[4][kp1]-2.0*buf[4][k]+buf[4][km1])+ dz5tz1*( ue[4][kp1]-2.0*ue[4][k]+ ue[4][km1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { k = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][k] - 4.0*ue[m][k+1] +ue[m][k+2]); k = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1] + ue[m][k+2]); } for (m = 0; m < 5; m++) { for (k = 3; k <= grid_points[2]-4; k++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][k-2] - 4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1] + ue[m][k+2]); } } for (m = 0; m < 5; m++) { k = grid_points[2]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - 4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1]); k = grid_points[2]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - 4.0*ue[m][k-1] + 5.0*ue[m][k]); } } } /*-------------------------------------------------------------------- c now change the sign of the forcing function, c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { forcing[m][i][j][k] = -1.0 * forcing[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_solution(double xi, double eta, double zeta, double dtemp[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function returns the exact solution at point xi, eta, zeta c-------------------------------------------------------------------*/ int m; for (m = 0; m < 5; m++) { dtemp[m] = ce[0][m] + xi*(ce[1][m] + xi*(ce[4][m] + xi*(ce[7][m] + xi*ce[10][m]))) + eta*(ce[2][m] + eta*(ce[5][m] + eta*(ce[8][m] + eta*ce[11][m])))+ zeta*(ce[3][m] + zeta*(ce[6][m] + zeta*(ce[9][m] + zeta*ce[12][m]))); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void initialize(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This subroutine initializes the field variable u using c tri-linear transfinite interpolation of the boundary values c-------------------------------------------------------------------*/ int i, j, k, m, ix, iy, iz; double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; /*-------------------------------------------------------------------- c Later (in compute_rhs) we compute 1/u for every element. A few of c the corner elements are not used, but it convenient (and faster) c to compute the whole thing with a simple loop. Make sure those c values are nonzero by initializing the whole thing here. c-------------------------------------------------------------------*/ for (i = 0; i <= IMAX-1; i++) { for (j = 0; j <= IMAX-1; j++) { for (k = 0; k <= IMAX-1; k++) { u[0][i][j][k] = 1.0; u[1][i][j][k] = 0.0; u[2][i][j][k] = 0.0; u[3][i][j][k] = 0.0; u[4][i][j][k] = 1.0; } } } /*-------------------------------------------------------------------- c first store the "interpolated" values everywhere on the grid c-------------------------------------------------------------------*/ for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; for (ix = 0; ix < 2; ix++) { exact_solution((double)ix, eta, zeta, &Pface[ix][0][0]); } for (iy = 0; iy < 2; iy++) { exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]); } for (iz = 0; iz < 2; iz++) { exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]); } for (m = 0; m < 5; m++) { Pxi = xi * Pface[1][0][m] + (1.0-xi) * Pface[0][0][m]; Peta = eta * Pface[1][1][m] + (1.0-eta) * Pface[0][1][m]; Pzeta = zeta * Pface[1][2][m] + (1.0-zeta) * Pface[0][2][m]; u[m][i][j][k] = Pxi + Peta + Pzeta - Pxi*Peta - Pxi*Pzeta - Peta*Pzeta + Pxi*Peta*Pzeta; } } } } /*-------------------------------------------------------------------- c now store the exact values on the boundaries c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c west face c-------------------------------------------------------------------*/ xi = 0.0; i = 0; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c east face c-------------------------------------------------------------------*/ xi = 1.0; i = grid_points[0]-1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c south face c-------------------------------------------------------------------*/ eta = 0.0; j = 0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c north face c-------------------------------------------------------------------*/ eta = 1.0; j = grid_points[1]-1; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c bottom face c-------------------------------------------------------------------*/ zeta = 0.0; k = 0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i *dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c top face c-------------------------------------------------------------------*/ zeta = 1.0; k = grid_points[2]-1; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsinit(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, n; /*-------------------------------------------------------------------- c zap the whole left hand side for starters c-------------------------------------------------------------------*/ for (n = 0; n < 15; n++) { #pragma omp for nowait for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[n][i][j][k] = 0.0; } } } } #pragma omp barrier /*-------------------------------------------------------------------- c next, set all diagonal values to 1. This is overkill, but c convenient c-------------------------------------------------------------------*/ for (n = 0; n < 3; n++) { #pragma omp for for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[5*n+2][i][j][k] = 1.0; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsx(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three x-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { ru1 = c3c4*rho_i[i][j][k]; cv[i] = us[i][j][k]; rhon[i] = max(dx2+con43*ru1, max(dx5+c1c5*ru1, max(dxmax+ru1, dx1))); } #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = - dttx2 * cv[i-1] - dttx1 * rhon[i-1]; lhs[2][i][j][k] = 1.0 + c2dttx1 * rhon[i]; lhs[3][i][j][k] = dttx2 * cv[i+1] - dttx1 * rhon[i+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ i = 1; #pragma omp for nowait for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz6; lhs[3][i+1][j][k] = lhs[3][i+1][j][k] - comz4; lhs[4][i+1][j][k] = lhs[4][i+1][j][k] + comz1; } } #pragma omp for nowait for (i = 3; i <= grid_points[0]-4; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } i = grid_points[0]-3; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i+1][j][k] = lhs[0][i+1][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) by adding to c the first c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttx2 * speed[i-1][j][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttx2 * speed[i+1][j][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttx2 * speed[i-1][j][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttx2 * speed[i+1][j][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsy(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three y-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (j = 0; j <= grid_points[1]-1; j++) { ru1 = c3c4*rho_i[i][j][k]; cv[j] = vs[i][j][k]; rhoq[j] = max(dy3 + con43 * ru1, max(dy5 + c1c5*ru1, max(dymax + ru1, dy1))); } #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = -dtty2 * cv[j-1] - dtty1 * rhoq[j-1]; lhs[2][i][j][k] = 1.0 + c2dtty1 * rhoq[j]; lhs[3][i][j][k] = dtty2 * cv[j+1] - dtty1 * rhoq[j+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ j = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz6; lhs[3][i][j+1][k] = lhs[3][i][j+1][k] - comz4; lhs[4][i][j+1][k] = lhs[4][i][j+1][k] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3; j <= grid_points[1]-4; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } j = grid_points[1]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j+1][k] = lhs[0][i][j+1][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, do the other two factors c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dtty2 * speed[i][j-1][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dtty2 * speed[i][j+1][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dtty2 * speed[i][j-1][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dtty2 * speed[i][j+1][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsz(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three z-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { #pragma omp for for (k = 0; k <= grid_points[2]-1; k++) { ru1 = c3c4*rho_i[i][j][k]; cv[k] = ws[i][j][k]; rhos[k] = max(dz4 + con43 * ru1, max(dz5 + c1c5 * ru1, max(dzmax + ru1, dz1))); } #pragma omp for for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = -dttz2 * cv[k-1] - dttz1 * rhos[k-1]; lhs[2][i][j][k] = 1.0 + c2dttz1 * rhos[k]; lhs[3][i][j][k] = dttz2 * cv[k+1] - dttz1 * rhos[k+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ k = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz6; lhs[3][i][j][k+1] = lhs[3][i][j][k+1] - comz4; lhs[4][i][j][k+1] = lhs[4][i][j][k+1] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3; k <= grid_points[2]-4; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } k = grid_points[2]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j][k+1] = lhs[0][i][j][k+1] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttz2 * speed[i][j][k-1]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttz2 * speed[i][j][k+1]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttz2 * speed[i][j][k-1]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttz2 * speed[i][j][k+1]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void ninvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double r1, r2, r3, r4, r5, t1, t2; #pragma omp parallel for default(shared) private(i,j,k,r1,r2,r3,r4,r5,t1,t2) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r3; t2 = 0.5 * ( r4 + r5 ); rhs[0][i][j][k] = -r2; rhs[1][i][j][k] = r1; rhs[2][i][j][k] = bt * ( r4 - r5 ); rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void pinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double r1, r2, r3, r4, r5, t1, t2; #pragma omp parallel for default(shared) private(i,j,k,r1,r2,r3,r4,r5,t1,t2) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r1; t2 = 0.5 * ( r4 + r5 ); rhs[0][i][j][k] = bt * ( r4 - r5 ); rhs[1][i][j][k] = -r3; rhs[2][i][j][k] = r2; rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void compute_rhs(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, m; double aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; /*-------------------------------------------------------------------- c compute the reciprocal of density, and the kinetic energy, c and the speed of sound. c-------------------------------------------------------------------*/ #pragma omp for nowait for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rho_inv = 1.0/u[0][i][j][k]; rho_i[i][j][k] = rho_inv; us[i][j][k] = u[1][i][j][k] * rho_inv; vs[i][j][k] = u[2][i][j][k] * rho_inv; ws[i][j][k] = u[3][i][j][k] * rho_inv; square[i][j][k] = 0.5* (u[1][i][j][k]*u[1][i][j][k] + u[2][i][j][k]*u[2][i][j][k] + u[3][i][j][k]*u[3][i][j][k] ) * rho_inv; qs[i][j][k] = square[i][j][k] * rho_inv; /*-------------------------------------------------------------------- c (do not need speed and ainx until the lhs computation) c-------------------------------------------------------------------*/ aux = c1c2*rho_inv* (u[4][i][j][k] - square[i][j][k]); aux = sqrt(aux); speed[i][j][k] = aux; ainv[i][j][k] = 1.0/aux; } } } /*-------------------------------------------------------------------- c copy the exact forcing term to the right hand side; because c this forcing term is known, we can store it on the whole grid c including the boundary c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rhs[m][i][j][k] = forcing[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c compute xi-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { uijk = us[i][j][k]; up1 = us[i+1][j][k]; um1 = us[i-1][j][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dx1tx1 * (u[0][i+1][j][k] - 2.0*u[0][i][j][k] + u[0][i-1][j][k]) - tx2 * (u[1][i+1][j][k] - u[1][i-1][j][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dx2tx1 * (u[1][i+1][j][k] - 2.0*u[1][i][j][k] + u[1][i-1][j][k]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[1][i+1][j][k]*up1 - u[1][i-1][j][k]*um1 + (u[4][i+1][j][k]- square[i+1][j][k]- u[4][i-1][j][k]+ square[i-1][j][k])* c2); rhs[2][i][j][k] = rhs[2][i][j][k] + dx3tx1 * (u[2][i+1][j][k] - 2.0*u[2][i][j][k] + u[2][i-1][j][k]) + xxcon2 * (vs[i+1][j][k] - 2.0*vs[i][j][k] + vs[i-1][j][k]) - tx2 * (u[2][i+1][j][k]*up1 - u[2][i-1][j][k]*um1); rhs[3][i][j][k] = rhs[3][i][j][k] + dx4tx1 * (u[3][i+1][j][k] - 2.0*u[3][i][j][k] + u[3][i-1][j][k]) + xxcon2 * (ws[i+1][j][k] - 2.0*ws[i][j][k] + ws[i-1][j][k]) - tx2 * (u[3][i+1][j][k]*up1 - u[3][i-1][j][k]*um1); rhs[4][i][j][k] = rhs[4][i][j][k] + dx5tx1 * (u[4][i+1][j][k] - 2.0*u[4][i][j][k] + u[4][i-1][j][k]) + xxcon3 * (qs[i+1][j][k] - 2.0*qs[i][j][k] + qs[i-1][j][k]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[4][i+1][j][k]*rho_i[i+1][j][k] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i-1][j][k]*rho_i[i-1][j][k]) - tx2 * ( (c1*u[4][i+1][j][k] - c2*square[i+1][j][k])*up1 - (c1*u[4][i-1][j][k] - c2*square[i-1][j][k])*um1 ); } } } /*-------------------------------------------------------------------- c add fourth order xi-direction dissipation c-------------------------------------------------------------------*/ i = 1; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } i = 2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 3*1; i <= grid_points[0]-3*1-1; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k] ); } } } } i = grid_points[0]-3; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] ); } } } i = grid_points[0]-2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 5.0*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute eta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { vijk = vs[i][j][k]; vp1 = vs[i][j+1][k]; vm1 = vs[i][j-1][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dy1ty1 * (u[0][i][j+1][k] - 2.0*u[0][i][j][k] + u[0][i][j-1][k]) - ty2 * (u[2][i][j+1][k] - u[2][i][j-1][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dy2ty1 * (u[1][i][j+1][k] - 2.0*u[1][i][j][k] + u[1][i][j-1][k]) + yycon2 * (us[i][j+1][k] - 2.0*us[i][j][k] + us[i][j-1][k]) - ty2 * (u[1][i][j+1][k]*vp1 - u[1][i][j-1][k]*vm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dy3ty1 * (u[2][i][j+1][k] - 2.0*u[2][i][j][k] + u[2][i][j-1][k]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[2][i][j+1][k]*vp1 - u[2][i][j-1][k]*vm1 + (u[4][i][j+1][k] - square[i][j+1][k] - u[4][i][j-1][k] + square[i][j-1][k]) *c2); rhs[3][i][j][k] = rhs[3][i][j][k] + dy4ty1 * (u[3][i][j+1][k] - 2.0*u[3][i][j][k] + u[3][i][j-1][k]) + yycon2 * (ws[i][j+1][k] - 2.0*ws[i][j][k] + ws[i][j-1][k]) - ty2 * (u[3][i][j+1][k]*vp1 - u[3][i][j-1][k]*vm1); rhs[4][i][j][k] = rhs[4][i][j][k] + dy5ty1 * (u[4][i][j+1][k] - 2.0*u[4][i][j][k] + u[4][i][j-1][k]) + yycon3 * (qs[i][j+1][k] - 2.0*qs[i][j][k] + qs[i][j-1][k]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[4][i][j+1][k]*rho_i[i][j+1][k] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j-1][k]*rho_i[i][j-1][k]) - ty2 * ((c1*u[4][i][j+1][k] - c2*square[i][j+1][k]) * vp1 - (c1*u[4][i][j-1][k] - c2*square[i][j-1][k]) * vm1); } } } /*-------------------------------------------------------------------- c add fourth order eta-direction dissipation c-------------------------------------------------------------------*/ j = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } j = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3*1; j <= grid_points[1]-3*1-1; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k] ); } } } } j = grid_points[1]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] ); } } } j = grid_points[1]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 5.0*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute zeta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { wijk = ws[i][j][k]; wp1 = ws[i][j][k+1]; wm1 = ws[i][j][k-1]; rhs[0][i][j][k] = rhs[0][i][j][k] + dz1tz1 * (u[0][i][j][k+1] - 2.0*u[0][i][j][k] + u[0][i][j][k-1]) - tz2 * (u[3][i][j][k+1] - u[3][i][j][k-1]); rhs[1][i][j][k] = rhs[1][i][j][k] + dz2tz1 * (u[1][i][j][k+1] - 2.0*u[1][i][j][k] + u[1][i][j][k-1]) + zzcon2 * (us[i][j][k+1] - 2.0*us[i][j][k] + us[i][j][k-1]) - tz2 * (u[1][i][j][k+1]*wp1 - u[1][i][j][k-1]*wm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dz3tz1 * (u[2][i][j][k+1] - 2.0*u[2][i][j][k] + u[2][i][j][k-1]) + zzcon2 * (vs[i][j][k+1] - 2.0*vs[i][j][k] + vs[i][j][k-1]) - tz2 * (u[2][i][j][k+1]*wp1 - u[2][i][j][k-1]*wm1); rhs[3][i][j][k] = rhs[3][i][j][k] + dz4tz1 * (u[3][i][j][k+1] - 2.0*u[3][i][j][k] + u[3][i][j][k-1]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[3][i][j][k+1]*wp1 - u[3][i][j][k-1]*wm1 + (u[4][i][j][k+1] - square[i][j][k+1] - u[4][i][j][k-1] + square[i][j][k-1]) *c2); rhs[4][i][j][k] = rhs[4][i][j][k] + dz5tz1 * (u[4][i][j][k+1] - 2.0*u[4][i][j][k] + u[4][i][j][k-1]) + zzcon3 * (qs[i][j][k+1] - 2.0*qs[i][j][k] + qs[i][j][k-1]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[4][i][j][k+1]*rho_i[i][j][k+1] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j][k-1]*rho_i[i][j][k-1]) - tz2 * ( (c1*u[4][i][j][k+1] - c2*square[i][j][k+1])*wp1 - (c1*u[4][i][j][k-1] - c2*square[i][j][k-1])*wm1); } } } /*-------------------------------------------------------------------- c add fourth order zeta-direction dissipation c-------------------------------------------------------------------*/ k = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } k = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3*1; k <= grid_points[2]-3*1-1; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2] ); } } } } k = grid_points[2]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] ); } } } k = grid_points[2]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 5.0*u[m][i][j][k] ); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] * dt; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void set_constants(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ ce[0][0] = 2.0; ce[1][0] = 0.0; ce[2][0] = 0.0; ce[3][0] = 4.0; ce[4][0] = 5.0; ce[5][0] = 3.0; ce[6][0] = 0.5; ce[7][0] = 0.02; ce[8][0] = 0.01; ce[9][0] = 0.03; ce[10][0] = 0.5; ce[11][0] = 0.4; ce[12][0] = 0.3; ce[0][1] = 1.0; ce[1][1] = 0.0; ce[2][1] = 0.0; ce[3][1] = 0.0; ce[4][1] = 1.0; ce[5][1] = 2.0; ce[6][1] = 3.0; ce[7][1] = 0.01; ce[8][1] = 0.03; ce[9][1] = 0.02; ce[10][1] = 0.4; ce[11][1] = 0.3; ce[12][1] = 0.5; ce[0][2] = 2.0; ce[1][2] = 2.0; ce[2][2] = 0.0; ce[3][2] = 0.0; ce[4][2] = 0.0; ce[5][2] = 2.0; ce[6][2] = 3.0; ce[7][2] = 0.04; ce[8][2] = 0.03; ce[9][2] = 0.05; ce[10][2] = 0.3; ce[11][2] = 0.5; ce[12][2] = 0.4; ce[0][3] = 2.0; ce[1][3] = 2.0; ce[2][3] = 0.0; ce[3][3] = 0.0; ce[4][3] = 0.0; ce[5][3] = 2.0; ce[6][3] = 3.0; ce[7][3] = 0.03; ce[8][3] = 0.05; ce[9][3] = 0.04; ce[10][3] = 0.2; ce[11][3] = 0.1; ce[12][3] = 0.3; ce[0][4] = 5.0; ce[1][4] = 4.0; ce[2][4] = 3.0; ce[3][4] = 2.0; ce[4][4] = 0.1; ce[5][4] = 0.4; ce[6][4] = 0.3; ce[7][4] = 0.05; ce[8][4] = 0.04; ce[9][4] = 0.03; ce[10][4] = 0.1; ce[11][4] = 0.3; ce[12][4] = 0.2; c1 = 1.4; c2 = 0.4; c3 = 0.1; c4 = 1.0; c5 = 1.4; bt = sqrt(0.5); dnxm1 = 1.0 / (double)(grid_points[0]-1); dnym1 = 1.0 / (double)(grid_points[1]-1); dnzm1 = 1.0 / (double)(grid_points[2]-1); c1c2 = c1 * c2; c1c5 = c1 * c5; c3c4 = c3 * c4; c1345 = c1c5 * c3c4; conz1 = (1.0-c1c5); tx1 = 1.0 / (dnxm1 * dnxm1); tx2 = 1.0 / (2.0 * dnxm1); tx3 = 1.0 / dnxm1; ty1 = 1.0 / (dnym1 * dnym1); ty2 = 1.0 / (2.0 * dnym1); ty3 = 1.0 / dnym1; tz1 = 1.0 / (dnzm1 * dnzm1); tz2 = 1.0 / (2.0 * dnzm1); tz3 = 1.0 / dnzm1; dx1 = 0.75; dx2 = 0.75; dx3 = 0.75; dx4 = 0.75; dx5 = 0.75; dy1 = 0.75; dy2 = 0.75; dy3 = 0.75; dy4 = 0.75; dy5 = 0.75; dz1 = 1.0; dz2 = 1.0; dz3 = 1.0; dz4 = 1.0; dz5 = 1.0; dxmax = max(dx3, dx4); dymax = max(dy2, dy4); dzmax = max(dz2, dz3); dssp = 0.25 * max(dx1, max(dy1, dz1) ); c4dssp = 4.0 * dssp; c5dssp = 5.0 * dssp; dttx1 = dt*tx1; dttx2 = dt*tx2; dtty1 = dt*ty1; dtty2 = dt*ty2; dttz1 = dt*tz1; dttz2 = dt*tz2; c2dttx1 = 2.0*dttx1; c2dtty1 = 2.0*dtty1; c2dttz1 = 2.0*dttz1; dtdssp = dt*dssp; comz1 = dtdssp; comz4 = 4.0*dtdssp; comz5 = 5.0*dtdssp; comz6 = 6.0*dtdssp; c3c4tx3 = c3c4*tx3; c3c4ty3 = c3c4*ty3; c3c4tz3 = c3c4*tz3; dx1tx1 = dx1*tx1; dx2tx1 = dx2*tx1; dx3tx1 = dx3*tx1; dx4tx1 = dx4*tx1; dx5tx1 = dx5*tx1; dy1ty1 = dy1*ty1; dy2ty1 = dy2*ty1; dy3ty1 = dy3*ty1; dy4ty1 = dy4*ty1; dy5ty1 = dy5*ty1; dz1tz1 = dz1*tz1; dz2tz1 = dz2*tz1; dz3tz1 = dz3*tz1; dz4tz1 = dz4*tz1; dz5tz1 = dz5*tz1; c2iv = 2.5; con43 = 4.0/3.0; con16 = 1.0/6.0; xxcon1 = c3c4tx3*con43*tx3; xxcon2 = c3c4tx3*tx3; xxcon3 = c3c4tx3*conz1*tx3; xxcon4 = c3c4tx3*con16*tx3; xxcon5 = c3c4tx3*c1c5*tx3; yycon1 = c3c4ty3*con43*ty3; yycon2 = c3c4ty3*ty3; yycon3 = c3c4ty3*conz1*ty3; yycon4 = c3c4ty3*con16*ty3; yycon5 = c3c4ty3*c1c5*ty3; zzcon1 = c3c4tz3*con43*tz3; zzcon2 = c3c4tz3*tz3; zzcon3 = c3c4tz3*conz1*tz3; zzcon4 = c3c4tz3*con16*tz3; zzcon5 = c3c4tz3*c1c5*tz3; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void txinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication --------------------------------------------------------------------*/ int i, j, k; double t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3, r4, r5, ac2inv; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { ru1 = rho_i[i][j][k]; uu = us[i][j][k]; vv = vs[i][j][k]; ww = ws[i][j][k]; ac = speed[i][j][k]; ac2inv = ainv[i][j][k]*ainv[i][j][k]; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = c2 * ac2inv * ( qs[i][j][k]*r1 - uu*r2 - vv*r3 - ww*r4 + r5 ); t2 = bt * ru1 * ( uu * r1 - r2 ); t3 = ( bt * ru1 * ac ) * t1; rhs[0][i][j][k] = r1 - t1; rhs[1][i][j][k] = - ru1 * ( ww*r1 - r4 ); rhs[2][i][j][k] = ru1 * ( vv*r1 - r3 ); rhs[3][i][j][k] = - t2 + t3; rhs[4][i][j][k] = t2 + t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void tzetar(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double t1, t2, t3, ac, xvel, yvel, zvel, r1, r2, r3, r4, r5, btuz, acinv, ac2u, uzik1; #pragma omp for private(i,j,k,t1,t2,t3,ac,xvel,yvel,zvel,r1,r2,r3,r4,r5,btuz,ac2u,uzik1) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { xvel = us[i][j][k]; yvel = vs[i][j][k]; zvel = ws[i][j][k]; ac = speed[i][j][k]; acinv = ainv[i][j][k]; ac2u = ac*ac; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; uzik1 = u[0][i][j][k]; btuz = bt * uzik1; t1 = btuz*acinv * (r4 + r5); t2 = r3 + t1; t3 = btuz * (r4 - r5); rhs[0][i][j][k] = t2; rhs[1][i][j][k] = -uzik1*r2 + xvel*t2; rhs[2][i][j][k] = uzik1*r1 + yvel*t2; rhs[3][i][j][k] = zvel*t2 + t3; rhs[4][i][j][k] = uzik1*(-xvel*r2 + yvel*r1) + qs[i][j][k]*t2 + c2iv*ac2u*t1 + zvel*t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void verify(int no_time_steps, char *class, boolean *verified) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c verification routine --------------------------------------------------------------------*/ double xcrref[5],xceref[5],xcrdif[5],xcedif[5], epsilon, xce[5], xcr[5], dtref; int m; /*-------------------------------------------------------------------- c tolerance level --------------------------------------------------------------------*/ epsilon = 1.0e-08; /*-------------------------------------------------------------------- c compute the error norm and the residual norm, and exit if not printing --------------------------------------------------------------------*/ error_norm(xce); compute_rhs(); rhs_norm(xcr); for (m = 0; m < 5; m++) { xcr[m] = xcr[m] / dt; } *class = 'U'; *verified = TRUE; for (m = 0; m < 5; m++) { xcrref[m] = 1.0; xceref[m] = 1.0; } /*-------------------------------------------------------------------- c reference data for 12X12X12 grids after 100 time steps, with DT = 1.50d-02 --------------------------------------------------------------------*/ if ( grid_points[0] == 12 && grid_points[1] == 12 && grid_points[2] == 12 && no_time_steps == 100) { *class = 'S'; dtref = 1.5e-2; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 2.7470315451339479e-02; xcrref[1] = 1.0360746705285417e-02; xcrref[2] = 1.6235745065095532e-02; xcrref[3] = 1.5840557224455615e-02; xcrref[4] = 3.4849040609362460e-02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 2.7289258557377227e-05; xceref[1] = 1.0364446640837285e-05; xceref[2] = 1.6154798287166471e-05; xceref[3] = 1.5750704994480102e-05; xceref[4] = 3.4177666183390531e-05; /*-------------------------------------------------------------------- c reference data for 36X36X36 grids after 400 time steps, with DT = 1.5d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 36 && grid_points[1] == 36 && grid_points[2] == 36 && no_time_steps == 400) { *class = 'W'; dtref = 1.5e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.1893253733584e-02; xcrref[1] = 0.1717075447775e-03; xcrref[2] = 0.2778153350936e-03; xcrref[3] = 0.2887475409984e-03; xcrref[4] = 0.3143611161242e-02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.7542088599534e-04; xceref[1] = 0.6512852253086e-05; xceref[2] = 0.1049092285688e-04; xceref[3] = 0.1128838671535e-04; xceref[4] = 0.1212845639773e-03; /*-------------------------------------------------------------------- c reference data for 64X64X64 grids after 400 time steps, with DT = 1.5d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 64 && grid_points[1] == 64 && grid_points[2] == 64 && no_time_steps == 400 ) { *class = 'A'; dtref = 1.5e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 2.4799822399300195; xcrref[1] = 1.1276337964368832; xcrref[2] = 1.5028977888770491; xcrref[3] = 1.4217816211695179; xcrref[4] = 2.1292113035138280; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 1.0900140297820550e-04; xceref[1] = 3.7343951769282091e-05; xceref[2] = 5.0092785406541633e-05; xceref[3] = 4.7671093939528255e-05; xceref[4] = 1.3621613399213001e-04; /*-------------------------------------------------------------------- c reference data for 102X102X102 grids after 400 time steps, c with DT = 1.0d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 102 && grid_points[1] == 102 && grid_points[2] == 102 && no_time_steps == 400) { *class = 'B'; dtref = 1.0e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.6903293579998e+02; xcrref[1] = 0.3095134488084e+02; xcrref[2] = 0.4103336647017e+02; xcrref[3] = 0.3864769009604e+02; xcrref[4] = 0.5643482272596e+02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.9810006190188e-02; xceref[1] = 0.1022827905670e-02; xceref[2] = 0.1720597911692e-02; xceref[3] = 0.1694479428231e-02; xceref[4] = 0.1847456263981e-01; /*-------------------------------------------------------------------- c reference data for 162X162X162 grids after 400 time steps, c with DT = 0.67d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 162 && grid_points[1] == 162 && grid_points[2] == 162 && no_time_steps == 400) { *class = 'C'; dtref = 0.67e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.5881691581829e+03; xcrref[1] = 0.2454417603569e+03; xcrref[2] = 0.3293829191851e+03; xcrref[3] = 0.3081924971891e+03; xcrref[4] = 0.4597223799176e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.2598120500183e+00; xceref[1] = 0.2590888922315e-01; xceref[2] = 0.5132886416320e-01; xceref[3] = 0.4806073419454e-01; xceref[4] = 0.5483377491301e+00; } else { *verified = FALSE; } /*-------------------------------------------------------------------- c verification test for residuals if gridsize is either 12X12X12 or c 64X64X64 or 102X102X102 or 162X162X162 --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Compute the difference of solution values and the known reference values. --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]) ; xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]); } /*-------------------------------------------------------------------- c Output the comparison of computed results to known cases. --------------------------------------------------------------------*/ if (*class != 'U') { printf(" Verification being performed for class %1c\n", *class); printf(" accuracy setting for epsilon = %20.13e\n", epsilon); if (fabs(dt-dtref) > epsilon) { *verified = FALSE; *class = 'U'; printf(" DT does not match the reference value of %15.8e\n", dtref); } } else { printf(" Unknown class\n"); } if (*class != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d%20.13e\n", m, xcr[m]); } else if (xcrdif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } } if (*class != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d%20.13e\n", m, xce[m]); } else if (xcedif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } } if (*class == 'U') { printf(" No reference values provided\n"); printf(" No verification performed\n"); } else if (*verified) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the x-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the x-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, i1, i2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsx(); /*-------------------------------------------------------------------- c perform the Thomas algorithm; first, FORWARD ELIMINATION --------------------------------------------------------------------*/ n = 0; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1.0/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i1][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i1][j][k]; rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (m = 0; m < 3; m++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } } /*-------------------------------------------------------------------- c Do the block-diagonal inversion --------------------------------------------------------------------*/ ninvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the y-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the y-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, j1, j2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsy(); n = 0; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j1][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j1][k]; rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j1 + 1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } } pinvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the z-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the z-lines. Boundary conditions are non-periodic c-------------------------------------------------------------------*/ int i, j, k, n, k1, k2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION c-------------------------------------------------------------------*/ lhsz(); n = 0; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately c-------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j][k1]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately (some of this is overkill c if this is the last cell) c-------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j][k1]; rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c Whether or not this is the last processor, we always have c to complete the back-substitution c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c The first three factors c-------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } /*-------------------------------------------------------------------- c And the remaining two c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } } tzetar(); }
GB_unop__identity_fp64_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__identity_fp64_fc64) // op(A') function: GB (_unop_tran__identity_fp64_fc64) // C type: double // A type: GxB_FC64_t // cast: double cij = (double) creal (aij) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ double // 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) \ double z = (double) 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)) */ \ double z = (double) creal (aij) ; \ 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_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp64_fc64) ( double *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] ; double z = (double) creal (aij) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; double z = (double) 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_fp64_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
nstream-target.c
/// /// Copyright (c) 2019, Intel Corporation /// /// 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 Intel Corporation nor the names of its /// contributors may be used to endorse or promote products /// derived from this software without specific prior written /// permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS /// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT /// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE /// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, /// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, /// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; /// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT /// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN /// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////// /// /// NAME: nstream /// /// PURPOSE: To compute memory bandwidth when adding a vector of a given /// number of double precision values to the scalar multiple of /// another vector of the same length, and storing the result in /// a third vector. /// /// USAGE: The program takes as input the number /// of iterations to loop over the triad vectors and /// the length of the vectors. /// /// <progname> <# iterations> <vector length> /// /// The output consists of diagnostics to make sure the /// algorithm worked, and of timing statistics. /// /// NOTES: Bandwidth is determined as the number of words read, plus the /// number of words written, times the size of the words, divided /// by the execution time. For a vector length of N, the total /// number of words read and written is 4*N*sizeof(double). /// /// /// HISTORY: This code is loosely based on the Stream benchmark by John /// McCalpin, but does not follow all the Stream rules. Hence, /// reported results should not be associated with Stream in /// external publications /// /// Converted to C++11 by Jeff Hammond, November 2017. /// Converted to C11 by Jeff Hammond, February 2019. /// ////////////////////////////////////////////////////////////////////// #include "prk_util.h" #include "prk_openmp.h" int main(int argc, char * argv[]) { printf("Parallel Research Kernels version %d\n", PRKVERSION ); printf("C11/OpenMP TARGET STREAM triad: A = B + scalar * C\n"); ////////////////////////////////////////////////////////////////////// /// Read and test input parameters ////////////////////////////////////////////////////////////////////// if (argc < 3) { printf("Usage: <# iterations> <vector length>\n"); return 1; } int iterations = atoi(argv[1]); if (iterations < 1) { printf("ERROR: iterations must be >= 1\n"); return 1; } // length of a the vector size_t length = atol(argv[2]); if (length <= 0) { printf("ERROR: Vector length must be greater than 0\n"); return 1; } int device = (argc > 3) ? atol(argv[3]) : omp_get_default_device(); if ( (device < 0 || omp_get_num_devices() <= device ) && (device != omp_get_default_device()) ) { printf("ERROR: device number %d is not valid.\n", device); return 1; } printf("Number of iterations = %d\n", iterations); printf("Vector length = %zu\n", length); printf("OpenMP Device = %d\n", device); ////////////////////////////////////////////////////////////////////// // Allocate space and perform the computation ////////////////////////////////////////////////////////////////////// double nstream_time = 0.0; size_t bytes = length*sizeof(double); double * restrict A = prk_malloc(bytes); double * restrict B = prk_malloc(bytes); double * restrict C = prk_malloc(bytes); double scalar = 3.0; #pragma omp parallel for simd schedule(static) for (size_t i=0; i<length; i++) { A[i] = 0.0; B[i] = 2.0; C[i] = 2.0; } #pragma omp target data map(tofrom: A[0:length]) map(to: B[0:length], C[0:length]) { for (int iter = 0; iter<=iterations; iter++) { if (iter==1) nstream_time = omp_get_wtime(); #pragma omp target teams distribute parallel for simd schedule(static) // device(device) for (size_t i=0; i<length; i++) { A[i] += B[i] + scalar * C[i]; } } nstream_time = omp_get_wtime() - nstream_time; } prk_free(C); prk_free(B); ////////////////////////////////////////////////////////////////////// /// Analyze and output results ////////////////////////////////////////////////////////////////////// double ar = 0.0; double br = 2.0; double cr = 2.0; for (int i=0; i<=iterations; i++) { ar += br + scalar * cr; } ar *= length; double asum = 0.0; #pragma omp parallel for reduction(+:asum) for (size_t i=0; i<length; i++) { asum += fabs(A[i]); } prk_free(A); double epsilon=1.e-8; if (fabs(ar-asum)/asum > epsilon) { printf("Failed Validation on output array\n" " Expected checksum: %lf\n" " Observed checksum: %lf\n" "ERROR: solution did not validate\n", ar, asum); return 1; } else { printf("Solution validates\n"); double avgtime = nstream_time/iterations; double nbytes = 4.0 * length * sizeof(double); printf("Rate (MB/s): %lf Avg time (s): %lf\n", 1.e-6*nbytes/avgtime, avgtime); } return 0; }
main.c
/// /// @copyright Copyright (c) 2016-, Issam SAID <said.issam@gmail.com> /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// 1. Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// 2. Redistributions in binary form must reproduce the above copyright /// notice, this list of conditions and the following disclaimer in the /// documentation and/or other materials provided with the distribution. /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived from /// this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, /// INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT /// HOLDER OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, /// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, /// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR /// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF /// LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING /// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS /// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// /// @file stencil_3d/main.c /// @author Issam SAID /// @brief An example of 3D finite difference stencil code based on /// the ezcu C/C++ interface. /// #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <ezcu/ezcu.h> #define N 320 /// /// @brief The main program of the ezcu based sgemm C/C++ example. /// /// This is the main routine that shows how to use the ezcu C/C++ interface /// to implement a simple matrix to matrix multiplication. /// Note that the CUDA kernel is implemented in a seperate file (sgemm.cl). /// @return Error code if any. /// int main(void) { unsigned int i; float *u; float *v; float *coeffs; unsigned int grid[3] = {N/16, N/16, 1}; unsigned int block[3] = {16, 16, 1}; ezcu_dev_t device; fprintf(stdout, "... start of the ezcu 3D stencil C/C++ example\n"); /// ///< Initialize ezcu with selecting the default GPU. /// ezcu_init(); /// ///< Load the CUDA kernel that runs the stencil computations. /// ezcu_load(PREFIX"/stencil_3d.cu", NULL); /// ///< Get a pointer to the desired device (in this case the default GPU). /// device = ezcu_dev_find(0); u = (float*)malloc((N+8)*(N+8)*(N+8)*sizeof(float)); v = (float*)malloc((N+8)*(N+8)*(N+8)*sizeof(float)); coeffs = (float*)malloc(5*sizeof(float)); memset(u, 0, (N+8)*(N+8)*(N+8)*sizeof(float)); srand (time(NULL)); #pragma omp parallel for private(i) for (i = 0; i< (N+8)*(N+8)*(N+8); ++i) v[i] = (float)(i%100); coeffs[0] = -2.6; coeffs[1] = 1.6; coeffs[2] = -0.2; coeffs[3] = 0.02; coeffs[4] = -0.001; /// ///< Wrap the matrices into ezcu memory objects. /// ezcu_mem_wrap(device, u, (N+8)*(N+8)*(N+8), FLOAT | READ_WRITE | HWA); ezcu_mem_wrap(device, v, (N+8)*(N+8)*(N+8), FLOAT | READ_WRITE | HWA); ezcu_mem_wrap(device, coeffs, 5, FLOAT | READ_ONLY | HWA); /// ///< Set the work size an dimension of the kernel. /// ezcu_knl_set_wrk("stencil_3d", 2, grid, block); /// ///< Run the kernel on the default GPU. /// ezcu_knl_run("stencil_3d", device, v, u, coeffs, N, N, N); /// ///< Update the u buffer on the CPU side so that the results can be seen ///< on the host side. /// ezcu_mem_update(u, READ_ONLY); free(u); free(v); free(coeffs); /// ///< Release ezcu resources. /// ezcu_release(); fprintf(stdout, "... end of the ezcu 3D stencil C/C++ example\n"); return EXIT_SUCCESS; }
matrix.h
#pragma once #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <omp.h> #include <string.h> #include <immintrin.h> #ifndef OMP_METHOD #define OMP_METHOD static #endif #ifndef OMP_STRIDE #define OMP_STRIDE 1 #endif typedef float db; // Helper functions for timing double clk; void enter() { clk = omp_get_wtime(); } void leave(const char *msg) { double t = omp_get_wtime() - clk; fprintf(stderr, "%s\nElapsed time: %lf\n", msg, t); } typedef struct { int a, b, c, d; int allo; db *v; } Matrix; void mshape(Matrix *m, int a, int b, int c, int d) { m->a = a; m->b = b; m->c = c; m->d = d; } #define msize(m) \ (m->a * m->b * m->c * m->d) #define mpos(m, i, j, k, l) \ ((i) * m->b * m->c * m->d + (j) * m->c * m->d + (k) * m->d + (l)) #define mget(m, i, j, k, l) \ (m->v[mpos(m, i, j, k, l)]) void mset(Matrix *m, int i, int j, int k, int l, db v) { m->v[mpos(m, i, j, k, l)] = v; } void mswap(Matrix **a, Matrix **b) { Matrix *c = *a; *a = *b; *b = c; } void mallo(Matrix *m) { if (!m->allo) return; if (m->v != NULL) { free(m->v); } m->v = (db *)malloc(sizeof(db) * m->a * m->b * m->c * m->d); } void mread(Matrix *m, void **mem) { int bytes = msize(m) * sizeof(db); if (m->allo) memcpy(m->v, *mem, bytes); else m->v = (db *) (*mem); *mem += bytes; } void minit(Matrix *m, int i, int j, int k, int l, void **mem) { mshape(m, i, j, k, l); mallo(m); mread(m, mem); } Matrix *mnew(int allo) { Matrix *ret = malloc(sizeof(Matrix)); ret->v = NULL; ret->allo = allo; return ret; } void mprint(Matrix *m) { printf("\n\n%d %d %d %d\n", m->a, m->b, m->c, m->d); printf("["); for (int i = 0; i < m->a; ++i) { printf("["); for (int j = 0; j < m->b; ++j) { printf("["); for (int k = 0; k < m->c; ++k) { printf("["); for (int l = 0; l < m->d; ++l) { printf("%.2f ", mget(m, i, j, k, l)); } printf("]\n "); } printf("]\n"); } printf("] "); } printf("]\n"); } void ReLU(Matrix *input, Matrix *output) { enter(); mshape(output, input->a, input->b, input->c, input->d); mallo(output); for (int i = 0; i < msize(input); ++i) { output->v[i] = input->v[i] > 0 ? input->v[i] : 0; } leave("ReLU"); } void ReLUInplace(Matrix *input) { enter(); for (int i = 0; i < msize(input); ++i) { input->v[i] = input->v[i] > 0 ? input->v[i] : 0; } leave("ReLUInplace"); } void Dropout(Matrix *input, Matrix *output) { return ; mshape(output, input->a, input->b, input->c, input->d); mallo(output); for (int i = 0; i < msize(input); ++i) { output->v[i] = (rand() & 1) ? 0 : input->v[i]; } } void DropoutInplace(Matrix *input) { return ; for (int i = 0; i < msize(input); ++i) { if (rand() & 1) input->v[i] = 0; } } void BatchNorm2d(Matrix *input, Matrix *weight, Matrix *bias, Matrix *mean, Matrix *var, Matrix *output) { enter(); mshape(output, input->a, input->b, input->c, input->d); mallo(output); db eps = 1e-5; // this should only work when input->a = 1 for (int i = 0, idx = 0; i < msize(input); i += input->c * input->d, ++idx) { // loop invariant db sq = sqrt(var->v[idx] + eps); for (int j = i; j < i + input->c * input->d; ++j) { output->v[j] = (input->v[j] - mean->v[idx]) / sq * weight->v[idx] + bias->v[idx]; } } leave("BatchNorm2d"); } void Linear(Matrix *input, Matrix *weight, Matrix *bias, Matrix *output) { enter(); mshape(output, input->a, input->b, input->c, weight->c); mallo(output); #pragma omp parallel shared(input, weight, bias, output) num_threads(4) #pragma omp for schedule(OMP_METHOD, OMP_STRIDE) for (int i = 0; i < weight->c; ++i) { output->v[i] = bias->v[i]; for (int j = 0; j < weight->d; ++j) output->v[i] += weight->v[i * weight->d + j] * input->v[j]; } leave("Linear"); } db max2(db a, db b) { return a > b ? a : b; } db max4(db a, db b, db c, db d) { return max2(a, max2(b, max2(c, d))); } // kernel_size=2 stride=2 void MaxPool2d(Matrix *input, Matrix *output) { enter(); mshape(output, input->a, input->b, input->c / 2, input->d / 2); mallo(output); int tot = 0; for (int s = 0; s < msize(input); s += input->c * input->d) { for (int ii = 0; ii < input->c; ii += 2) { for (int jj = 0; jj < input->d; jj += 2) { output->v[tot++] = max4(input->v[s + ii * input->d + jj], input->v[s + ii * input->d + jj + 1], input->v[s + (ii + 1) * input->d + jj], input->v[s + (ii + 1) * input->d + jj + 1]); } } } leave("MaxPool2d"); } // output_size = (7, 7) // NOT adaptive! void AdaptiveAvgPool2d(Matrix *input, Matrix *output) { enter(); mshape(output, input->a, input->b, 7, 7); mallo(output); int tot = 0; int size = input->c / 7; for (int s = 0; s < msize(input); s += input->c * input->d) { for (int ii = 0; ii < input->c; ii += size) { for (int jj = 0; jj < input->d; jj += size) { db avg = 0; for (int i = ii; i < ii + size; ++i) { for (int j = jj; j < jj + size; ++j) { avg += input->v[s + ii * input->d + jj]; } } output->v[tot++] = avg / (size * size); } } } leave("AdaptiveAvgPool2d"); } void Padding(Matrix *input, Matrix *output) { enter(); mshape(output, input->a, input->b, input->c + 2, input->d + 2); mallo(output); for (int i = 0; i < output->a; ++i) for (int j = 0; j < output->b; ++j) for (int k = 0; k < output->c; ++k) for (int l = 0; l < output->d; ++l) { if (k == 0 || k == output->c - 1 || l == 0 || l == output->d - 1) mset(output, i, j, k, l, 0); else mset(output, i, j, k, l, mget(input, i, j, k - 1, l - 1)); } leave("Padding"); } // a b c d -> a c d b void Transpose(Matrix *input, Matrix *output) { enter(); mshape(output, input->a, input->c, input->d, input->b); mallo(output); for (int i = 0; i < output->a; ++i) for (int j = 0; j < output->b; ++j) for (int k = 0; k < output->c; ++k) for (int l = 0; l < output->d; ++l) { mset(output, i, j, k, l, mget(input, i, l, j, k)); } leave("Transpose"); } // stride = 1, kernel = 3 * 3 void Conv2d(Matrix *input, Matrix *weight, Matrix *bias, Matrix *output) { // orginal input c and input d int originalInputC = input->c; int originalInputD = input->d; // orignal weight a int originalWeightA = weight->a; // padding Padding(input, output); mswap(&input, &output); // transpose input Transpose(input, output); mswap(&input, &output); // transpose weight Matrix *newWeight = mnew(1); Transpose(weight, newWeight); // conv2d enter(); mshape(output, 1, originalWeightA, originalInputC, originalInputD); mallo(output); #pragma omp parallel shared(input, newWeight, bias, output) num_threads(4) #pragma omp for schedule(OMP_METHOD, OMP_STRIDE) // oa = 0 for (int ob = 0; ob < output->b; ++ob) for (int oc = 0; oc < output->c; ++oc) for (int od = 0; od < output->d; ++od) { db sum = bias->v[ob]; __m256 avx1 = _mm256_setzero_ps(); __m256 avx2 = _mm256_setzero_ps(); int wd; // kernel 3 * 3 #define _unroll(wb, wc) ({ \ wd = 0; \ if (newWeight->d >= 16) \ for (; wd < newWeight->d; wd += 16) { \ db *inputP = input->v + mpos(input, 0, oc + wb, od + wc, wd); \ db *weightP = newWeight->v + mpos(newWeight, ob, wb, wc, wd); \ __m256 a = _mm256_loadu_ps(inputP); \ __m256 b = _mm256_loadu_ps(weightP); \ avx1 = _mm256_fmadd_ps(a, b, avx1); \ __m256 c = _mm256_loadu_ps(inputP + 8); \ __m256 d = _mm256_loadu_ps(weightP + 8); \ avx2 = _mm256_fmadd_ps(c, d, avx2); \ } \ else /*only one case in data, branch prediction can handle this*/ \ for (; wd < newWeight->d; ++wd) \ sum += mget(input, 0, oc + wb, od + wc, wd) * \ mget(newWeight, ob, wb, wc, wd); \ }) _unroll(0, 0); _unroll(0, 1); _unroll(0, 2); _unroll(1, 0); _unroll(1, 1); _unroll(1, 2); _unroll(2, 0); _unroll(2, 1); _unroll(2, 2); __m256 avxSum = _mm256_add_ps(avx1, avx2); avxSum = _mm256_hadd_ps(avxSum, avxSum); avxSum = _mm256_hadd_ps(avxSum, avxSum); sum += avxSum[0] + avxSum[4]; mset(output, 0, ob, oc, od, sum); } // free memory free(newWeight->v); free(newWeight); leave("Conv2d"); }
tasks.c
#include <stdio.h> #include <omp.h> #define NUM 10 void do_it(){ int id = omp_get_thread_num(); int cont = 0; printf("%d\n",id); while (cont < NUM){ cont++; } } void end_it(){ int id = omp_get_thread_num(); int cont = 0; printf("Single: %d\n",id); while (cont < NUM){ printf("%d\t", cont++); } printf("\n"); } int main(){ #pragma omp parallel { #pragma omp task do_it(); #pragma omp barrier #pragma omp single { #pragma omp task end_it(); } } return 0; }
GB_unop__identity_uint32_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint32_uint8) // op(A') function: GB (_unop_tran__identity_uint32_uint8) // C type: uint32_t // A type: uint8_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint32_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 = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = (uint32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = (uint32_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint32_uint8) ( uint32_t *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t aij = Ax [p] ; uint32_t z = (uint32_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint8_t aij = Ax [p] ; uint32_t z = (uint32_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint32_uint8) ( 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-simple.c
/* Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Simone Atzeni (simone@cs.utah.edu), Joachim Protze (joachim.protze@tu-dresden.de), Jonas Hahnfeld (hahnfeld@itc.rwth-aachen.de), Ganesh Gopalakrishnan, Zvonimir Rakamaric, Dong H. Ahn, Gregory L. Lee, Ignacio Laguna, and Martin Schulz. LLNL-CODE-773957 All rights reserved. This file is part of Archer. For details, see https://pruners.github.io/archer. Please also read https://github.com/PRUNERS/archer/blob/master/LICENSE. 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. */ // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> int main(int argc, char* argv[]) { int var = 0; #pragma omp parallel num_threads(2) shared(var) { if (omp_get_thread_num() == 1) { var++; } } // implicit barrier var++; fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK: DONE
symv_x_csr_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include<stdlib.h> static alphasparse_status_t symv_s_csr_u_hi_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mule(y[i], beta); alpha_madde(y[i], alpha, x[i]); } ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT); for(ALPHA_INT i = 0; i < num_threads; i++) { y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); memset(y_local[i], '\0', sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_Number tmp; for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col <= i) { continue; } else { alpha_setzero(tmp); alpha_mul(tmp, alpha, A->values[ai]); alpha_madde(y_local[tid][col], tmp, x[i]); alpha_madde(y_local[tid][i], tmp, x[col]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT row = 0; row < m; row++) for(ALPHA_INT i = 0; i < num_threads; i++) alpha_adde(y[row], y_local[i][row]); for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_free(y_local[i]); } alpha_free(y_local); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return symv_s_csr_u_hi_omp(alpha, A, x, beta, y); }
shared-2.c
#include <stdio.h> #include <omp.h> extern void abort (void); void parallel (int a, int b) { int bad, LASTPRIV, LASTPRIV_SEC; int i; a = b = 3; bad = 0; #pragma omp parallel firstprivate (a,b) shared (bad) num_threads (5) { if (a != 3 || b != 3) bad = 1; #pragma omp for lastprivate (LASTPRIV) for (i = 0; i < 10; i++) LASTPRIV = i; #pragma omp sections lastprivate (LASTPRIV_SEC) { #pragma omp section { LASTPRIV_SEC = 3; } #pragma omp section { LASTPRIV_SEC = 42; } } } if (LASTPRIV != 9) abort (); if (LASTPRIV_SEC != 42) abort (); if (bad) abort (); } int main() { parallel (1, 2); return 0; }
uccsd_t.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 <stdio.h> #include <stdlib.h> #include "config.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #include <assert.h> typedef struct { void *cache[6]; short a; short b; short c; short _padding; } CacheJob; int Sc (int i, int a, int nocc); int Dc (int i, int j, int a, int b, int nocc2); int Tc (int i, int j, int k, int a, int b, int c, int nocc3); int DSc(int i, int j, int k, int a, int b, int c, int nocc, int nvir, int nocc2); int SDc(int i, int j, int k, int a, int b, int c, int nocc, int nvir, int nocc2) { return Sc(i, a, nocc) * nocc2 * nvir*(nvir-1)/2 + Dc(j, k, b, c, nocc2); } int S(int i, int a, int nvir); int D(int i, int j, int a, int b, int nocc, int nvir); size_t T(int i, int j, int k, int a, int b, int c, int nocc, int nvir); int SD(int i, int j, int k, int a, int b, int c, int nocc, int nvir) { return S(i, a, nvir) * nocc * nocc * nvir * nvir + D(j, k, b, c, nocc, nvir); } double _ccsd_t_get_energy(double *w, double *v, double *mo_energy, int nocc, int a, int b, int c, double fac); size_t _ccsd_t_gen_jobs(CacheJob *jobs, int nocc, int nvir, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b, size_t stride); void _make_permute_indices(int *idx, int n); double _ccsd_t_zget_energy(double complex *w, double complex *v, double *mo_energy, int nocc, int a, int b, int c, double fac); int comparator (const void * p1, const void * p2) { return (*(int*)p1 - *(int*)p2); } double _ecccsd_t_get_energy(double *w, double *v, double *mo_energy, double *paaa, int nocc, int nocc3, int nocc_iact, int a, int b, int c, double fac) { int i, j, k, n; int it, jt, kt, at, bt, ct; double abc = mo_energy[nocc+a] + mo_energy[nocc+b] + mo_energy[nocc+c]; double et = 0; double exclude = 1.0; int arr[3] = {a, b, c}; qsort(arr, 3, sizeof(int), comparator); at = arr[0]; bt = arr[1]; ct = arr[2]; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { arr[0]=i; arr[1]=j; arr[2]=k; qsort(arr, 3, sizeof(int), comparator); it = arr[0]-nocc_iact; jt = arr[1]-nocc_iact; kt = arr[2]-nocc_iact; if ( it != jt && jt != kt ) exclude = paaa[Tc(it, jt, kt, at, bt, ct, nocc3)]; et += fac * w[n] * v[n] / (mo_energy[i] + mo_energy[j] + mo_energy[k] - abc) * exclude; } } } return et; } /* * w + w.transpose(1,2,0) + w.transpose(2,0,1) * - w.transpose(2,1,0) - w.transpose(0,2,1) - w.transpose(1,0,2) */ static void add_and_permute(double *out, double *w, double *v, int n) { int nn = n * n; int nnn = nn * n; int i, j, k; for (i = 0; i < nnn; i++) { v[i] += w[i]; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { out[i*nn+j*n+k] = v[i*nn+j*n+k] + v[j*nn+k*n+i] + v[k*nn+i*n+j] - v[k*nn+j*n+i] - v[i*nn+k*n+j] - v[j*nn+i*n+k]; } } } } /* * t2T = t2.transpose(2,3,0,1) * ov = vv_op[:,nocc:] * oo = vv_op[:,:nocc] * w = numpy.einsum('if,fjk->ijk', -ov, t2T[c]) * w-= numpy.einsum('ijm,mk->ijk', vooo[a], t2T[b,c]) * v = numpy.einsum('ij,k->ijk', oo, t1T[c]) * v+= w */ static void get_wv(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1T, double *t2T, int nocc, int nvir, int a, int b, int c, int *idx) { const double D0 = 0; const double D1 = 1; const double DN1 =-1; const char TRANS_N = 'N'; const char TRANS_T = 'T'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double *pt2T; dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &DN1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); dgemm_(&TRANS_N, &TRANS_T, &nocc, &noo, &nocc, &DN1, t2T+b*nvoo+c*noo, &nocc, vooo+a*nooo, &noo, &D1, cache, &nocc); pt2T = t2T + a * nvoo + b * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { w[idx[n]] += cache[n]; v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } ////full p mat version //static void get_wv_ec(double *w, double *v, double *cache, // double *fvohalf, double *vooo, // double *vv_op, double *t1T, double *t2T, // double *paaa, int nocc, int nocc3, int nocc_iact, // int nvir, int a, int b, int c, int *idx) //{ // const double D0 = 0; // const double D1 = 1; // const double DN1 =-1; // const char TRANS_N = 'N'; // const char TRANS_T = 'T'; // const int nmo = nocc + nvir; // const int noo = nocc * nocc; // const size_t nooo = nocc * noo; // const size_t nvoo = nvir * noo; // int i, j, k, n; // double *pt2T; // // dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, // &DN1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, // &D0, cache, &noo); // dgemm_(&TRANS_N, &TRANS_T, &nocc, &noo, &nocc, // &DN1, t2T+b*nvoo+c*noo, &nocc, vooo+a*nooo, &noo, // &D1, cache, &nocc); // // pt2T = t2T + a * nvoo + b * noo; // for (n = 0, i = 0; i < nocc; i++) { // for (j = 0; j < nocc; j++) { // for (k = 0; k < nocc; k++, n++) { // w[idx[n]] += cache[n] * paaa[T(i-nocc_iact, j-nocc_iact, k-nocc_iact, a, b, c, nocc, nvir)]; // v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] // + pt2T[i*nocc+j] * fvohalf[c*nocc+k]) * paaa[T(i-nocc_iact, j-nocc_iact, k-nocc_iact, a, b, c, nocc, nvir)]; // } } } //} // off diag version static void get_wv_ec(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1T, double *t2T, double *paaa, int nocc, int nocc3, int nocc_iact, int nvir, int nvir_cas, int a, int b, int c, int *idx) { const double D0 = 0; const double D1 = 1; const double DN1 =-1; const char TRANS_N = 'N'; const char TRANS_T = 'T'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double *pt2T; int it, jt, kt, at, bt, ct; double exclude = 1.0; int arr[3] = {a, b, c}; qsort(arr, 3, sizeof(int), comparator); at = arr[0]; bt = arr[1]; ct = arr[2]; dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &DN1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); dgemm_(&TRANS_N, &TRANS_T, &nocc, &noo, &nocc, &DN1, t2T+b*nvoo+c*noo, &nocc, vooo+a*nooo, &noo, &D1, cache, &nocc); pt2T = t2T + a * nvoo + b * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { arr[0]=i; arr[1]=j; arr[2]=k; qsort(arr, 3, sizeof(int), comparator); it = arr[0]-nocc_iact; jt = arr[1]-nocc_iact; kt = arr[2]-nocc_iact; if ( it >= 0 && jt >= 0 && kt >= 0 && it != jt && jt != kt && it != kt && at != bt && bt != ct && at != ct && at < nvir_cas && bt < nvir_cas && ct < nvir_cas ){ exclude = paaa[Tc(it, jt, kt, at, bt, ct, nocc3)]; //printf("idx: %d for %d %d %d %d %d %d\n",Tc(it, jt, kt, at, bt, ct, nocc3),it, jt, kt, at, bt, ct); //if (exclude == 1.0) printf("no exclude: %d %d %d %d %d %d\n",it+nocc_iact,jt+nocc_iact,kt+nocc_iact,at+nocc,bt+nocc,ct+nocc); } else exclude = 1.0; w[idx[n]] += cache[n] * exclude; v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]) * exclude; } } } } // off diag version static void get_wv_ecr(double *w, double *v, double *y, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1T, double *t2T, double *paaa, int nocc, int nocc3, int nocc_iact, int nvir, int nvir_cas, int a, int b, int c, int *idx) { const double D0 = 0; const double D1 = 1; const double DN1 =-1; const char TRANS_N = 'N'; const char TRANS_T = 'T'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double *pt2Tab, *pt2Tbc, *pt2Tac; int it, jt, kt, at, bt, ct; double exclude = 1.0; int arr[3] = {a, b, c}; qsort(arr, 3, sizeof(int), comparator); at = arr[0]; bt = arr[1]; ct = arr[2]; dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &DN1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); dgemm_(&TRANS_N, &TRANS_T, &nocc, &noo, &nocc, &DN1, t2T+b*nvoo+c*noo, &nocc, vooo+a*nooo, &noo, &D1, cache, &nocc); pt2Tab = t2T + a * nvoo + b * noo; pt2Tbc = t2T + b * nvoo + c * noo; pt2Tac = t2T + a * nvoo + c * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { arr[0]=i; arr[1]=j; arr[2]=k; qsort(arr, 3, sizeof(int), comparator); it = arr[0]-nocc_iact; jt = arr[1]-nocc_iact; kt = arr[2]-nocc_iact; if ( it >= 0 && jt >= 0 && kt >= 0 && it != jt && jt != kt && it != kt && at != bt && bt != ct && at != ct && at < nvir_cas && bt < nvir_cas && ct < nvir_cas ){ exclude = paaa[Tc(it, jt, kt, at, bt, ct, nocc3)]; //printf("idx: %d for %d %d %d %d %d %d\n",Tc(it, jt, kt, at, bt, ct, nocc3),it, jt, kt, at, bt, ct); //if (exclude == 1.0) printf("no exclude: %d %d %d %d %d %d\n",it+nocc_iact,jt+nocc_iact,kt+nocc_iact,at+nocc,bt+nocc,ct+nocc); } else exclude = 1.0; w[idx[n]] += cache[n] * exclude; v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] + pt2Tab[i*nocc+j]* fvohalf[c*nocc+k]) * exclude; y[idx[n]] += (t1T[a*nocc+i] * t1T[b*nocc+j] * t1T[c*nocc+k] +t1T[a*nocc+i] * pt2Tbc[j*nocc+k] +t1T[b*nocc+j] * pt2Tac[i*nocc+k] +t1T[c*nocc+k] * pt2Tab[i*nocc+j])* exclude; } } } } static void sym_wv(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1T, double *t2T, int nocc, int nvir, int a, int b, int c, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, int *idx) { const double D0 = 0; const double D1 = 1; const char TRANS_N = 'N'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const int nooo = nocc * noo; const int nvoo = nvir * noo; int a_irrep = orbsym[nocc+a]; int b_irrep = orbsym[nocc+b]; int c_irrep = orbsym[nocc+c]; int ab_irrep = a_irrep ^ b_irrep; int bc_irrep = c_irrep ^ b_irrep; int i, j, k, n; int fr, f0, f1, df, mr, m0, m1, dm, mk0; int ir, i0, i1, di, kr, k0, k1, dk, jr; int ijr, ij0, ij1, dij, jkr, jk0, jk1, djk; double *pt2T; /* symmetry adapted * w = numpy.einsum('if,fjk->ijk', ov, t2T[c]) */ pt2T = t2T + c * nvoo; for (ir = 0; ir < nirrep; ir++) { i0 = o_ir_loc[ir]; i1 = o_ir_loc[ir+1]; di = i1 - i0; if (di > 0) { fr = ir ^ ab_irrep; f0 = v_ir_loc[fr]; f1 = v_ir_loc[fr+1]; df = f1 - f0; if (df > 0) { jkr = fr ^ c_irrep; jk0 = oo_ir_loc[jkr]; jk1 = oo_ir_loc[jkr+1]; djk = jk1 - jk0; if (djk > 0) { dgemm_(&TRANS_N, &TRANS_N, &djk, &di, &df, &D1, pt2T+f0*noo+jk0, &noo, vv_op+i0*nmo+nocc+f0, &nmo, &D0, cache, &djk); for (n = 0, i = o_ir_loc[ir]; i < o_ir_loc[ir+1]; i++) { for (jr = 0; jr < nirrep; jr++) { kr = jkr ^ jr; for (j = o_ir_loc[jr]; j < o_ir_loc[jr+1]; j++) { for (k = o_ir_loc[kr]; k < o_ir_loc[kr+1]; k++, n++) { w[idx[i*noo+j*nocc+k]] -= cache[n]; } } } } } } } } /* symmetry adapted * w-= numpy.einsum('ijm,mk->ijk', eris_vooo[a], t2T[c,b]) */ pt2T = t2T + c * nvoo + b * noo; vooo += a * nooo; mk0 = oo_ir_loc[bc_irrep]; for (mr = 0; mr < nirrep; mr++) { m0 = o_ir_loc[mr]; m1 = o_ir_loc[mr+1]; dm = m1 - m0; if (dm > 0) { kr = mr ^ bc_irrep; k0 = o_ir_loc[kr]; k1 = o_ir_loc[kr+1]; dk = k1 - k0; if (dk > 0) { ijr = mr ^ a_irrep; ij0 = oo_ir_loc[ijr]; ij1 = oo_ir_loc[ijr+1]; dij = ij1 - ij0; if (dij > 0) { dgemm_(&TRANS_N, &TRANS_N, &dk, &dij, &dm, &D1, pt2T+mk0, &dk, vooo+ij0*nocc+m0, &nocc, &D0, cache, &dk); for (n = 0, ir = 0; ir < nirrep; ir++) { jr = ijr ^ ir; for (i = o_ir_loc[ir]; i < o_ir_loc[ir+1]; i++) { for (j = o_ir_loc[jr]; j < o_ir_loc[jr+1]; j++) { for (k = o_ir_loc[kr]; k < o_ir_loc[kr+1]; k++, n++) { w[idx[i*noo+j*nocc+k]] -= cache[n]; } } } } } mk0 += dm * dk; } } } pt2T = t2T + a * nvoo + b * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } static double contract6_aaa(int nocc, int nvir, int a, int b, int c, double *mo_energy, double *t1T, double *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *fvo, double *vooo, double *cache1, void **cache, int *permute_idx) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double *v0 = cache1; double *w0 = v0 + nooo; double *z0 = w0 + nooo; double *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } if (nirrep == 1) { get_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, idx0); get_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, idx1); get_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, idx2); get_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, idx3); get_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, idx4); get_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, idx5); } else { sym_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx0); sym_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx1); sym_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx2); sym_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx3); sym_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx4); sym_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx5); } add_and_permute(z0, w0, v0, nocc); double et; if (a == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } static double eccontract6_aaa(int nocc, int nocc3, int nocc_iact, int nvir, int nvir_cas, int a, int b, int c, double *mo_energy, double *t1T, double *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *fvo, double *vooo, double *cache1, void **cache, int *permute_idx, double *paaa) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double *v0 = cache1; double *w0 = v0 + nooo; double *z0 = w0 + nooo; double *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } if (nirrep == 1) { get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, a, b, c, idx0); get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, a, c, b, idx1); get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, b, a, c, idx2); get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, b, c, a, idx3); get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, c, a, b, idx4); get_wv_ec(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, c, b, a, idx5); // get_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, idx0); // get_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, idx1); // get_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, idx2); // get_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, idx3); // get_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, idx4); // get_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, idx5); } else { printf("Not implemented yet"); sym_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx0); sym_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx1); sym_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx2); sym_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx3); sym_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx4); sym_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx5); } add_and_permute(z0, w0, v0, nocc); double et; if (a == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } static void permute(double *out, double *v, int n) { int nn = n * n; int nnn = nn * n; int i, j, k; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { out[i*nn+j*n+k] = v[i*nn+j*n+k] * 4 + v[j*nn+k*n+i] + v[k*nn+i*n+j] - v[k*nn+j*n+i] * 2 - v[i*nn+k*n+j] * 2 - v[j*nn+i*n+k] * 2; } } } } double _rccsd_t_get_denom(double *w, double *v, double *mo_energy, int nocc, int a, int b, int c, double fac) { int i, j, k, n; double abc = mo_energy[nocc+a] + mo_energy[nocc+b] + mo_energy[nocc+c]; double dn = 0; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { dn += fac * w[n] * v[n] / (mo_energy[i] + mo_energy[j] + mo_energy[k] - abc); } } } return dn; } static void ecrcontract6_aaa(double et, double dn, int nocc, int nocc3, int nocc_iact, int nvir, int nvir_cas, int a, int b, int c, double *mo_energy, double *t1T, double *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *fvo, double *vooo, double *cache1, void **cache, int *permute_idx, double *paaa) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double *v0 = cache1; double *w0 = v0 + nooo; double *z0 = w0 + nooo; double *y0 = z0 + nooo; double *wtmp = y0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; y0[i] = 0; } if (nirrep == 1) { get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[0], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, a, b, c, idx0); get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[1], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, a, c, b, idx1); get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[2], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, b, a, c, idx2); get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[3], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, b, c, a, idx3); get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[4], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, c, a, b, idx4); get_wv_ecr(w0, v0, y0, wtmp, fvo, vooo, cache[5], t1T, t2T, paaa, nocc, nocc3, nocc_iact, nvir, nvir_cas, c, b, a, idx5); } else { printf("Not implemented yet"); sym_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx0); sym_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx1); sym_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx2); sym_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx3); sym_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx4); sym_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx5); } add_and_permute(z0, w0, v0, nocc); if (a == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } for (i = 0; i < nooo; i++) { w0[i] = 0; } permute(w0, y0, nocc); if (a == c) { dn = _rccsd_t_get_denom(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { dn = _rccsd_t_get_denom(w0, z0, mo_energy, nocc, a, b, c, .5); } else { dn = _rccsd_t_get_denom(w0, z0, mo_energy, nocc, a, b, c, 1.); } } void CCuccsd_t_aaa(double complex *e_tot, double *mo_energy, double *t1T, double *t2T, double *vooo, double *fvo, int nocc, int nvir, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *cache_row_a, double *cache_col_a, double *cache_row_b, double *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); double fvohalf[nvir*nocc]; int i; for (i = 0; i < nvir*nocc; i++) { fvohalf[i] = fvo[i] * .5; } int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvohalf, jobs, e_tot, \ permute_idx) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (nocc*nocc*nocc*3+2)); double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += contract6_aaa(nocc, nvir, a, b, c, mo_energy, t1T, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx); } free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); } void CCecccsd_t_aaa(double complex *e_tot, double *mo_energy, double *t1T, double *t2T, double *vooo, double *fvo, double *paaa, int nocc, int nvir, const int nocc_iact, const int nvir_cas, const int nocc3, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *cache_row_a, double *cache_col_a, double *cache_row_b, double *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); double fvohalf[nvir*nocc]; int i; for (i = 0; i < nvir*nocc; i++) { fvohalf[i] = fvo[i] * .5; } int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvohalf, jobs, e_tot, \ permute_idx, paaa) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (nocc*nocc*nocc*3+2)); double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += eccontract6_aaa(nocc, nocc3, nocc_iact, nvir, nvir_cas, a, b, c, mo_energy, t1T, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx, paaa); } free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); } void CCecrccsd_t_aaa(double complex *e_tot, double complex *denom, double *mo_energy, double *t1T, double *t2T, double *vooo, double *fvo, double *paaa, int nocc, int nvir, const int nocc_iact, const int nvir_cas, const int nocc3, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *cache_row_a, double *cache_col_a, double *cache_row_b, double *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); double fvohalf[nvir*nocc]; int i; for (i = 0; i < nvir*nocc; i++) { fvohalf[i] = fvo[i] * .5; } int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvohalf, jobs, e_tot, \ denom, permute_idx, paaa) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (nocc*nocc*nocc*4+2)); double e = 0; double d = 0; double etmp, dtmp; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; ecrcontract6_aaa(etmp, dtmp, nocc, nocc3, nocc_iact, nvir, nvir_cas, a, b, c, mo_energy, t1T, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx, paaa); e += etmp; d += dtmp; } free(cache1); #pragma omp critical *e_tot += e; *denom += d; } free(permute_idx); } /************************************************* * * UCCSD(T) beta-alpha-alpha * *************************************************/ static void get_wv_baa(double *w, double *v, double **vs_ts, double **cache, int nocca, int noccb, int nvira, int nvirb, int a, int b, int c) { double *fvo = vs_ts[2]; double *fVO = vs_ts[3]; double *vooo = vs_ts[4]; double *vOoO = vs_ts[5]; double *VoOo = vs_ts[6]; double *t1aT = vs_ts[7]; double *t1bT = vs_ts[8]; double *t2aaT = vs_ts[9]; double *t2abT = vs_ts[10]; double *vvop = cache[0]; double *vVoP = cache[1]; double *VvOp = cache[2]; const double D0 = 0; const double D1 = 1; const double D2 = 2; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const int nmoa = nocca + nvira; const int nmob = noccb + nvirb; const int noo = nocca * nocca; const int nOo = noccb * nocca; const size_t nooo = nocca * noo; const size_t noOo = nocca * nOo; const size_t nOoO = noccb * nOo; const size_t nvoo = nvira * noo; const int nVoO = nvirb * nOo; int i, j, k, n; /* * t2aaT = t2aa.transpose(2,3,0,1) * w = numpy.einsum('ejI,ke->Ijk', t2abT[:,a], vvov) * 2 * w += numpy.einsum('EjI,kE->Ijk', t2abT[b,:], vVoV) * 2 * w += numpy.einsum('mj,mIk->Ijk', t2aaT[b,c], VoOo[a,:]) * w += numpy.einsum('kM,MjI->Ijk', t2abT[b,a], vOoO[c,:]) * 2 * w += numpy.einsum('ejk,Ie->Ijk', t2aaT[b,:], VvOv) * w += numpy.einsum('mI,mjk->Ijk', t2abT[b,a], vooo[c,:]) * 2 * v = numpy.einsum('kj,I->Ijk', vvoo, t1bT[a]) * v += numpy.einsum('Ik,j->Ijk', VvOo, t1aT[b]) * 2 * v += numpy.einsum('jk,I->Ijk', t2aaT[b,c], fVO[a]) * .5 * v += numpy.einsum('kI,j->Ijk', t2abT[c,a], fvo[b]) * 2 * v += w */ dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvira, &D2, vvop+nocca, &nmoa, t2abT+a*nOo, &nVoO, &D0, v, &nocca); dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvirb, &D2, vVoP+noccb, &nmob, t2abT+b*(size_t)nVoO, &nOo, &D1, v, &nocca); dgemm_(&TRANS_N, &TRANS_T, &nOo, &nocca, &nocca, &D1, VoOo+a*noOo, &nOo, t2aaT+b*nvoo+c*noo, &nocca, &D1, v, &nOo); dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &noccb, &D2, t2abT+b*(size_t)nVoO+a*nOo, &noccb, vOoO+c*nOoO, &nOo, &D1, v, &nocca); for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { w[n] = v[j*nOo+i*nocca+k]; } } } dgemm_(&TRANS_N, &TRANS_N, &noo, &noccb, &nvira, &D1, t2aaT+b*nvoo, &noo, VvOp+nocca, &nmoa, &D1, w, &noo); dgemm_(&TRANS_N, &TRANS_T, &noo, &noccb, &nocca, &D2, vooo+c*nooo, &noo, t2abT+b*(size_t)nVoO+a*nOo, &noccb, &D1, w, &noo); double t1aT2[nocca]; double fvo2[nocca]; double fVOhalf[noccb]; for (i = 0; i < nocca; i++) { t1aT2[i] = t1aT[b*nocca+i] * 2; fvo2[i] = fvo[b*nocca+i] * 2; } for (i = 0; i < noccb; i++) { fVOhalf[i] = fVO[a*noccb+i] * .5; } double *pt2aaT = t2aaT + b * nvoo + c * noo; double *pt2abT = t2abT + (c*nvirb+a) * nOo; for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { v[n] = (w[n] + vvop[k*nmoa+j] * t1bT[a*noccb+i] + VvOp[i*nmoa+k] * t1aT2[j] + pt2aaT[j*nocca+k] * fVOhalf[i] + pt2abT[k*noccb+i] * fvo2[j]); } } } } //static void get_wv_baa_ec(double *w, double *v, double **vs_ts, double **cache, // int nocca, int noccb, int nvira, int nvirb, // int nocc_cas, int nvir_cas, int nocc_iact, int nocc2, // int a, int b, int c) //{ // double *fvo = vs_ts[2]; // double *fVO = vs_ts[3]; // double *vooo = vs_ts[4]; // double *vOoO = vs_ts[5]; // double *VoOo = vs_ts[6]; // double *t1aT = vs_ts[7]; // double *t1bT = vs_ts[8]; // double *t2aaT = vs_ts[9]; // double *t2abT = vs_ts[10]; // double *pbaa = vs_ts[11]; // double *vvop = cache[0]; // double *vVoP = cache[1]; // double *VvOp = cache[2]; // const double D0 = 0; // const double D1 = 1; // const double D2 = 2; // const char TRANS_T = 'T'; // const char TRANS_N = 'N'; // const int nmoa = nocca + nvira; // const int nmob = noccb + nvirb; // const int noo = nocca * nocca; // const int nOo = noccb * nocca; // const size_t nooo = nocca * noo; // const size_t noOo = nocca * nOo; // const size_t nOoO = noccb * nOo; // const size_t nvoo = nvira * noo; // const int nVoO = nvirb * nOo; // int i, j, k, n; // ///* // * t2aaT = t2aa.transpose(2,3,0,1) // * w = numpy.einsum('ejI,ke->Ijk', t2abT[:,a], vvov) * 2 // * w += numpy.einsum('EjI,kE->Ijk', t2abT[b,:], vVoV) * 2 // * w += numpy.einsum('mj,mIk->Ijk', t2aaT[b,c], VoOo[a,:]) // * w += numpy.einsum('kM,MjI->Ijk', t2abT[b,a], vOoO[c,:]) * 2 // * w += numpy.einsum('ejk,Ie->Ijk', t2aaT[b,:], VvOv) // * w += numpy.einsum('mI,mjk->Ijk', t2abT[b,a], vooo[c,:]) * 2 // * v = numpy.einsum('kj,I->Ijk', vvoo, t1bT[a]) // * v += numpy.einsum('Ik,j->Ijk', VvOo, t1aT[b]) * 2 // * v += numpy.einsum('jk,I->Ijk', t2aaT[b,c], fVO[a]) * .5 // * v += numpy.einsum('kI,j->Ijk', t2abT[c,a], fvo[b]) * 2 // * v += w // */ // dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvira, // &D2, vvop+nocca, &nmoa, t2abT+a*nOo, &nVoO, // &D0, v, &nocca); // dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvirb, // &D2, vVoP+noccb, &nmob, t2abT+b*(size_t)nVoO, &nOo, // &D1, v, &nocca); // dgemm_(&TRANS_N, &TRANS_T, &nOo, &nocca, &nocca, // &D1, VoOo+a*noOo, &nOo, t2aaT+b*nvoo+c*noo, &nocca, // &D1, v, &nOo); // dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &noccb, // &D2, t2abT+b*(size_t)nVoO+a*nOo, &noccb, vOoO+c*nOoO, &nOo, // &D1, v, &nocca); // for (n = 0, i = 0; i < noccb; i++) { // for (j = 0; j < nocca; j++) { // for (k = 0; k < nocca; k++, n++) { // w[n] = v[j*nOo+i*nocca+k] * pbaa[T(i-nocc_iact, j-nocc_iact, k-nocc_iact, a, b, c, nocca, nvira)]; // } } } // dgemm_(&TRANS_N, &TRANS_N, &noo, &noccb, &nvira, // &D1, t2aaT+b*nvoo, &noo, VvOp+nocca, &nmoa, // &D1, w, &noo); // dgemm_(&TRANS_N, &TRANS_T, &noo, &noccb, &nocca, // &D2, vooo+c*nooo, &noo, t2abT+b*(size_t)nVoO+a*nOo, &noccb, // &D1, w, &noo); // // double t1aT2[nocca]; // double fvo2[nocca]; // double fVOhalf[noccb]; // for (i = 0; i < nocca; i++) { // t1aT2[i] = t1aT[b*nocca+i] * 2; // fvo2[i] = fvo[b*nocca+i] * 2; // } // for (i = 0; i < noccb; i++) { // fVOhalf[i] = fVO[a*noccb+i] * .5; // } // double *pt2aaT = t2aaT + b * nvoo + c * noo; // double *pt2abT = t2abT + (c*nvirb+a) * nOo; // for (n = 0, i = 0; i < noccb; i++) { // for (j = 0; j < nocca; j++) { // for (k = 0; k < nocca; k++, n++) { // v[n] = (w[n] + vvop[k*nmoa+j] * t1bT[a*noccb+i] // + VvOp[i*nmoa+k] * t1aT2[j] // + pt2aaT[j*nocca+k] * fVOhalf[i] // + pt2abT[k*noccb+i] * fvo2[j]) * pbaa[T(i-nocc_iact, j-nocc_iact, k-nocc_iact, a, b, c, nocca, nvira)]; // } } } //} // off diag version static void get_wv_baa_ec(double *w, double *v, double **vs_ts, double **cache, int nocca, int noccb, int nvira, int nvirb, int nocc_cas, int nvir_cas, int nocc_iact, int nocc2, int a, int b, int c) { double *fvo = vs_ts[2]; double *fVO = vs_ts[3]; double *vooo = vs_ts[4]; double *vOoO = vs_ts[5]; double *VoOo = vs_ts[6]; double *t1aT = vs_ts[7]; double *t1bT = vs_ts[8]; double *t2aaT = vs_ts[9]; double *t2abT = vs_ts[10]; double *pbaa = vs_ts[11]; double *vvop = cache[0]; double *vVoP = cache[1]; double *VvOp = cache[2]; const double D0 = 0; const double D1 = 1; const double D2 = 2; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const int nmoa = nocca + nvira; const int nmob = noccb + nvirb; const int noo = nocca * nocca; const int nOo = noccb * nocca; const size_t nooo = nocca * noo; const size_t noOo = nocca * nOo; const size_t nOoO = noccb * nOo; const size_t nvoo = nvira * noo; const int nVoO = nvirb * nOo; int i, j, k, n; int it, jt, kt, at, bt, ct; double exclude = 1.0; int arr[2] = {b, c}; qsort(arr, 2, sizeof(int), comparator); at = a; bt = arr[0]; ct = arr[1]; /* * t2aaT = t2aa.transpose(2,3,0,1) * w = numpy.einsum('ejI,ke->Ijk', t2abT[:,a], vvov) * 2 * w += numpy.einsum('EjI,kE->Ijk', t2abT[b,:], vVoV) * 2 * w += numpy.einsum('mj,mIk->Ijk', t2aaT[b,c], VoOo[a,:]) * w += numpy.einsum('kM,MjI->Ijk', t2abT[b,a], vOoO[c,:]) * 2 * w += numpy.einsum('ejk,Ie->Ijk', t2aaT[b,:], VvOv) * w += numpy.einsum('mI,mjk->Ijk', t2abT[b,a], vooo[c,:]) * 2 * v = numpy.einsum('kj,I->Ijk', vvoo, t1bT[a]) * v += numpy.einsum('Ik,j->Ijk', VvOo, t1aT[b]) * 2 * v += numpy.einsum('jk,I->Ijk', t2aaT[b,c], fVO[a]) * .5 * v += numpy.einsum('kI,j->Ijk', t2abT[c,a], fvo[b]) * 2 * v += w */ dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvira, &D2, vvop+nocca, &nmoa, t2abT+a*nOo, &nVoO, &D0, v, &nocca); dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvirb, &D2, vVoP+noccb, &nmob, t2abT+b*(size_t)nVoO, &nOo, &D1, v, &nocca); dgemm_(&TRANS_N, &TRANS_T, &nOo, &nocca, &nocca, &D1, VoOo+a*noOo, &nOo, t2aaT+b*nvoo+c*noo, &nocca, &D1, v, &nOo); dgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &noccb, &D2, t2abT+b*(size_t)nVoO+a*nOo, &noccb, vOoO+c*nOoO, &nOo, &D1, v, &nocca); for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { arr[0]=j; arr[1]=k; qsort(arr, 2, sizeof(int), comparator); it = i-nocc_iact; jt = arr[0]-nocc_iact; kt = arr[1]-nocc_iact; if ( it >=0 && jt >= 0 && kt >= 0 && jt != kt && bt != ct && at < nvir_cas && bt < nvir_cas && ct < nvir_cas ) exclude = pbaa[SDc(it, jt, kt, at, bt, ct, nocc_cas, nvir_cas, nocc2)]; else exclude = 1.0; //printf("%d %d %d %d %d %d, exclude: %f\n",i,j,k,a,b,c,exclude); assert(exclude == 1.0 || exclude == 0.0); w[n] = v[j*nOo+i*nocca+k] * exclude; } } } dgemm_(&TRANS_N, &TRANS_N, &noo, &noccb, &nvira, &D1, t2aaT+b*nvoo, &noo, VvOp+nocca, &nmoa, &D1, w, &noo); dgemm_(&TRANS_N, &TRANS_T, &noo, &noccb, &nocca, &D2, vooo+c*nooo, &noo, t2abT+b*(size_t)nVoO+a*nOo, &noccb, &D1, w, &noo); double t1aT2[nocca]; double fvo2[nocca]; double fVOhalf[noccb]; for (i = 0; i < nocca; i++) { t1aT2[i] = t1aT[b*nocca+i] * 2; fvo2[i] = fvo[b*nocca+i] * 2; } for (i = 0; i < noccb; i++) { fVOhalf[i] = fVO[a*noccb+i] * .5; } double *pt2aaT = t2aaT + b * nvoo + c * noo; double *pt2abT = t2abT + (c*nvirb+a) * nOo; for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { arr[0]=j; arr[1]=k; qsort(arr, 2, sizeof(int), comparator); it = i-nocc_iact; jt = arr[0]-nocc_iact; kt = arr[1]-nocc_iact; if ( it >=0 && jt >= 0 && kt >= 0 && jt != kt && bt != ct && at < nvir_cas && bt < nvir_cas && ct < nvir_cas ) exclude = pbaa[SDc(it, jt, kt, at, bt, ct, nocc_cas, nvir_cas, nocc2)]; else exclude = 1.0; assert(exclude == 1.0 || exclude == 0.0); v[n] = (w[n] + vvop[k*nmoa+j] * t1bT[a*noccb+i] + VvOp[i*nmoa+k] * t1aT2[j] + pt2aaT[j*nocca+k] * fVOhalf[i] + pt2abT[k*noccb+i] * fvo2[j]) * exclude; } } } } /* * w - w.transpose(0,2,1) */ static void permute_baa(double *out, double *w, int nocca, int noccb) { int noo = nocca * nocca; int n; int i, j, k; for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { out[n] = w[i*noo+j*nocca+k] - w[i*noo+k*nocca+j]; } } } } static double _get_energy_baa_ec(double *z0, double *z1, double *w0, double *w1, double *mo_ea, double *mo_eb, double *pbaa, int nocca, int noccb, int nocc_cas, int nvir_cas, int nocc_iact, int nocc2, int a, int b, int c, double fac) { int noo = nocca * nocca; int i, j, k; int it, jt, kt, at, bt, ct; double abc = mo_eb[noccb+a] + mo_ea[nocca+b] + mo_ea[nocca+c]; double et = 0; double exclude = 1.0; int arr[3] = {a, b, c}; qsort(arr, 3, sizeof(int), comparator); at = arr[0]; bt = arr[1]; ct = arr[2]; for (i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++) { arr[0]=i; arr[1]=j; arr[2]=k; qsort(arr, 3, sizeof(int), comparator); it = arr[0]-nocc_iact; jt = arr[1]-nocc_iact; kt = arr[2]-nocc_iact; if ( it != jt && jt != kt ) exclude = pbaa[DSc(it, jt, kt, at, bt, ct, nocc_cas, nvir_cas, nocc2)]; et += (z0[i*noo+j*nocca+k] + z1[i*noo+k*nocca+j]) * (w0[i*noo+j*nocca+k] + w1[i*noo+k*nocca+j]) * fac / (mo_eb[i] + mo_ea[j] + mo_ea[k] - abc) * exclude; } } } return et; } static double _get_energy_baa(double *z0, double *z1, double *w0, double *w1, double *mo_ea, double *mo_eb, int nocca, int noccb, int a, int b, int c, double fac) { int noo = nocca * nocca; int i, j, k; double abc = mo_eb[noccb+a] + mo_ea[nocca+b] + mo_ea[nocca+c]; double et = 0; for (i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++) { et += (z0[i*noo+j*nocca+k] + z1[i*noo+k*nocca+j]) * (w0[i*noo+j*nocca+k] + w1[i*noo+k*nocca+j]) * fac / (mo_eb[i] + mo_ea[j] + mo_ea[k] - abc); } } } return et; } static double contract6_baa(int nocca, int noccb, int nvira, int nvirb, int a, int b, int c, double **vs_ts, void **cache, double *cache1) { int nOoo = noccb * nocca * nocca; double *v0 = cache1; double *v1 = v0 + nOoo; double *w0 = v1 + nOoo; double *w1 = w0 + nOoo; double *z0 = w1 + nOoo; double *z1 = v0; get_wv_baa(w0, v0, vs_ts, ((double **)cache) , nocca, noccb, nvira, nvirb, a, b, c); get_wv_baa(w1, v1, vs_ts, ((double **)cache)+3, nocca, noccb, nvira, nvirb, a, c, b); permute_baa(z0, v0, nocca, noccb); permute_baa(z1, v1, nocca, noccb); double *mo_ea = vs_ts[0]; double *mo_eb = vs_ts[1]; double et; if (b == c) { et = _get_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, .5); } else { et = _get_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, 1.); } return et; } static double eccontract6_baa(int nocca, int noccb, int nvira, int nvirb, int nocc_cas, int nvir_cas, int nocc_iact, int nocc2, int a, int b, int c, double **vs_ts, void **cache, double *cache1) { int nOoo = noccb * nocca * nocca; double *v0 = cache1; double *v1 = v0 + nOoo; double *w0 = v1 + nOoo; double *w1 = w0 + nOoo; double *z0 = w1 + nOoo; double *z1 = v0; get_wv_baa_ec(w0, v0, vs_ts, ((double **)cache) , nocca, noccb, nvira, nvirb, nocc_cas, nvir_cas, nocc_iact, nocc2, a, b, c); get_wv_baa_ec(w1, v1, vs_ts, ((double **)cache)+3, nocca, noccb, nvira, nvirb, nocc_cas, nvir_cas, nocc_iact, nocc2, a, c, b); // get_wv_baa(w0, v0, vs_ts, ((double **)cache) , nocca, noccb, nvira, nvirb, a, b, c); // get_wv_baa(w1, v1, vs_ts, ((double **)cache)+3, nocca, noccb, nvira, nvirb, a, c, b); permute_baa(z0, v0, nocca, noccb); permute_baa(z1, v1, nocca, noccb); double *mo_ea = vs_ts[0]; double *mo_eb = vs_ts[1]; double et; if (b == c) { // printf("b==c in tabb\n"); et = _get_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, .5); } else { et = _get_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, 1.); //et = _get_energy_baa_ec(z0, z1, w0, w1, mo_ea, mo_eb, pbaa, nocca, noccb, // nocc_cas, nvir_cas, nocc_iact, nocc2, a, b, c, 1.); } return et; } static size_t gen_baa_jobs(CacheJob *jobs, int nocca, int noccb, int nvira, int nvirb, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b, size_t stride) { size_t nov = nocca * (nocca+nvira) * stride; size_t noV = nocca * (noccb+nvirb) * stride; size_t nOv = noccb * (nocca+nvira) * stride; int da = a1 - a0; int db = b1 - b0; int a, b, c; size_t m = 0; for (a = a0; a < a1; a++) { for (b = b0; b < b1; b++) { for (c = 0; c <= b; c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; if (c < b0) { jobs[m].cache[0] = cache_col_b + nov*(db*(c )+b-b0); } else { jobs[m].cache[0] = cache_row_b + nov*(b1*(c-b0)+b ); } jobs[m].cache[1] = cache_col_a + noV*(da *(c )+a-a0); jobs[m].cache[2] = cache_row_a + nOv*(nvira*(a-a0)+c ); jobs[m].cache[3] = cache_row_b + nov*(b1 *(b-b0)+c ); jobs[m].cache[4] = cache_col_a + noV*(da *(b )+a-a0); jobs[m].cache[5] = cache_row_a + nOv*(nvira*(a-a0)+b ); } } } return m; } void CCuccsd_t_baa(double complex *e_tot, double *mo_ea, double *mo_eb, double *t1aT, double *t1bT, double *t2aaT, double *t2abT, double *vooo, double *vOoO, double *VoOo, double *fvo, double *fVO, int nocca, int noccb, int nvira, int nvirb, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = gen_baa_jobs(jobs, nocca, noccb, nvira, nvirb, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); double *vs_ts[] = {mo_ea, mo_eb, fvo, fVO, vooo, vOoO, VoOo, t1aT, t1bT, t2aaT, t2abT}; #pragma omp parallel default(none) \ shared(njobs, nocca, noccb, nvira, nvirb, vs_ts, jobs, e_tot) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (noccb*nocca*nocca*5+1)); double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += contract6_baa(nocca, noccb, nvira, nvirb, a, b, c, vs_ts, jobs[k].cache, cache1); } free(cache1); #pragma omp critical *e_tot += e; } } void CCecccsd_t_baa(double complex *e_tot, double *mo_ea, double *mo_eb, double *t1aT, double *t1bT, double *t2aaT, double *t2abT, double *vooo, double *vOoO, double *VoOo, double *fvo, double *fVO, double *pbaa, int nocca, int noccb, int nvira, int nvirb, const int nocc_cas, const int nvir_cas, const int nocc_iact, const int nocc2, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = gen_baa_jobs(jobs, nocca, noccb, nvira, nvirb, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); double *vs_ts[] = {mo_ea, mo_eb, fvo, fVO, vooo, vOoO, VoOo, t1aT, t1bT, t2aaT, t2abT, pbaa}; #pragma omp parallel default(none) \ shared(njobs, nocca, noccb, nvira, nvirb, vs_ts, jobs, e_tot) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (noccb*nocca*nocca*5+1)); double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += eccontract6_baa(nocca, noccb, nvira, nvirb, nocc_cas, nvir_cas, nocc_iact, nocc2, a, b, c, vs_ts, jobs[k].cache, cache1); } free(cache1); #pragma omp critical *e_tot += e; } } /* * Complex version of all functions */ static void zadd_and_permute(double complex *out, double complex *w, double complex *v, int n) { int nn = n * n; int nnn = nn * n; int i, j, k; for (i = 0; i < nnn; i++) { v[i] += w[i]; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { out[i*nn+j*n+k] = v[i*nn+j*n+k] + v[j*nn+k*n+i] + v[k*nn+i*n+j] - v[k*nn+j*n+i] - v[i*nn+k*n+j] - v[j*nn+i*n+k]; } } } } static void zget_wv(double complex *w, double complex *v, double complex *cache, double complex *fvohalf, double complex *vooo, double complex *vv_op, double complex *t1T, double complex *t2T, int nocc, int nvir, int a, int b, int c, int *idx) { const double complex D0 = 0; const double complex D1 = 1; const double complex DN1 =-1; const char TRANS_N = 'N'; const char TRANS_T = 'T'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double complex *pt2T; zgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &DN1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); zgemm_(&TRANS_N, &TRANS_T, &nocc, &noo, &nocc, &DN1, t2T+b*nvoo+c*noo, &nocc, vooo+a*nooo, &noo, &D1, cache, &nocc); pt2T = t2T + a * nvoo + b * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { w[idx[n]] += cache[n]; v[idx[n]] +=(vv_op[i*nmo+j] * t1T[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } static double complex zcontract6_aaa(int nocc, int nvir, int a, int b, int c, double *mo_energy, double complex *t1T, double complex *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double complex *fvo, double complex *vooo, double complex *cache1, void **cache, int *permute_idx) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double complex *v0 = cache1; double complex *w0 = v0 + nooo; double complex *z0 = w0 + nooo; double complex *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } zget_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, idx0); zget_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, idx1); zget_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, idx2); zget_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, idx3); zget_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, idx4); zget_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, idx5); zadd_and_permute(z0, w0, v0, nocc); double complex et; if (a == c) { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } void CCuccsd_t_zaaa(double complex *e_tot, double *mo_energy, double complex *t1T, double complex *t2T, double complex *vooo, double complex *fvo, int nocc, int nvir, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double complex)); double complex fvohalf[nvir*nocc]; int i; for (i = 0; i < nvir*nocc; i++) { fvohalf[i] = fvo[i] * .5; } int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvohalf, jobs, e_tot, \ permute_idx) { int a, b, c; size_t k; double complex *cache1 = malloc(sizeof(double complex) * (nocc*nocc*nocc*3+2)); double complex e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += zcontract6_aaa(nocc, nvir, a, b, c, mo_energy, t1T, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx); } free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); } /************************************************* * * UCCSD(T) beta-alpha-alpha * *************************************************/ static void zget_wv_baa(double complex *w, double complex *v, double complex **vs_ts, double complex **cache, int nocca, int noccb, int nvira, int nvirb, int a, int b, int c) { double complex *fvo = vs_ts[2]; double complex *fVO = vs_ts[3]; double complex *vooo = vs_ts[4]; double complex *vOoO = vs_ts[5]; double complex *VoOo = vs_ts[6]; double complex *t1aT = vs_ts[7]; double complex *t1bT = vs_ts[8]; double complex *t2aaT = vs_ts[9]; double complex *t2abT = vs_ts[10]; double complex *vvop = cache[0]; double complex *vVoP = cache[1]; double complex *VvOp = cache[2]; const double complex D0 = 0; const double complex D1 = 1; const double complex D2 = 2; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const int nmoa = nocca + nvira; const int nmob = noccb + nvirb; const int noo = nocca * nocca; const int nOo = noccb * nocca; const size_t nooo = nocca * noo; const size_t noOo = nocca * nOo; const size_t nOoO = noccb * nOo; const size_t nvoo = nvira * noo; const int nVoO = nvirb * nOo; int i, j, k, n; zgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvira, &D2, vvop+nocca, &nmoa, t2abT+a*nOo, &nVoO, &D0, v, &nocca); zgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &nvirb, &D2, vVoP+noccb, &nmob, t2abT+b*(size_t)nVoO, &nOo, &D1, v, &nocca); zgemm_(&TRANS_N, &TRANS_T, &nOo, &nocca, &nocca, &D1, VoOo+a*noOo, &nOo, t2aaT+b*nvoo+c*noo, &nocca, &D1, v, &nOo); zgemm_(&TRANS_T, &TRANS_T, &nocca, &nOo, &noccb, &D2, t2abT+b*(size_t)nVoO+a*nOo, &noccb, vOoO+c*nOoO, &nOo, &D1, v, &nocca); for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { w[n] = v[j*nOo+i*nocca+k]; } } } zgemm_(&TRANS_N, &TRANS_N, &noo, &noccb, &nvira, &D1, t2aaT+b*nvoo, &noo, VvOp+nocca, &nmoa, &D1, w, &noo); zgemm_(&TRANS_N, &TRANS_T, &noo, &noccb, &nocca, &D2, vooo+c*nooo, &noo, t2abT+b*(size_t)nVoO+a*nOo, &noccb, &D1, w, &noo); double complex t1aT2[nocca]; double complex fvo2[nocca]; double complex fVOhalf[noccb]; for (i = 0; i < nocca; i++) { t1aT2[i] = t1aT[b*nocca+i] * 2; fvo2[i] = fvo[b*nocca+i] * 2; } for (i = 0; i < noccb; i++) { fVOhalf[i] = fVO[a*noccb+i] * .5; } double complex *pt2aaT = t2aaT + b * nvoo + c * noo; double complex *pt2abT = t2abT + (c*nvirb+a) * nOo; for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { v[n] = (w[n] + vvop[k*nmoa+j] * t1bT[a*noccb+i] + VvOp[i*nmoa+k] * t1aT2[j] + pt2aaT[j*nocca+k] * fVOhalf[i] + pt2abT[k*noccb+i] * fvo2[j]); } } } } /* * w - w.transpose(0,2,1) */ static void zpermute_baa(double complex *out, double complex *w, int nocca, int noccb) { int noo = nocca * nocca; int n; int i, j, k; for (n = 0, i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++, n++) { out[n] = w[i*noo+j*nocca+k] - w[i*noo+k*nocca+j]; } } } } static double complex _zget_energy_baa(double complex *z0, double complex *z1, double complex *w0, double complex *w1, double *mo_ea, double *mo_eb, int nocca, int noccb, int a, int b, int c, double fac) { int noo = nocca * nocca; int i, j, k; double abc = mo_eb[noccb+a] + mo_ea[nocca+b] + mo_ea[nocca+c]; double complex et = 0; for (i = 0; i < noccb; i++) { for (j = 0; j < nocca; j++) { for (k = 0; k < nocca; k++) { et += conj(z0[i*noo+j*nocca+k] + z1[i*noo+k*nocca+j]) * (w0[i*noo+j*nocca+k] + w1[i*noo+k*nocca+j]) * (fac / (mo_eb[i] + mo_ea[j] + mo_ea[k] - abc)); } } } return et; } static double complex zcontract6_baa(int nocca, int noccb, int nvira, int nvirb, int a, int b, int c, double complex **vs_ts, void **cache, double complex *cache1) { int nOoo = noccb * nocca * nocca; double complex *v0 = cache1; double complex *v1 = v0 + nOoo; double complex *w0 = v1 + nOoo; double complex *w1 = w0 + nOoo; double complex *z0 = w1 + nOoo; double complex *z1 = v0; zget_wv_baa(w0, v0, vs_ts, ((double complex **)cache) , nocca, noccb, nvira, nvirb, a, b, c); zget_wv_baa(w1, v1, vs_ts, ((double complex **)cache)+3, nocca, noccb, nvira, nvirb, a, c, b); zpermute_baa(z0, v0, nocca, noccb); zpermute_baa(z1, v1, nocca, noccb); double *mo_ea = (double *)vs_ts[0]; double *mo_eb = (double *)vs_ts[1]; double complex et; if (b == c) { et = _zget_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, .5); } else { et = _zget_energy_baa(z0, z1, w0, w1, mo_ea, mo_eb, nocca, noccb, a, b, c, 1.); } return et; } void CCuccsd_t_zbaa(double complex *e_tot, double *mo_ea, double *mo_eb, double complex *t1aT, double complex *t1bT, double complex *t2aaT, double complex *t2abT, double complex *vooo, double complex *vOoO, double complex *VoOo, double complex *fvo, double complex *fVO, int nocca, int noccb, int nvira, int nvirb, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = gen_baa_jobs(jobs, nocca, noccb, nvira, nvirb, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double complex)); double complex *vs_ts[] = {(double complex *)mo_ea, (double complex *)mo_eb, fvo, fVO, vooo, vOoO, VoOo, t1aT, t1bT, t2aaT, t2abT}; #pragma omp parallel default(none) \ shared(njobs, nocca, noccb, nvira, nvirb, vs_ts, jobs, e_tot) { int a, b, c; size_t k; double complex *cache1 = malloc(sizeof(double complex) * (noccb*nocca*nocca*5+1)); double complex e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += zcontract6_baa(nocca, noccb, nvira, nvirb, a, b, c, vs_ts, jobs[k].cache, cache1); } free(cache1); #pragma omp critical *e_tot += e; } }
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/OpenMPClause.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/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; /// 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 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> 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<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; /// 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; /// 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(); /// \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 ParsedType getTypeAnnotation(const Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } /// 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); 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(bool IsAddressOfOperand, 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. /// /// 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(); 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(); }; /// 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; 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); } }; // 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); static void LateTemplateParserCleanupCallback(void *P); 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); 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, if non-NULL, is filled with the location of the last token of // the simple-asm. ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); ExprResult ParseAsmStringLiteral(); // 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(); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false); /// 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 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 ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); 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 EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = 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(); //===--------------------------------------------------------------------===// // 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(); //===--------------------------------------------------------------------===// // 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"); } /// 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 }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// 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 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(); 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); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } 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 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); 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); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( Declarator &D, 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, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, 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 clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, 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); /// 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 Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(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); 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); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers> MapTypeModifiers; SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers> MapTypeModifiersLoc; OpenMPMapClauseKind MapType = OMPC_MAP_unknown; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, 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); bool 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); 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 &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); void AnnotateTemplateIdTokenAsType(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(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // 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; }; } // end namespace clang #endif
mkldnn_common.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 mkldnn_common.h * \brief Common header file for MKLDNN backend subgraph * \author Ciyong Chen */ #ifndef MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_ #define MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_ #if MXNET_USE_ONEDNN == 1 #include <vector> #include "../../numpy/np_matrix_op-inl.h" namespace mxnet { namespace op { template <typename DType> static std::vector<float> GetWeightScales(const NDArray& weight, const NDArray* bias, const float data_scale, bool weight_channelwise_scale) { auto nthreads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); std::vector<float> weight_scales; const DType* weight_ptr = weight.data().dptr<DType>(); const DType* bias_ptr = bias ? bias->data().dptr<DType>() : nullptr; const auto wshape = weight.shape(); size_t channel = wshape[0]; size_t offset = wshape.ProdShape(1, wshape.ndim()); std::vector<DType> weight_c_min(channel, MaxValue<DType>()); std::vector<DType> weight_c_max(channel, MinValue<DType>()); for (int c = 0; c < static_cast<int>(channel); ++c) { const DType* p1 = weight_ptr + c * offset; for (size_t k = 0; k < offset; ++k) { if (weight_c_min[c] > p1[k]) weight_c_min[c] = p1[k]; if (weight_c_max[c] < p1[k]) weight_c_max[c] = p1[k]; } } if (weight_channelwise_scale) { weight_scales.resize(channel); #pragma omp parallel for num_threads(nthreads) for (int c = 0; c < static_cast<int>(channel); ++c) { float scale = GetQuantizeScale(mshadow::kInt8, weight_c_min[c], weight_c_max[c]); if (bias_ptr && bias_ptr[c]) { // avoid overflow on bias // TODO(zhennan): mkldnn has bug to handle INT_MAX in bias, so set the maximum value of bias // to INT_MAX / 2. float scale_max = static_cast<float>(bias_ptr[c] > 0 ? MaxValue<int32_t>() : MinValue<int32_t>()) / 2 / bias_ptr[c] / data_scale; scale = Min(scale, scale_max); } weight_scales[c] = scale; } } else { DType total_min = weight_c_min[0]; DType total_max = weight_c_max[0]; for (size_t c = 0; c < channel; ++c) { if (total_min > weight_c_min[c]) total_min = weight_c_min[c]; if (total_max < weight_c_max[c]) total_max = weight_c_max[c]; } weight_scales.resize(3); weight_scales[0] = GetQuantizeScale(mshadow::kInt8, total_min, total_max); weight_scales[1] = total_min; weight_scales[2] = total_max; } return weight_scales; } static inline void ConvertWeightBias2MKLDNN(NDArray* weight, NDArray* bias, bool has_bias, const mkldnn::memory::desc& weight_md, const mkldnn::memory::desc* bias_md, const int num_group, float data_scale, const std::vector<float>& weight_scales, const bool submit = true) { MKLDNNStream* stream = MKLDNNStream::Get(); const auto new_weight = NDArray(weight_md); const auto conv_weights_memory = new_weight.GetMKLDNNData(); mkldnn::primitive_attr weight_attr; if (weight_scales.size()) { const int weight_mask = (weight_scales.size()) == 1 ? 0 : 1; weight_attr.set_output_scales(weight_mask, weight_scales); } auto default_weights_memory = GetWeights(*weight, num_group); if (default_weights_memory == nullptr) default_weights_memory = weight->GetMKLDNNData(); const auto weight_reorder_pd = mkldnn::reorder::primitive_desc(*default_weights_memory, *conv_weights_memory, weight_attr); MKLDNNStream::Get()->RegisterPrimArgs( mkldnn::reorder(weight_reorder_pd), {{MKLDNN_ARG_FROM, *default_weights_memory}, {MKLDNN_ARG_TO, *conv_weights_memory}}); NDArray new_bias; if (has_bias && data_scale) { std::vector<float> bias_scales(weight_scales.size()); for (size_t c = 0; c < weight_scales.size(); ++c) { bias_scales[c] = weight_scales[c] * data_scale; } new_bias = NDArray(*bias_md); const auto conv_bias_memory = new_bias.GetMKLDNNData(); const int bias_mask = (bias_scales.size()) == 1 ? 0 : 1; mkldnn::primitive_attr bias_attr; bias_attr.set_output_scales(bias_mask, bias_scales); auto bias_weights_memory = bias->GetMKLDNNData(); const auto bias_reorder_pd = mkldnn::reorder::primitive_desc(*bias_weights_memory, *conv_bias_memory, bias_attr); MKLDNNStream::Get()->RegisterPrimArgs( mkldnn::reorder(bias_reorder_pd), {{MKLDNN_ARG_FROM, *bias_weights_memory}, {MKLDNN_ARG_TO, *conv_bias_memory}}); } if (submit) stream->Submit(); *weight = new_weight; if (has_bias && data_scale) *bias = new_bias; } static inline bool CheckReshapeConditions(const nnvm::Node& node, const index_t out_index) { const index_t split_output_index = node.inputs[0].index; if (split_output_index != out_index) return false; const auto& reshape_param = nnvm::get<NumpyXReshapeParam>(node.attrs.parsed); const auto newshape = reshape_param.newshape; if (newshape.ndim() != 4 || !(newshape[0] == newshape[1] && newshape[0] == -2)) return false; return true; } static inline bool CheckSwapAxisConditions(const nnvm::Node& node) { auto params = node.attrs.dict; int dim1 = 0, dim2 = 0; if (params.count("dim1") && params.count("dim2")) { dim1 = std::stoi(params.at("dim1")); dim2 = std::stoi(params.at("dim2")); } else { return false; } return ((dim1 == 1 && dim2 == 2) || (dim1 == 2 && dim2 == 1)); } } // namespace op } // namespace mxnet #endif // if MXNET_USE_ONEDNN == 1 #endif // MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_
module_bl_mynn_mym_predict_impl.h
#ifndef __MODULE_BL_MYNN_MYM_PREDICT_IMPL_H__ #define __MODULE_BL_MYNN_MYM_PREDICT_IMPL_H__ // File version granularity. #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_VERSION_MAJOR #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_VERSION_MAJOR 1 #endif #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_VERSION_MINOR #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_VERSION_MINOR 0 #endif #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_PATCH_VERSION #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_PATCH_VERSION 0 #endif #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_CREATE_DATE #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_CREATE_DATE "Date: 11-11-2016 , Time: 15:36 PM GMT+2" #endif // Set this value to successful build date/time. #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_BUILD_DATE #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_BUILD_DATE "" #endif #ifndef MODULE_BL_MYNN_MYM_PREDICT_IMPL_AUTHOR #define MODULE_BL_MYNN_MYM_PREDICT_IMPL_AUTHOR "Name: Bernard Gingold , e-mail: beniekg@gmail.com" #endif #include "module_bl_mynn_F90_iface.h" #include "PhysLib_Config.h" #include "std_headers.h" namespace wrf_phys_wrappers { namespace module_bl_mynn { template<typename R32 = float, typename I32 = int > struct Wrap_Mym_Predict { /****************************************** Constructors and Destructor. ******************************************/ /* @Purpose: Default Constructor - explicitly default. */ Wrap_Mym_Predict() = default; /* @Purpose: 1st 'main' Constructor which purpose is to allocate and initialize scalar and array members. Array members are zero-filled. Caller must later initialize input arrays to correct physical state. */ Wrap_Mym_Predict(_In_ const I32 kts, _In_ const I32 kte, _In_ const I32 levflag, _In_ const I32 bl_mynn_edmf_tke, _In_ const R32 delt, _In_ const R32 flt, _In_ const R32 flq, _In_ const R32 ust, _In_ const R32 pmz, _In_ const R32 phh) : m_kts{ kts }, m_kte{ kte }, m_levflag{ levflag }, m_bl_mynn_edmf_tke{ bl_mynn_edmf_tke }, m_delt{ delt }, m_flt{ flt }, m_flq{ flq }, m_ust{ ust }, m_pmz{ pmz }, m_phh{ phh }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_s_awqke{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_s_aw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) } { if (0 > (m_kte - m_kts)) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Invalid array size 1st Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Lower range value m_kts: " << m_kts << "\n"; std::cerr << "Upper range value m_kte: " << m_kte << "\n"; std::cerr << "Range value difference: " << m_kte - m_kts << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_dz)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 1st Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = 0.f; m_dfq[i] = 0.f; m_el[i] = 0.f; m_pdk[i] = 0.f; m_pdt[i] = 0.f; m_pdq[i] = 0.f; m_pdc[i] = 0.f; m_qke[i] = 0.f; m_tsq[i] = 0.f; m_qsq[i] = 0.f; m_cov[i] = 0.f; m_s_awqke[i] = 0.f; m_s_aw[i] = 0.f; } const int top = m_kte + 1; m_s_awqke[top] = 0.f; m_s_aw[top] = 0.f; #else #if defined (USE_AUTO_VECTORIZATION) #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) #endif for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = 0.f; m_dfq[i] = 0.f; m_el[i] = 0.f; m_pdk[i] = 0.f; m_pdt[i] = 0.f; m_pdq[i] = 0.f; m_pdc[i] = 0.f; m_qke[i] = 0.f; m_tsq[i] = 0.f; m_qsq[i] = 0.f; m_cov[i] = 0.f; m_s_awqke[i] = 0.f; m_s_aw[i] = 0.f; } const int top = m_kte + 1; m_s_awqke[top] = 0.f; m_s_aw[top] = 0.f; #endif } /* @Purpose: 2nd 'main' Constructor which purpose is to allocate and initialize scalar and array members. Array output members are zero-filled. Caller must pass initialized input arrays to correct physical state. */ Wrap_Mym_Predict(_In_ const I32 kts, _In_ const I32 kte, _In_ const I32 levflag, _In_ const I32 bl_mynn_edmf_tke, _In_ const R32 delt, _In_ const R32 flt, _In_ const R32 flq, _In_ const R32 ust, _In_ const R32 pmz, _In_ const R32 phh, _In_ R32* __restrict const dz, _In_ R32* __restrict const dfq, _In_ R32* __restrict const el, _In_ R32* __restrict const pdk, _In_ R32* __restrict const pdt, _In_ R32* __restrict const pdq, _In_ R32* __restrict const pdc, _In_ R32* __restrict const qke, _In_ R32* __restrict const tsq, _In_ R32* __restrict const qsq, _In_ R32* __restrict const cov, _In_ R32* __restrict const s_awqke, _In_ R32* __restrict const s_aw) : m_kts{ kts }, m_kte{ kte }, m_levflag{ levflag }, m_bl_mynn_edmf_tke{ bl_mynn_edmf_tke }, m_delt{ delt }, m_flt{ flt }, m_flq{ flq }, m_ust{ ust }, m_pmz{ pmz }, m_phh{ phh }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_s_awqke{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_s_aw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) } { if (0 > (m_kte - m_kts)) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Invalid array size 2nd Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Lower range value m_kts: " << m_kts << "\n"; std::cerr << "Upper range value m_kte: " << m_kte << "\n"; std::cerr << "Range value difference: " << m_kte - m_kts << "\n"; std::cerr << "Cannot recover --> calling exit(-1)!!\n"; std::exit(-1); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_dz)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } if (dz == NULL || dfq == NULL || el == NULL || pdk == NULL || pdt == NULL || pdq == NULL || pdc == NULL || qke == NULL || tsq == NULL || qsq == NULL || cov == NULL || s_awqke == NULL || s_aw == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "One or more caller's arrays contains invalid pointer!!\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = dz[i]; m_dfq[i] = dfq[i]; m_el[i] = el[i]; m_pdk[i] = pdk[i]; m_pdt[i] = pdt[i]; m_pdq[i] = pdq[i]; m_pdc[i] = pdc[i]; m_qke[i] = qke[i]; m_tsq[i] = tsq[i]; m_qsq[i] = qsq[i]; m_cov[i] = cov[i]; m_s_awqke[i] = s_awqke[i]; m_s_aw[i] = s_aw[i]; } const int top = m_kte + 1; m_s_awqke[top] = s_awqke[top]; m_s_aw[top] = s_aw[top]; #else #if defined (USE_AUTO_VECTORIZATION) #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) #endif for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = dz[i]; m_dfq[i] = dfq[i]; m_el[i] = el[i]; m_pdk[i] = pdk[i]; m_pdt[i] = pdt[i]; m_pdq[i] = pdq[i]; m_pdc[i] = pdc[i]; m_qke[i] = qke[i]; m_tsq[i] = tsq[i]; m_qsq[i] = qsq[i]; m_cov[i] = cov[i]; m_s_awqke[i] = s_awqke[i]; m_s_aw[i] = s_aw[i]; } const int top = m_kte + 1; m_s_awqke[top] = s_awqke[top]; m_s_aw[top] = s_aw[top]; #endif } /* @Purpose: Copy Constructor implements deep copy semantics. */ Wrap_Mym_Predict(_In_ const Wrap_Mym_Predict &x) : m_kts{ x.m_kts }, m_kte{ x.m_kte }, m_levflag{ x.m_levflag }, m_bl_mynn_edmf_tke{ x.m_bl_mynn_edmf_tke }, m_delt{ x.m_delt }, m_flt{ x.m_flt }, m_flq{ x.m_flq }, m_ust{ x.m_ust }, m_pmz{ x.m_pmz }, m_phh{ x.m_phh }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_s_awqke{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_s_aw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) } { for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_dz)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy-Ctor: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = x.m_dz[i]; m_dfq[i] = x.m_dfq[i]; m_el[i] = x.m_el[i]; m_pdk[i] = x.m_pdk[i]; m_pdt[i] = x.m_pdt[i]; m_pdq[i] = x.m_pdq[i]; m_pdc[i] = x.m_pdc[i]; m_qke[i] = x.m_qke[i]; m_tsq[i] = x.m_tsq[i]; m_qsq[i] = x.m_qsq[i]; m_cov[i] = x.m_cov[i]; m_s_awqke[i] = x.m_s_awqke[i]; m_s_aw[i] = x.m_s_aw[i]; } const int top = m_kte + 1; m_s_awqke[top] = x.m_s_awqke[top]; m_s_aw[top] = x.m_s_aw[top]; #else #if defined (USE_AUTO_VECTORIZATION) #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) #endif for (int i = m_kts; i != m_kte; ++i) { m_dz[i] = x.m_dz[i]; m_dfq[i] = x.m_dfq[i]; m_el[i] = x.m_el[i]; m_pdk[i] = x.m_pdk[i]; m_pdt[i] = x.m_pdt[i]; m_pdq[i] = x.m_pdq[i]; m_pdc[i] = x.m_pdc[i]; m_qke[i] = x.m_qke[i]; m_tsq[i] = x.m_tsq[i]; m_qsq[i] = x.m_qsq[i]; m_cov[i] = x.m_cov[i]; m_s_awqke[i] = x.m_s_awqke[i]; m_s_aw[i] = x.m_s_aw[i]; } const int top = m_kte + 1; m_s_awqke[top] = x.m_s_awqke[top]; m_s_aw[top] = x.m_s_aw[top]; #endif } /* @Purpose: Move Constructor implements shallow copy semantics. */ Wrap_Mym_Predict(_In_ Wrap_Mym_Predict &&x) : m_kts{ x.m_kts }, m_kte{ x.m_kte }, m_levflag{ x.m_levflag }, m_bl_mynn_edmf_tke{ x.m_bl_mynn_edmf_tke }, m_delt{ x.m_delt }, m_flt{ x.m_flt }, m_flq{ x.m_flq }, m_ust{ x.m_ust }, m_pmz{ x.m_pmz }, m_phh{ x.m_phh } { for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_dz)[i] = (&x.m_dz)[i]; } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&x.m_dz)[i] = NULL; } x.m_kts = 0; x.m_kte = 0; } /* @Purpose: Class Destructor. */ ~Wrap_Mym_Predict() { for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_dz)[i]) { _mm_free((&this->m_dz)[i]); } } for (int i{ 0 }; i != this->m_totArrays; ++i) { (this->m_dz)[i] = NULL; } m_kts = 0; m_kte = 0; } /* @Purpose: Copy-assign Operator implements deep copy seamntics. */ Wrap_Mym_Predict & operator=(_In_ const Wrap_Mym_Predict &x) { if (this == &x) return (*this); m_kts = x.m_kts; m_kte = x.m_kte; m_levflag = x.m_levflag; m_bl_mynn_edmf_tke = x.m_bl_mynn_edmf_tke; m_delt = x.m_delt; m_flt = x.m_flt; m_flq = x.m_flq; m_ust = x.m_ust; m_pmz = x.m_pmz; m_phh = x.m_phh; constexpr int ntPtrs1D{13}; R32 *tPtrs1D[ntPtrs1D] = {}; for (int i{ 0 }; i != this->m_totArrays; ++i) { tPtrs1D[i] = reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)),align32B)); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if (tPtrs1D[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Operator: 'Wrap_Mym_Predict'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << tPtrs1D[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int idx = 0; idx != this->m_totArrays; ++idx) { for (int i = m_kts; i != m_kte; ++i) { tPtrs1D[idx][i] = (&x.m_dz)[idx][i]; } } const int top = m_kte + 1; tPtrs1D[11][top] = x.m_s_awqke[top]; tPtrs1D[12][top] = x.m_s_aw[top]; for (int i {0}; i != this->m_totArrays; ++i) { _mm_free((&this->m_dz)[i]); } for (int i {0}; i != this->m_totArrays; ++i) { (&this->m_dz)[i] = tPtrs1D[i]; } return (*this); #else for (int idx = 0; idx != this->m_totArrays; ++idx) { #if defined (USE_AUTO_VECTORIZATION) #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) #endif for (int i = m_kts; i != m_kte; ++i) { tPtrs1D[idx][i] = (&x.m_dz)[idx][i]; } } const int top = m_kte + 1; tPtrs1D[11][top] = x.m_s_awqke[top]; tPtrs1D[12][top] = x.m_s_aw[top]; for (int i{ 0 }; i != this->m_totArrays; ++i) { _mm_free((&this->m_dz)[i]); } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_dz)[i] = tPtrs1D[i]; } return (*this); #endif } /* @Purpose: Move-assign Operator implements shallow copy semantics. */ Wrap_Mym_Predict & operator=(_In_ Wrap_Mym_Predict &&x) { if (this == &x) return (*this); m_kts = x.m_kts; m_kte = x.m_kte; m_levflag = x.m_levflag; m_bl_mynn_edmf_tke = x.m_bl_mynn_edmf_tke; m_delt = x.m_delt; m_flt = x.m_flt; m_flq = x.m_flq; m_ust = x.m_ust; m_pmz = x.m_pmz; m_phh = x.m_phh; for (int i{ 0 }; i != this->m_totArrays; ++i) { _mm_free((&this->m_dz)[i]); } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_dz)[i] = (&x.m_dz)[i]; } for (int i{ 0 }; i != x.m_totArrays; ++i) { (x.m_dz)[i] = NULL; } return (*this); } /* @Purpose: Call Fortran 90 'MYM_PREDICT' subroutine. */ void Call_Mym_Predict() { MODULE_BL_MYNN_mp_MYM_PREDICT(&this->m_kts,&this->m_kte, &this->m_levflag, &this->m_delt, &this->m_dz[0], &this->m_ust, &this->m_flt, &this->m_flq, &this->m_pmz, &this->m_phh, &this->m_el[0], &this->m_dfq[0], &this->m_pdk[0], &this->m_pdt[0], &this->m_pdq[0], &this->m_pdc[0], &this->m_qke[0], &this->m_tsq[0], &this->m_qsq[0], &this->m_cov[0], &this->m_s_aw[0], &this->m_s_awqke[0], &this->m_bl_mynn_edmf_tke); } /* @Purpose: Member variables. */ I32 m_kts; I32 m_kte; I32 m_levflag; I32 m_bl_mynn_edmf_tke; R32 m_delt; R32 m_flt; R32 m_flq; R32 m_ust; R32 m_pmz; R32 m_phh; // Input arrays. _Field_size_(m_kte) R32* __restrict m_dz; _Field_size_(m_kte) R32* __restrict m_dfq; _Field_size_(m_kte) R32* __restrict m_el; // Input/Output arrays. _Field_size_(m_kte) R32* __restrict m_pdk; _Field_size_(m_kte) R32* __restrict m_pdt; _Field_size_(m_kte) R32* __restrict m_pdq; _Field_size_(m_kte) R32* __restrict m_pdc; _Field_size_(m_kte) R32* __restrict m_qke; _Field_size_(m_kte) R32* __restrict m_tsq; _Field_size_(m_kte) R32* __restrict m_qsq; _Field_size_(m_kte) R32* __restrict m_cov; _Field_size_(m_kte) R32* __restrict m_s_awqke; _Field_size_(m_kte) R32* __restrict m_s_aw; static const int m_totArrays = 13; }; } } #endif /*__MODULE_BL_MYNN_MYM_PREDICT_IMPL_H__*/
sgemm-openmp-backup3.c
#include <stdio.h> #include <stdlib.h> #include <emmintrin.h> #include <math.h> #include <float.h> #include <string.h> #include <omp.h> #define NUM_THREADS 16 #define CHUNK 64 void mm_28( int m, int n, int ind1, int ind2, float *An, float *Cn); void p_tail_4( int m, int r, int a, int x, float *An, float *Cn); void tail(int r, int x, int a, float *An, float *Cn); void sgemm( int m, int n, float *A, float *C ) { int BLOCKSIZE = 28; int r = ( m / BLOCKSIZE ) * BLOCKSIZE; int x = ( n / BLOCKSIZE ) * BLOCKSIZE; int a = r + (m-r)/4*4; int b = x + (n-x)/4*4; omp_set_num_threads(NUM_THREADS); #pragma nowait { #pragma omp parallel { int id = omp_get_thread_num(); for(int j = 0; j < CHUNK; j++) if(id == j % 14) mm_28(m,n,j*r/CHUNK,(j+1)*r/CHUNK,A+0,C+0); //if(id == 15) // mm_28(m,n,m/CHUNK*CHUNK,m,A+0,C+0); if(a != r || b != x) { p_tail_4(r,m,a,n, A+0, C+0); if(m % 4 !=0 || n % BLOCKSIZE != 0) tail(m,n,a,A+0,C+0); } } } } void mm_28( int r, int x, int ind1, int ind2, float *An, float *Cn) { int BLOCKSIZE = 28; int m = ( r / BLOCKSIZE ) * BLOCKSIZE; int i,j,k, blockInd1; __m128 c0,c1,c2,c3,c4,c5,c6,a0,a1,a2,a3,a4,a5,a6,a0T; /*------------------------------------------------------------------------*/ #pragma omp nowait { /* Start parallel multiply big block */ #pragma omp private(ind1,ind2,j,k,c0,c1,c2,c3,c4,c5,c6,a0,a1,a2,a3,a4,a5,a6,a0T,blockInd1) for( j = ind1; j < ind2; j++) { for(blockInd1 = 0; blockInd1 < m; blockInd1 += BLOCKSIZE) { /* Load C data into registers */ c0 = _mm_loadu_ps(Cn+blockInd1+j*r); c1 = _mm_loadu_ps(Cn+blockInd1+4+j*r); c2 = _mm_loadu_ps(Cn+blockInd1+8+j*r); c3 = _mm_loadu_ps(Cn+blockInd1+12+j*r); c4 = _mm_loadu_ps(Cn+blockInd1+16+j*r); /* Experiment */ c5 = _mm_loadu_ps(Cn+blockInd1+20+j*r); c6 = _mm_loadu_ps(Cn+blockInd1+24+j*r); //c7 = _mm_loadu_ps(Cn+blockInd1+28+j*r); for(k = 0; k < x; k++) { /* Load the value that will be multiplied across multiple a's */ a0T = _mm_load1_ps(An+j+k*r); /* Load the values to be multiplied */ a0 = _mm_loadu_ps(An+blockInd1+k*r); a1 = _mm_loadu_ps(An+blockInd1+4+k*r); a2 = _mm_loadu_ps(An+blockInd1+8+k*r); a3 = _mm_loadu_ps(An+blockInd1+12+k*r); a4 = _mm_loadu_ps(An+blockInd1+16+k*r); /* Experiment */ a5 = _mm_loadu_ps(An+blockInd1+20+k*r); a6 = _mm_loadu_ps(An+blockInd1+24+k*r); //a7 = _mm_loadu_ps(An+blockInd1+28+k*r); /* Multiply */ a0 = _mm_mul_ps(a0, a0T); a1 = _mm_mul_ps(a1, a0T); a2 = _mm_mul_ps(a2, a0T); a3 = _mm_mul_ps(a3, a0T); a4 = _mm_mul_ps(a4, a0T); /* Experiment */ a5 = _mm_mul_ps(a5,a0T); a6 = _mm_mul_ps(a6,a0T); //a7 = _mm_mul_ps(a7,a0T); /* Add */ c0 = _mm_add_ps(c0, a0); c1 = _mm_add_ps(c1, a1); c2 = _mm_add_ps(c2,a2); c3 = _mm_add_ps(c3,a3); c4 = _mm_add_ps(c4, a4); /* Experiment */ c5 = _mm_add_ps(c5,a5); c6 = _mm_add_ps(c6,a6); //c7 = _mm_add_ps(c7,a7); } /* Store the registers back into Cn */ _mm_storeu_ps(Cn+blockInd1+j*r, c0); _mm_storeu_ps(Cn+blockInd1+4+j*r, c1); _mm_storeu_ps(Cn+blockInd1+8+j*r, c2); _mm_storeu_ps(Cn+blockInd1+12+j*r, c3); _mm_storeu_ps(Cn+blockInd1+16+j*r, c4); /* Experiment */ _mm_storeu_ps(Cn+blockInd1+20+j*r,c5); _mm_storeu_ps(Cn+blockInd1+24+j*r,c6); //_mm_storeu_ps(Cn+blockInd1+28+j*r,c7); } } /* End Parallel Multiply Big Block */ } /*---------------------------------------------------------------------*/ } /* End Program */ void tail( int r, int x, int a, float *An, float *Cn) { #pragma omp nowait { int i,j,k, id = omp_get_thread_num(); if(id == 12) { #pragma omp private(i,k,j) //small bottom for( j = 0; j < r; j++) { for( k = 0; k < x; k++) { for( i = a; i < r/2*2; i+=2) { Cn[i+j*r] += An[i+k*r] * An[j+k*r]; Cn[i+1+j*r] += An[i+1+k*r] * An[j+k*r]; } for( i = r/2*2; i < r; i++) Cn[i+j*r] += An[i+k*r] * An[j+k*r]; } } } if(id == 13) { //small side for( j = a; j < r; j++) { for( k = 0; k < x; k++) { for( i = 0; i < a/2*2; i+=2) { Cn[i+j*r] += An[i+k*r] * An[j+k*r]; Cn[i+1+j*r] += An[i+1+k*r] * An[j+k*r]; } for( i = a/2*2; i < a; i++) Cn[i+j*r] += An[i+k*r] * An[j+k*r]; } } } } } void p_tail_4(int m, int r, int a, int x, float *An, float *Cn) { #pragma omp nowait { int i,j,k, id = omp_get_thread_num(); __m128 c0,a0,a0T; if(id == 15) { #pragma omp private(i,j,k,c0,a0,a0T) //parallel bottom for( j = 0 ; j < a; j++) { for( i = m; i < a; i+=4 ) { c0 = _mm_loadu_ps(Cn+i+j*r); //more registers //c1 = _mm_loadu_ps(Cn+i+4+j*r); for( k = 0; k < x; k++ ) { a0T = _mm_load1_ps(An+j+k*r); a0 = _mm_loadu_ps(An+i+k*r); //more registers //a1 = _mm_loadu_ps(An+i+4+k*r); a0 = _mm_mul_ps(a0, a0T); //more registers //a1 = _mm_mul_ps(a1,a0T); c0 = _mm_add_ps(c0, a0); //more registeres //c1 = _mm_add_ps(c1,a1); } _mm_storeu_ps(Cn+i+j*r, c0); // more reigserts //_mm_storeu_ps(Cn+i+4+j*r,c1); } } } if(id == 14) { #pragma omp private(i,j,k,c0,a0,a0T) //parallel sides for( j = m; j < a; j++) { for( i = 0; i < m; i+=4) { c0 = _mm_loadu_ps(Cn+i+j*r); // more registers //c1 = _mm_loadu_ps(Cn+i+4+j*r); for( k = 0; k < x; k++) { a0T = _mm_load1_ps(An+j+k*r); a0 = _mm_loadu_ps(An+i+k*r); //more registers //a1 = _mm_loadu_ps(An+i+4+k*r); a0 = _mm_mul_ps(a0, a0T); //more registers //a1 = _mm_mul_ps(a1,a0T); c0 = _mm_add_ps(c0, a0); //more registers //c1 = _mm_add_ps(c1,a1); } _mm_storeu_ps(Cn+i+j*r, c0); //more registers //_mm_storeu_ps(Cn+i+4+j*r,c1); } } } } }
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; out0.fill(bias0); out1.fill(bias1); const float* k0 = kernel + p * inch * 9; const float* k1 = kernel + (p + 1) * inch * 9; for (int q = 0; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr0n = outptr0 + outw; float* outptr1n = outptr1 + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; #if __ARM_NEON float32x4_t _k00 = vld1q_f32(k0); float32x4_t _k03 = vld1q_f32(k0 + 3); float32x4_t _k06 = vld1q_f32(k0 + 6); float32x4_t _k10 = vld1q_f32(k1); float32x4_t _k13 = vld1q_f32(k1 + 3); float32x4_t _k16 = vld1q_f32(k1 + 6); #endif // __ARM_NEON int i = 0; for (; i + 1 < outh; i += 2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v8.4s, v9.4s}, [%5] \n" // r0 "add %5, %5, #16 \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v14.4s, v15.4s}, [%8] \n" // r3 "add %8, %8, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v14.16b, v15.16b, #8 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v6.4s}, [%1] \n" // _sum0 "prfm pldl1keep, [%2, #128] \n" "ld1 {v7.4s}, [%2] \n" // _sum1 "fmla v6.4s, v8.4s, %18.s[0] \n" "fmla v7.4s, v8.4s, %21.s[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v12.4s}, [%3] \n" // _sum0n "prfm pldl1keep, [%4, #128] \n" "ld1 {v13.4s}, [%4] \n" // _sum1n "fmla v12.4s, v14.4s, %20.s[0] \n" "fmla v13.4s, v14.4s, %23.s[0] \n" "ext v8.16b, v8.16b, v9.16b, #8 \n" "ext v9.16b, v14.16b, v15.16b, #4 \n" "fmla v6.4s, v10.4s, %18.s[1] \n" "fmla v7.4s, v10.4s, %21.s[1] \n" "fmla v12.4s, v11.4s, %20.s[2] \n" "fmla v13.4s, v11.4s, %23.s[2] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v14.4s, v15.4s}, [%6] \n" // r1 "add %6, %6, #16 \n" "fmla v6.4s, v8.4s, %18.s[2] \n" "fmla v7.4s, v8.4s, %21.s[2] \n" "fmla v12.4s, v9.4s, %20.s[1] \n" "fmla v13.4s, v9.4s, %23.s[1] \n" "ext v10.16b, v14.16b, v15.16b, #4 \n" "fmla v6.4s, v14.4s, %19.s[0] \n" "fmla v7.4s, v14.4s, %22.s[0] \n" "fmla v12.4s, v14.4s, %18.s[0] \n" "fmla v13.4s, v14.4s, %21.s[0] \n" "ext v11.16b, v14.16b, v15.16b, #8 \n" "fmla v6.4s, v10.4s, %19.s[1] \n" "fmla v7.4s, v10.4s, %22.s[1] \n" "fmla v12.4s, v10.4s, %18.s[1] \n" "fmla v13.4s, v10.4s, %21.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v8.4s, v9.4s}, [%7] \n" // r2 "add %7, %7, #16 \n" "fmla v6.4s, v11.4s, %19.s[2] \n" "fmla v7.4s, v11.4s, %22.s[2] \n" "fmla v12.4s, v11.4s, %18.s[2] \n" "fmla v13.4s, v11.4s, %21.s[2] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "fmla v6.4s, v8.4s, %20.s[0] \n" "fmla v7.4s, v8.4s, %23.s[0] \n" "fmla v12.4s, v8.4s, %19.s[0] \n" "fmla v13.4s, v8.4s, %22.s[0] \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v6.4s, v10.4s, %20.s[1] \n" "fmla v7.4s, v10.4s, %23.s[1] \n" "fmla v12.4s, v10.4s, %19.s[1] \n" "fmla v13.4s, v10.4s, %22.s[1] \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v8.4s, v9.4s}, [%5] \n" // r0 "add %5, %5, #16 \n" "fmla v6.4s, v11.4s, %20.s[2] \n" "fmla v7.4s, v11.4s, %23.s[2] \n" "fmla v12.4s, v11.4s, %19.s[2] \n" "fmla v13.4s, v11.4s, %22.s[2] \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v14.4s, v15.4s}, [%8] \n" // r3 "add %8, %8, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v7.4s}, [%2], #16 \n" "ext v11.16b, v14.16b, v15.16b, #8 \n" "st1 {v12.4s}, [%3], #16 \n" "st1 {v13.4s}, [%4], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %5, %5, #16 \n" "sub %8, %8, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr0n), // %3 "=r"(outptr1n), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr0n), "4"(outptr1n), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k00), // %18 "w"(_k03), // %19 "w"(_k06), // %20 "w"(_k10), // %21 "w"(_k13), // %22 "w"(_k16) // %23 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5 :64] \n" // r0 "add %5, #16 \n" "pld [%8, #192] \n" "vld1.f32 {d28-d30}, [%8] \n" // r3 "add %8, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q14, q15, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :64] \n" // _sum0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :64] \n" // _sum1 "vmla.f32 q6, q8, %e18[0] \n" "vmla.f32 q7, q8, %e21[0] \n" "pld [%3, #128] \n" "vld1.f32 {d24-d25}, [%3] \n" // _sum0n "pld [%4, #128] \n" "vld1.f32 {d26-d27}, [%4] \n" // _sum1n "vmla.f32 q12, q14, %e20[0] \n" "vmla.f32 q13, q14, %e23[0] \n" "vext.32 q8, q8, q9, #2 \n" "vext.32 q9, q14, q15, #1 \n" "vmla.f32 q6, q10, %e18[1] \n" "vmla.f32 q7, q10, %e21[1] \n" "vmla.f32 q12, q11, %f20[0] \n" "vmla.f32 q13, q11, %f23[0] \n" "pld [%6, #192] \n" "vld1.f32 {d28-d30}, [%6] \n" // r1 "add %6, #16 \n" "vmla.f32 q6, q8, %f18[0] \n" "vmla.f32 q7, q8, %f21[0] \n" "vmla.f32 q12, q9, %e20[1] \n" "vmla.f32 q13, q9, %e23[1] \n" "vext.32 q10, q14, q15, #1 \n" "vmla.f32 q6, q14, %e19[0] \n" "vmla.f32 q7, q14, %e22[0] \n" "vmla.f32 q12, q14, %e18[0] \n" "vmla.f32 q13, q14, %e21[0] \n" "vext.32 q11, q14, q15, #2 \n" "vmla.f32 q6, q10, %e19[1] \n" "vmla.f32 q7, q10, %e22[1] \n" "vmla.f32 q12, q10, %e18[1] \n" "vmla.f32 q13, q10, %e21[1] \n" "pld [%7, #192] \n" "vld1.f32 {d16-d18}, [%7 :64] \n" // r2 "add %7, #16 \n" "vmla.f32 q6, q11, %f19[0] \n" "vmla.f32 q7, q11, %f22[0] \n" "vmla.f32 q12, q11, %f18[0] \n" "vmla.f32 q13, q11, %f21[0] \n" "vext.32 q10, q8, q9, #1 \n" "vmla.f32 q6, q8, %e20[0] \n" "vmla.f32 q7, q8, %e23[0] \n" "vmla.f32 q12, q8, %e19[0] \n" "vmla.f32 q13, q8, %e22[0] \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e20[1] \n" "vmla.f32 q7, q10, %e23[1] \n" "vmla.f32 q12, q10, %e19[1] \n" "vmla.f32 q13, q10, %e22[1] \n" "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5 :64] \n" // r0 "add %5, #16 \n" "vmla.f32 q6, q11, %f20[0] \n" "vmla.f32 q7, q11, %f23[0] \n" "vmla.f32 q12, q11, %f19[0] \n" "vmla.f32 q13, q11, %f22[0] \n" "pld [%8, #192] \n" "vld1.f32 {d28-d30}, [%8] \n" // r3 "add %8, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vst1.f32 {d12-d13}, [%1 : 64]!\n" "vst1.f32 {d14-d15}, [%2 : 64]!\n" "vext.32 q11, q14, q15, #2 \n" "vst1.f32 {d24-d25}, [%3]! \n" "vst1.f32 {d26-d27}, [%4]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %5, #16 \n" "sub %8, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr0n), // %3 "=r"(outptr1n), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr0n), "4"(outptr1n), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k00), // %18 "w"(_k03), // %19 "w"(_k06), // %20 "w"(_k10), // %21 "w"(_k13), // %22 "w"(_k16) // %23 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum0 = vmulq_f32(_r00, _k00); float32x4_t _sum1 = vmulq_f32(_r00, _k10); _sum0 = vmlaq_f32(_sum0, _r10, _k03); _sum1 = vmlaq_f32(_sum1, _r10, _k13); _sum0 = vmlaq_f32(_sum0, _r20, _k06); _sum1 = vmlaq_f32(_sum1, _r20, _k16); float32x4_t _sum0n = vmulq_f32(_r10, _k00); float32x4_t _sum1n = vmulq_f32(_r10, _k10); _sum0n = vmlaq_f32(_sum0n, _r20, _k03); _sum1n = vmlaq_f32(_sum1n, _r20, _k13); _sum0n = vmlaq_f32(_sum0n, _r30, _k06); _sum1n = vmlaq_f32(_sum1n, _r30, _k16); _sum0 = vsetq_lane_f32(*outptr0, _sum0, 3); _sum1 = vsetq_lane_f32(*outptr1, _sum1, 3); _sum0n = vsetq_lane_f32(*outptr0n, _sum0n, 3); _sum1n = vsetq_lane_f32(*outptr1n, _sum1n, 3); #if __aarch64__ *outptr0 = vaddvq_f32(_sum0); *outptr1 = vaddvq_f32(_sum1); *outptr0n = vaddvq_f32(_sum0n); *outptr1n = vaddvq_f32(_sum1n); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1)); float32x2_t _ss0n = vadd_f32(vget_low_f32(_sum0n), vget_high_f32(_sum0n)); float32x2_t _ss1n = vadd_f32(vget_low_f32(_sum1n), vget_high_f32(_sum1n)); float32x2_t _ss01 = vpadd_f32(_ss0, _ss1); float32x2_t _ss01n = vpadd_f32(_ss0n, _ss1n); *outptr0 = vget_lane_f32(_ss01, 0); *outptr1 = vget_lane_f32(_ss01, 1); *outptr0n = vget_lane_f32(_ss01n, 0); *outptr1n = vget_lane_f32(_ss01n, 1); #endif // __aarch64__ #else float sum0 = 0.f; float sum0n = 0.f; float sum1 = 0.f; float sum1n = 0.f; sum0 += r0[0] * k0[0]; sum0 += r0[1] * k0[1]; sum0 += r0[2] * k0[2]; sum0 += r1[0] * k0[3]; sum0 += r1[1] * k0[4]; sum0 += r1[2] * k0[5]; sum0 += r2[0] * k0[6]; sum0 += r2[1] * k0[7]; sum0 += r2[2] * k0[8]; sum1 += r0[0] * k1[0]; sum1 += r0[1] * k1[1]; sum1 += r0[2] * k1[2]; sum1 += r1[0] * k1[3]; sum1 += r1[1] * k1[4]; sum1 += r1[2] * k1[5]; sum1 += r2[0] * k1[6]; sum1 += r2[1] * k1[7]; sum1 += r2[2] * k1[8]; sum0n += r1[0] * k0[0]; sum0n += r1[1] * k0[1]; sum0n += r1[2] * k0[2]; sum0n += r2[0] * k0[3]; sum0n += r2[1] * k0[4]; sum0n += r2[2] * k0[5]; sum0n += r3[0] * k0[6]; sum0n += r3[1] * k0[7]; sum0n += r3[2] * k0[8]; sum1n += r1[0] * k1[0]; sum1n += r1[1] * k1[1]; sum1n += r1[2] * k1[2]; sum1n += r2[0] * k1[3]; sum1n += r2[1] * k1[4]; sum1n += r2[2] * k1[5]; sum1n += r3[0] * k1[6]; sum1n += r3[1] * k1[7]; sum1n += r3[2] * k1[8]; *outptr0 += sum0; *outptr1 += sum1; *outptr0n += sum0n; *outptr1n += sum1n; #endif // __ARM_NEON r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr0n++; outptr1n++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr0 += outw; outptr1 += outw; outptr0n += outw; outptr1n += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v8.4s, v9.4s}, [%3] \n" // r0 "add %3, %3, #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v6.4s}, [%1] \n" // _sum0 "prfm pldl1keep, [%2, #128] \n" "ld1 {v7.4s}, [%2] \n" // _sum1 "fmul v14.4s, v8.4s, %12.s[0] \n" "fmul v15.4s, v8.4s, %15.s[0] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v6.4s, v10.4s, %12.s[1] \n" "fmla v7.4s, v10.4s, %15.s[1] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v8.4s, v9.4s}, [%4] \n" // r1 "add %4, %4, #16 \n" "fmla v14.4s, v11.4s, %12.s[2] \n" "fmla v15.4s, v11.4s, %15.s[2] \n" "fmla v6.4s, v8.4s, %13.s[0] \n" "fmla v7.4s, v8.4s, %16.s[0] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v14.4s, v10.4s, %13.s[1] \n" "fmla v15.4s, v10.4s, %16.s[1] \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v8.4s, v9.4s}, [%5] \n" // r2 "add %5, %5, #16 \n" "fmla v6.4s, v11.4s, %13.s[2] \n" "fmla v7.4s, v11.4s, %16.s[2] \n" "fmla v14.4s, v8.4s, %14.s[0] \n" "fmla v15.4s, v8.4s, %17.s[0] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v6.4s, v10.4s, %14.s[1] \n" "fmla v7.4s, v10.4s, %17.s[1] \n" "fmla v14.4s, v11.4s, %14.s[2] \n" "fmla v15.4s, v11.4s, %17.s[2] \n" "fadd v6.4s, v6.4s, v14.4s \n" "fadd v7.4s, v7.4s, v15.4s \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v7.4s}, [%2], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(r0), "4"(r1), "5"(r2), "w"(_k00), // %12 "w"(_k03), // %13 "w"(_k06), // %14 "w"(_k10), // %15 "w"(_k13), // %16 "w"(_k16) // %17 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n" // r0 "add %3, #16 \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1] \n" // _sum0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2] \n" // _sum1 "vmul.f32 q14, q8, %e12[0] \n" "vmul.f32 q15, q8, %e15[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e12[1] \n" "vmla.f32 q7, q10, %e15[1] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n" // r1 "add %4, #16 \n" "vmla.f32 q14, q11, %f12[0] \n" "vmla.f32 q15, q11, %f15[0] \n" "vmla.f32 q6, q8, %e13[0] \n" "vmla.f32 q7, q8, %e16[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q14, q10, %e13[1] \n" "vmla.f32 q15, q10, %e16[1] \n" "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5] \n" // r2 "add %5, #16 \n" "vmla.f32 q6, q11, %f13[0] \n" "vmla.f32 q7, q11, %f16[0] \n" "vmla.f32 q14, q8, %e14[0] \n" "vmla.f32 q15, q8, %e17[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e14[1] \n" "vmla.f32 q7, q10, %e17[1] \n" "vmla.f32 q14, q11, %f14[0] \n" "vmla.f32 q15, q11, %f17[0] \n" "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q15 \n" "vst1.f32 {d12-d13}, [%1]! \n" "vst1.f32 {d14-d15}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(r0), "4"(r1), "5"(r2), "w"(_k00), // %12 "w"(_k03), // %13 "w"(_k06), // %14 "w"(_k10), // %15 "w"(_k13), // %16 "w"(_k16) // %17 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum0 = vmulq_f32(_r00, _k00); float32x4_t _sum1 = vmulq_f32(_r00, _k10); _sum0 = vmlaq_f32(_sum0, _r10, _k03); _sum1 = vmlaq_f32(_sum1, _r10, _k13); _sum0 = vmlaq_f32(_sum0, _r20, _k06); _sum1 = vmlaq_f32(_sum1, _r20, _k16); _sum0 = vsetq_lane_f32(*outptr0, _sum0, 3); _sum1 = vsetq_lane_f32(*outptr1, _sum1, 3); #if __aarch64__ *outptr0 = vaddvq_f32(_sum0); *outptr1 = vaddvq_f32(_sum1); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1)); float32x2_t _ss01 = vpadd_f32(_ss0, _ss1); *outptr0 = vget_lane_f32(_ss01, 0); *outptr1 = vget_lane_f32(_ss01, 1); #endif // __aarch64__ #else float sum0 = 0.f; float sum1 = 0.f; sum0 += r0[0] * k0[0]; sum0 += r0[1] * k0[1]; sum0 += r0[2] * k0[2]; sum0 += r1[0] * k0[3]; sum0 += r1[1] * k0[4]; sum0 += r1[2] * k0[5]; sum0 += r2[0] * k0[6]; sum0 += r2[1] * k0[7]; sum0 += r2[2] * k0[8]; sum1 += r0[0] * k1[0]; sum1 += r0[1] * k1[1]; sum1 += r0[2] * k1[2]; sum1 += r1[0] * k1[3]; sum1 += r1[1] * k1[4]; sum1 += r1[2] * k1[5]; sum1 += r2[0] * k1[6]; sum1 += r2[1] * k1[7]; sum1 += r2[2] * k1[8]; *outptr0 += sum0; *outptr1 += sum1; #endif // __ARM_NEON r0++; r1++; r2++; outptr0++; outptr1++; } r0 += 2; r1 += 2; r2 += 2; } k0 += 9; k1 += 9; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p * inch * 9; for (int q = 0; q < inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0 + 3); float32x4_t _k6789 = vld1q_f32(kernel0 + 6); #else const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #endif // __ARM_NEON int i = 0; for (; i + 1 < outh; i += 2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%3, #256] \n" "ld1 {v9.4s, v10.4s}, [%3] \n" // r0 "add %3, %3, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n" // _sum "fmla v7.4s, v9.4s, %14.s[0] \n" "fmul v6.4s, v11.4s, %14.s[1] \n" "fmul v13.4s, v12.4s, %14.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v9.4s, v10.4s}, [%4] \n" // r1 "add %4, %4, #16 \n" "fmla v7.4s, v9.4s, %15.s[0] \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" "fmla v6.4s, v11.4s, %15.s[1] \n" "fmla v13.4s, v12.4s, %15.s[2] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v8.4s}, [%2] \n" // _sum2 "fmla v8.4s, v9.4s, %14.s[0] \n" "fmul v14.4s, v11.4s, %14.s[1] \n" "fmul v15.4s, v12.4s, %14.s[2] \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v9.4s, v10.4s}, [%5] \n" // r2 "add %5, %5, #16 \n" "fmla v7.4s, v9.4s, %16.s[0] \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" "fmla v6.4s, v11.4s, %16.s[1] \n" "fmla v13.4s, v12.4s, %16.s[2] \n" "fmla v8.4s, v9.4s, %15.s[0] \n" "fmla v14.4s, v11.4s, %15.s[1] \n" "fmla v15.4s, v12.4s, %15.s[2] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v9.4s, v10.4s}, [%6] \n" // r3 "add %6, %6, #16 \n" "fmla v8.4s, v9.4s, %16.s[0] \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" "fmla v14.4s, v11.4s, %16.s[1] \n" "fmla v15.4s, v12.4s, %16.s[2] \n" "fadd v7.4s, v7.4s, v6.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v9.4s, v10.4s}, [%3] \n" // r0 "fadd v8.4s, v8.4s, v14.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "fadd v8.4s, v8.4s, v15.4s \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" "add %3, %3, #16 \n" "st1 {v7.4s}, [%1], #16 \n" "st1 {v8.4s}, [%2], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %3, %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n" // r0 "add %3, #16 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n" // _sum "vmla.f32 q7, q9, %e14[0] \n" "vmul.f32 q6, q11, %e14[1] \n" "vmul.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n" // r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n" // _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmul.f32 q14, q11, %e14[1] \n" "vmul.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n" // r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n" // r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n" // r0 "vadd.f32 q8, q8, q14 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q8, q8, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v8.4s, v9.4s}, [%2] \n" // r0 "add %2, %2, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n" // _sum "fmla v7.4s, v8.4s, %10.s[0] \n" "fmul v13.4s, v10.4s, %10.s[1] \n" "fmul v14.4s, v11.4s, %10.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v8.4s, v9.4s}, [%3] \n" // r1 "add %3, %3, #16 \n" "fmla v7.4s, v8.4s, %11.s[0] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v13.4s, v10.4s, %11.s[1] \n" "fmla v14.4s, v11.4s, %11.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v8.4s, v9.4s}, [%4] \n" // r2 "add %4, %4, #16 \n" "fmla v7.4s, v8.4s, %12.s[0] \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "fmla v13.4s, v10.4s, %12.s[1] \n" "fmla v14.4s, v11.4s, %12.s[2] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v8.4s, v9.4s}, [%2] \n" // r0 "add %2, %2, #16 \n" "fadd v7.4s, v7.4s, v13.4s \n" "fadd v7.4s, v7.4s, v14.4s \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" "ext v11.16b, v8.16b, v9.16b, #8 \n" "st1 {v7.4s}, [%1], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %2, %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n" // r0 "add %2, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n" // _sum "vmla.f32 q7, q8, %e10[0] \n" "vmul.f32 q13, q10, %e10[1] \n" "vmul.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n" // r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n" // r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n" // r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q7, q7, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch, const Option& opt) { kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // optimized layout for winograd4 // interleave weights int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; Mat kernel_tm2(8 * 8 * inch * 4, 1, nn_outch + (outch % 4 + 3) / 4); #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; float* ktm2 = kernel_tm2.channel(pp); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p + 1); const Mat kernel2_tm = kernel_tm.channel(p + 2); const Mat kernel3_tm = kernel_tm.channel(p + 3); int q = 0; #if __ARM_NEON && __aarch64__ for (; q + 3 < inch; q += 4) { const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q + 1); const float* k02 = kernel0_tm.row(q + 2); const float* k03 = kernel0_tm.row(q + 3); const float* k10 = kernel1_tm.row(q); const float* k11 = kernel1_tm.row(q + 1); const float* k12 = kernel1_tm.row(q + 2); const float* k13 = kernel1_tm.row(q + 3); const float* k20 = kernel2_tm.row(q); const float* k21 = kernel2_tm.row(q + 1); const float* k22 = kernel2_tm.row(q + 2); const float* k23 = kernel2_tm.row(q + 3); const float* k30 = kernel3_tm.row(q); const float* k31 = kernel3_tm.row(q + 1); const float* k32 = kernel3_tm.row(q + 2); const float* k33 = kernel3_tm.row(q + 3); for (int r = 0; r < 16; r++) { // split into two asm blocks for gcc reject over 30 oprands :( asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "ld1 {v2.4s}, [%3], #16 \n" "ld1 {v3.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "ld1 {v2.4s}, [%7], #16 \n" "ld1 {v3.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k02), // %3 "=r"(k03), // %4 "=r"(k10), // %5 "=r"(k11), // %6 "=r"(k12), // %7 "=r"(k13) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k02), "4"(k03), "5"(k10), "6"(k11), "7"(k12), "8"(k13) : "cc", "memory", "v0", "v1", "v2", "v3"); asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "ld1 {v2.4s}, [%3], #16 \n" "ld1 {v3.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "ld1 {v2.4s}, [%7], #16 \n" "ld1 {v3.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" : "=r"(ktm2), // %0 "=r"(k20), // %1 "=r"(k21), // %2 "=r"(k22), // %3 "=r"(k23), // %4 "=r"(k30), // %5 "=r"(k31), // %6 "=r"(k32), // %7 "=r"(k33) // %8 : "0"(ktm2), "1"(k20), "2"(k21), "3"(k22), "4"(k23), "5"(k30), "6"(k31), "7"(k32), "8"(k33) : "cc", "memory", "v0", "v1", "v2", "v3"); } } #endif // __ARM_NEON && __aarch64__ for (; q + 1 < inch; q += 2) { const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q + 1); const float* k10 = kernel1_tm.row(q); const float* k11 = kernel1_tm.row(q + 1); const float* k20 = kernel2_tm.row(q); const float* k21 = kernel2_tm.row(q + 1); const float* k30 = kernel3_tm.row(q); const float* k31 = kernel3_tm.row(q + 1); for (int r = 0; r < 16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%3], #16 \n" "ld1 {v1.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%7], #16 \n" "ld1 {v1.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k10), // %3 "=r"(k11), // %4 "=r"(k20), // %5 "=r"(k21), // %6 "=r"(k30), // %7 "=r"(k31) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k10), "4"(k11), "5"(k20), "6"(k21), "7"(k30), "8"(k31) : "cc", "memory", "v0", "v1"); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vld1.f32 {d2-d3}, [%2 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%3 :128]! \n" "vld1.f32 {d2-d3}, [%4 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "vld1.f32 {d2-d3}, [%6 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%7 :128]! \n" "vld1.f32 {d2-d3}, [%8 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k10), // %3 "=r"(k11), // %4 "=r"(k20), // %5 "=r"(k21), // %6 "=r"(k30), // %7 "=r"(k31) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k10), "4"(k11), "5"(k20), "6"(k21), "7"(k30), "8"(k31) : "cc", "memory", "q0", "q1"); #endif // __aarch64__ #else for (int m = 0; m < 4; m++) { ktm2[0 + m] = k00[m]; ktm2[4 + m] = k01[m]; ktm2[8 + m] = k10[m]; ktm2[12 + m] = k11[m]; ktm2[16 + m] = k20[m]; ktm2[20 + m] = k21[m]; ktm2[24 + m] = k30[m]; ktm2[28 + m] = k31[m]; } k00 += 4; k01 += 4; k10 += 4; k11 += 4; k20 += 4; k21 += 4; k30 += 4; k31 += 4; ktm2 += 32; #endif // __ARM_NEON } } for (; q < inch; q++) { const float* k00 = kernel0_tm.row(q); const float* k10 = kernel1_tm.row(q); const float* k20 = kernel2_tm.row(q); const float* k30 = kernel3_tm.row(q); for (int r = 0; r < 16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%3], #16 \n" "ld1 {v1.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k10), // %2 "=r"(k20), // %3 "=r"(k30) // %4 : "0"(ktm2), "1"(k00), "2"(k10), "3"(k20), "4"(k30) : "cc", "memory", "v0", "v1"); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vld1.f32 {d2-d3}, [%2 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%3 :128]! \n" "vld1.f32 {d2-d3}, [%4 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k10), // %2 "=r"(k20), // %3 "=r"(k30) // %4 : "0"(ktm2), "1"(k00), "2"(k10), "3"(k20), "4"(k30) : "cc", "memory", "q0", "q1"); #endif // __aarch64__ #else for (int m = 0; m < 4; m++) { ktm2[0 + m] = k00[m]; ktm2[4 + m] = k10[m]; ktm2[8 + m] = k20[m]; ktm2[12 + m] = k30[m]; } k00 += 4; k10 += 4; k20 += 4; k30 += 4; ktm2 += 16; #endif // __ARM_NEON } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* ktm2 = (float*)kernel_tm2.channel(nn_outch) + 8 * 8 * inch * (p - remain_outch_start); const Mat kernel0_tm = kernel_tm.channel(p); int q = 0; for (; q < inch; q++) { const float* k00 = kernel0_tm.row(q); for (int r = 0; r < 16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "st1 {v0.4s}, [%0], #16 \n" : "=r"(ktm2), // %0 "=r"(k00) // %1 : "0"(ktm2), "1"(k00) : "cc", "memory", "v0"); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vst1.f32 {d0-d1}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00) // %1 : "0"(ktm2), "1"(k00) : "cc", "memory", "q0"); #endif // __aarch64__ #else for (int m = 0; m < 4; m++) { ktm2[m] = k00[m]; } k00 += 4; ktm2 += 4; #endif // __ARM_NEON } } } kernel_tm = kernel_tm2; } static void conv3x3s1_winograd64_transform_kernel_neon5(const Mat& kernel, Mat& kernel_tm, int inch, int outch, const Option& opt) { kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // optimized layout for winograd5 // interleave weights // Mat kernel_tm2(8*8, inch, outch); // Mat kernel_tm2(inch, 64, outch); #if __ARM_NEON && __aarch64__ Mat kernel_tm2(8 * 4 * (inch / 4) + 8 * (inch % 4), 64, outch / 8 + (outch % 8) / 4 + outch % 4); #else Mat kernel_tm2(4 * 4 * (inch / 4) + 4 * (inch % 4), 64, outch / 4 + outch % 4); #endif int p = 0; #if __aarch64__ for (; p + 7 < outch; p += 8) { const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p + 1); const Mat kernel2_tm = kernel_tm.channel(p + 2); const Mat kernel3_tm = kernel_tm.channel(p + 3); const Mat kernel4_tm = kernel_tm.channel(p + 4); const Mat kernel5_tm = kernel_tm.channel(p + 5); const Mat kernel6_tm = kernel_tm.channel(p + 6); const Mat kernel7_tm = kernel_tm.channel(p + 7); Mat ktm2 = kernel_tm2.channel(p / 8); for (int r = 0; r < 64; r++) { float* ktm2p = ktm2.row(r); for (int q = 0; q < inch; q++) { const float* ktm0_0 = kernel0_tm.row(q); const float* ktm1_0 = kernel1_tm.row(q); const float* ktm2_0 = kernel2_tm.row(q); const float* ktm3_0 = kernel3_tm.row(q); const float* ktm4_0 = kernel4_tm.row(q); const float* ktm5_0 = kernel5_tm.row(q); const float* ktm6_0 = kernel6_tm.row(q); const float* ktm7_0 = kernel7_tm.row(q); ktm2p[0] = ktm0_0[r]; ktm2p[1] = ktm1_0[r]; ktm2p[2] = ktm2_0[r]; ktm2p[3] = ktm3_0[r]; ktm2p[4] = ktm4_0[r]; ktm2p[5] = ktm5_0[r]; ktm2p[6] = ktm6_0[r]; ktm2p[7] = ktm7_0[r]; ktm2p += 8; } } } #endif // __aarch64__ for (; p + 3 < outch; p += 4) { const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p + 1); const Mat kernel2_tm = kernel_tm.channel(p + 2); const Mat kernel3_tm = kernel_tm.channel(p + 3); #if __ARM_NEON && __aarch64__ Mat ktm2 = kernel_tm2.channel(p / 8 + (p % 8) / 4); #else Mat ktm2 = kernel_tm2.channel(p / 4); #endif for (int r = 0; r < 64; r++) { float* ktm2p = ktm2.row(r); for (int q = 0; q < inch; q++) { const float* ktm0_0 = kernel0_tm.row(q); const float* ktm1_0 = kernel1_tm.row(q); const float* ktm2_0 = kernel2_tm.row(q); const float* ktm3_0 = kernel3_tm.row(q); ktm2p[0] = ktm0_0[r]; ktm2p[1] = ktm1_0[r]; ktm2p[2] = ktm2_0[r]; ktm2p[3] = ktm3_0[r]; ktm2p += 4; } } } for (; p < outch; p++) { const Mat kernel0_tm = kernel_tm.channel(p); #if __ARM_NEON && __aarch64__ Mat ktm2 = kernel_tm2.channel(p / 8 + (p % 8) / 4 + p % 4); #else Mat ktm2 = kernel_tm2.channel(p / 4 + p % 4); #endif for (int r = 0; r < 64; r++) { float* ktm2p = ktm2.row(r); for (int q = 0; q < inch; q++) { const float* ktm0_0 = kernel0_tm.row(q); ktm2p[0] = ktm0_0[r]; ktm2p += 1; } } } kernel_tm = kernel_tm2; } static void conv3x3s1_winograd64_neon4(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(4, 16 * w_tm / 8 * h_tm / 8, inch, 4u, opt.workspace_allocator); const int tiles = w_tm / 8 * h_tm / 8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #if __ARM_NEON const float coeff[8] = { 0.25f, 0.5f, -1.25f, 2.f, -2.5f, 4.f, 4.25f, 5.25f }; float32x4_t _coeff0 = vld1q_f32(coeff); float32x4_t _coeff1 = vld1q_f32(coeff + 4); #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i = 0; i < h_tm / 8; i++) { for (int j = 0; j < w_tm / 8; j++) { #if __ARM_NEON const float* r0 = img0.row(i * 6) + j * 6; const float* r1 = r0 + w; const float* r2 = r0 + w * 2; const float* r3 = r0 + w * 3; // the assembly block for armv7 input transform requires 13 general registers // old gcc may fail to allocate register on debug build without -fomit-frame-pointer // so, fallback to intrinsic version for armv7 debug build --- nihui #if __aarch64__ || !defined(NDEBUG) for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _r0_0123 = vld1q_f32(r0); float32x4_t _r0_4567 = vld1q_f32(r0 + 4); float32x4_t _r1_0123 = vld1q_f32(r1); float32x4_t _r1_4567 = vld1q_f32(r1 + 4); float32x4_t _r2_0123 = vld1q_f32(r2); float32x4_t _r2_4567 = vld1q_f32(r2 + 4); float32x4_t _r3_0123 = vld1q_f32(r3); float32x4_t _r3_4567 = vld1q_f32(r3 + 4); float32x4x2_t _r01_00221133 = vtrnq_f32(_r0_0123, _r1_0123); float32x4x2_t _r01_44665577 = vtrnq_f32(_r0_4567, _r1_4567); float32x4x2_t _r23_00221133 = vtrnq_f32(_r2_0123, _r3_0123); float32x4x2_t _r23_44665577 = vtrnq_f32(_r2_4567, _r3_4567); // no vswp intrinsic :( float32x4_t _r_00 = vcombine_f32(vget_low_f32(_r01_00221133.val[0]), vget_low_f32(_r23_00221133.val[0])); float32x4_t _r_11 = vcombine_f32(vget_low_f32(_r01_00221133.val[1]), vget_low_f32(_r23_00221133.val[1])); float32x4_t _r_22 = vcombine_f32(vget_high_f32(_r01_00221133.val[0]), vget_high_f32(_r23_00221133.val[0])); float32x4_t _r_33 = vcombine_f32(vget_high_f32(_r01_00221133.val[1]), vget_high_f32(_r23_00221133.val[1])); float32x4_t _r_44 = vcombine_f32(vget_low_f32(_r01_44665577.val[0]), vget_low_f32(_r23_44665577.val[0])); float32x4_t _r_55 = vcombine_f32(vget_low_f32(_r01_44665577.val[1]), vget_low_f32(_r23_44665577.val[1])); float32x4_t _r_66 = vcombine_f32(vget_high_f32(_r01_44665577.val[0]), vget_high_f32(_r23_44665577.val[0])); float32x4_t _r_77 = vcombine_f32(vget_high_f32(_r01_44665577.val[1]), vget_high_f32(_r23_44665577.val[1])); float32x4_t _r_0_m_6 = vsubq_f32(_r_00, _r_66); float32x4_t _r_7_m_1 = vsubq_f32(_r_77, _r_11); float32x4_t _r_4_m_2 = vsubq_f32(_r_44, _r_22); float32x4_t _r_3_m_5 = vsubq_f32(_r_33, _r_55); float32x4_t _tmp0 = vmlaq_lane_f32(_r_0_m_6, _r_4_m_2, vget_high_f32(_coeff1), 1); float32x4_t _tmp7 = vmlaq_lane_f32(_r_7_m_1, _r_3_m_5, vget_high_f32(_coeff1), 1); vst1q_f32(&tmp[0][m], _tmp0); vst1q_f32(&tmp[7][m], _tmp7); float32x4_t _r_2_a_6 = vaddq_f32(_r_22, _r_66); float32x4_t _r_1_a_5 = vaddq_f32(_r_11, _r_55); float32x4_t _tmp12a = vmlsq_lane_f32(_r_2_a_6, _r_44, vget_high_f32(_coeff1), 0); float32x4_t _tmp12b = vmlsq_lane_f32(_r_1_a_5, _r_33, vget_high_f32(_coeff1), 0); float32x4_t _tmp1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _tmp2 = vsubq_f32(_tmp12a, _tmp12b); vst1q_f32(&tmp[1][m], _tmp1); vst1q_f32(&tmp[2][m], _tmp2); float32x4_t _r_4_x_c = vmulq_lane_f32(_r_44, vget_high_f32(_coeff0), 0); float32x4_t _r_3_x_c = vmulq_lane_f32(_r_33, vget_low_f32(_coeff1), 0); float32x4_t _tmp34a = vaddq_f32(_r_66, _r_4_x_c); _tmp34a = vmlaq_lane_f32(_tmp34a, _r_22, vget_low_f32(_coeff0), 0); float32x4_t _tmp34b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_low_f32(_coeff0), 1); _tmp34b = vmlaq_lane_f32(_tmp34b, _r_55, vget_high_f32(_coeff0), 1); float32x4_t _tmp3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _tmp4 = vsubq_f32(_tmp34a, _tmp34b); vst1q_f32(&tmp[3][m], _tmp3); vst1q_f32(&tmp[4][m], _tmp4); // reuse r04 * 1.25 // reuse r03 * 2.5 float32x4_t _r_2_a_4c = vaddq_f32(_r_22, _r_4_x_c); float32x4_t _tmp56a = vmlaq_lane_f32(_r_66, _r_2_a_4c, vget_low_f32(_coeff1), 1); float32x4_t _tmp56b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_high_f32(_coeff0), 1); _tmp56b = vmlaq_lane_f32(_tmp56b, _r_55, vget_low_f32(_coeff0), 1); float32x4_t _tmp5 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _tmp6 = vsubq_f32(_tmp56a, _tmp56b); vst1q_f32(&tmp[5][m], _tmp5); vst1q_f32(&tmp[6][m], _tmp6); r0 += w * 4; r1 += w * 4; r2 += w * 4; r3 += w * 4; } const float* t0 = tmp[0]; const float* t1 = tmp[1]; const float* t2 = tmp[2]; const float* t3 = tmp[3]; float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm0_4 = img0_tm.row(i * w_tm / 8 + j + tiles); float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 2); float* r0_tm1_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 3); float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 4); float* r0_tm2_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 5); float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 6); float* r0_tm3_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 7); for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _t0_0123 = vld1q_f32(t0); float32x4_t _t0_4567 = vld1q_f32(t0 + 4); float32x4_t _t1_0123 = vld1q_f32(t1); float32x4_t _t1_4567 = vld1q_f32(t1 + 4); float32x4_t _t2_0123 = vld1q_f32(t2); float32x4_t _t2_4567 = vld1q_f32(t2 + 4); float32x4_t _t3_0123 = vld1q_f32(t3); float32x4_t _t3_4567 = vld1q_f32(t3 + 4); float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123); float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567); float32x4x2_t _t23_00221133 = vtrnq_f32(_t2_0123, _t3_0123); float32x4x2_t _t23_44665577 = vtrnq_f32(_t2_4567, _t3_4567); // no vswp intrinsic :( float32x4_t _t_00 = vcombine_f32(vget_low_f32(_t01_00221133.val[0]), vget_low_f32(_t23_00221133.val[0])); float32x4_t _t_11 = vcombine_f32(vget_low_f32(_t01_00221133.val[1]), vget_low_f32(_t23_00221133.val[1])); float32x4_t _t_22 = vcombine_f32(vget_high_f32(_t01_00221133.val[0]), vget_high_f32(_t23_00221133.val[0])); float32x4_t _t_33 = vcombine_f32(vget_high_f32(_t01_00221133.val[1]), vget_high_f32(_t23_00221133.val[1])); float32x4_t _t_44 = vcombine_f32(vget_low_f32(_t01_44665577.val[0]), vget_low_f32(_t23_44665577.val[0])); float32x4_t _t_55 = vcombine_f32(vget_low_f32(_t01_44665577.val[1]), vget_low_f32(_t23_44665577.val[1])); float32x4_t _t_66 = vcombine_f32(vget_high_f32(_t01_44665577.val[0]), vget_high_f32(_t23_44665577.val[0])); float32x4_t _t_77 = vcombine_f32(vget_high_f32(_t01_44665577.val[1]), vget_high_f32(_t23_44665577.val[1])); float32x4_t _t_0_m_6 = vsubq_f32(_t_00, _t_66); float32x4_t _t_7_m_1 = vsubq_f32(_t_77, _t_11); float32x4_t _t_4_m_2 = vsubq_f32(_t_44, _t_22); float32x4_t _t_3_m_5 = vsubq_f32(_t_33, _t_55); float32x4_t _r0_tm_0_0 = vmlaq_lane_f32(_t_0_m_6, _t_4_m_2, vget_high_f32(_coeff1), 1); float32x4_t _r0_tm_4_3 = vmlaq_lane_f32(_t_7_m_1, _t_3_m_5, vget_high_f32(_coeff1), 1); r0_tm0_0[0] = vgetq_lane_f32(_r0_tm_0_0, 0); r0_tm1_0[0] = vgetq_lane_f32(_r0_tm_0_0, 1); r0_tm2_0[0] = vgetq_lane_f32(_r0_tm_0_0, 2); r0_tm3_0[0] = vgetq_lane_f32(_r0_tm_0_0, 3); r0_tm0_4[3] = vgetq_lane_f32(_r0_tm_4_3, 0); r0_tm1_4[3] = vgetq_lane_f32(_r0_tm_4_3, 1); r0_tm2_4[3] = vgetq_lane_f32(_r0_tm_4_3, 2); r0_tm3_4[3] = vgetq_lane_f32(_r0_tm_4_3, 3); float32x4_t _t_2_m_6 = vaddq_f32(_t_22, _t_66); float32x4_t _t_1_m_5 = vaddq_f32(_t_11, _t_55); float32x4_t _tmp12a = vmlsq_lane_f32(_t_2_m_6, _t_44, vget_high_f32(_coeff1), 0); float32x4_t _tmp12b = vmlsq_lane_f32(_t_1_m_5, _t_33, vget_high_f32(_coeff1), 0); float32x4_t _r0_tm_0_1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _r0_tm_0_2 = vsubq_f32(_tmp12a, _tmp12b); r0_tm0_0[1] = vgetq_lane_f32(_r0_tm_0_1, 0); r0_tm1_0[1] = vgetq_lane_f32(_r0_tm_0_1, 1); r0_tm2_0[1] = vgetq_lane_f32(_r0_tm_0_1, 2); r0_tm3_0[1] = vgetq_lane_f32(_r0_tm_0_1, 3); r0_tm0_0[2] = vgetq_lane_f32(_r0_tm_0_2, 0); r0_tm1_0[2] = vgetq_lane_f32(_r0_tm_0_2, 1); r0_tm2_0[2] = vgetq_lane_f32(_r0_tm_0_2, 2); r0_tm3_0[2] = vgetq_lane_f32(_r0_tm_0_2, 3); float32x4_t _t_4_x_c = vmulq_lane_f32(_t_44, vget_high_f32(_coeff0), 0); float32x4_t _t_3_x_c = vmulq_lane_f32(_t_33, vget_low_f32(_coeff1), 0); float32x4_t _tmp34a = vaddq_f32(_t_66, _t_4_x_c); _tmp34a = vmlaq_lane_f32(_tmp34a, _t_22, vget_low_f32(_coeff0), 0); float32x4_t _tmp34b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_low_f32(_coeff0), 1); _tmp34b = vmlaq_lane_f32(_tmp34b, _t_55, vget_high_f32(_coeff0), 1); float32x4_t _r0_tm_0_3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _r0_tm_4_0 = vsubq_f32(_tmp34a, _tmp34b); r0_tm0_0[3] = vgetq_lane_f32(_r0_tm_0_3, 0); r0_tm1_0[3] = vgetq_lane_f32(_r0_tm_0_3, 1); r0_tm2_0[3] = vgetq_lane_f32(_r0_tm_0_3, 2); r0_tm3_0[3] = vgetq_lane_f32(_r0_tm_0_3, 3); r0_tm0_4[0] = vgetq_lane_f32(_r0_tm_4_0, 0); r0_tm1_4[0] = vgetq_lane_f32(_r0_tm_4_0, 1); r0_tm2_4[0] = vgetq_lane_f32(_r0_tm_4_0, 2); r0_tm3_4[0] = vgetq_lane_f32(_r0_tm_4_0, 3); float32x4_t _t_2_a_4c = vaddq_f32(_t_22, _t_4_x_c); float32x4_t _tmp56a = vmlaq_lane_f32(_t_66, _t_2_a_4c, vget_low_f32(_coeff1), 1); float32x4_t _tmp56b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_high_f32(_coeff0), 1); _tmp56b = vmlaq_lane_f32(_tmp56b, _t_55, vget_low_f32(_coeff0), 1); float32x4_t _r0_tm_4_1 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _r0_tm_4_2 = vsubq_f32(_tmp56a, _tmp56b); r0_tm0_4[1] = vgetq_lane_f32(_r0_tm_4_1, 0); r0_tm1_4[1] = vgetq_lane_f32(_r0_tm_4_1, 1); r0_tm2_4[1] = vgetq_lane_f32(_r0_tm_4_1, 2); r0_tm3_4[1] = vgetq_lane_f32(_r0_tm_4_1, 3); r0_tm0_4[2] = vgetq_lane_f32(_r0_tm_4_2, 0); r0_tm1_4[2] = vgetq_lane_f32(_r0_tm_4_2, 1); r0_tm2_4[2] = vgetq_lane_f32(_r0_tm_4_2, 2); r0_tm3_4[2] = vgetq_lane_f32(_r0_tm_4_2, 3); t0 += 8 * 4; t1 += 8 * 4; t2 += 8 * 4; t3 += 8 * 4; r0_tm0_0 += img0_tm.w * tiles * 2 * 4; r0_tm0_4 += img0_tm.w * tiles * 2 * 4; r0_tm1_0 += img0_tm.w * tiles * 2 * 4; r0_tm1_4 += img0_tm.w * tiles * 2 * 4; r0_tm2_0 += img0_tm.w * tiles * 2 * 4; r0_tm2_4 += img0_tm.w * tiles * 2 * 4; r0_tm3_0 += img0_tm.w * tiles * 2 * 4; r0_tm3_4 += img0_tm.w * tiles * 2 * 4; } #else // __aarch64__ float* t0 = tmp[0]; float* t1 = tmp[1]; float* t2 = tmp[2]; float* t3 = tmp[3]; float* t4 = tmp[4]; float* t5 = tmp[5]; float* t6 = tmp[6]; float* t7 = tmp[7]; int stepw = w * 4 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%8], %26 \n" "vld1.f32 {d20-d23}, [%9], %26 \n" "vld1.f32 {d24-d27}, [%10], %26 \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%11], %26 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f25[1] \n" "vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f25[0] \n" "vmls.f32 q5, q14, %f25[0] \n" "vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m] "vmov q3, q7 \n" // use q7 "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e24[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f24[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e24[0] \n" "vmla.f32 q3, q11, %f24[1] \n" "vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m] "vmla.f32 q4, q6, %e25[1] \n" "vmla.f32 q5, q11, %e24[1] \n" "vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m] "vadd.f32 q8, q2, q3 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m] "vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m] "vmla.f32 q6, q7, %f25[1] \n" "vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m] "vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m] "vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m] // loop1 "vld1.f32 {d16-d19}, [%8] \n" "vld1.f32 {d20-d23}, [%9] \n" "vld1.f32 {d24-d27}, [%10] \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%11] \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f25[1] \n" "vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f25[0] \n" "vmls.f32 q5, q14, %f25[0] \n" "vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m] "vmov q3, q7 \n" // use q7 "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e24[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f24[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e24[0] \n" "vmla.f32 q3, q11, %f24[1] \n" "vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m] "vmla.f32 q4, q6, %e25[1] \n" "vmla.f32 q5, q11, %e24[1] \n" "vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m] "vadd.f32 q8, q2, q3 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m] "vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m] "vmla.f32 q6, q7, %f25[1] \n" "vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m] "vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m] "vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m] : "=r"(t0), // %0 "=r"(t1), // %1 "=r"(t2), // %2 "=r"(t3), // %3 "=r"(t4), // %4 "=r"(t5), // %5 "=r"(t6), // %6 "=r"(t7), // %7 "=r"(r0), // %8 "=r"(r1), // %9 "=r"(r2), // %10 "=r"(r3) // %11 : "0"(t0), "1"(t1), "2"(t2), "3"(t3), "4"(t4), "5"(t5), "6"(t6), "7"(t7), "8"(r0), "9"(r1), "10"(r2), "11"(r3), "w"(_coeff0), // %24 "w"(_coeff1), // %25 "r"(stepw) // %26 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); t0 = tmp[0]; t1 = tmp[1]; t2 = tmp[2]; t3 = tmp[3]; float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm0_4 = img0_tm.row(i * w_tm / 8 + j + tiles); float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 2); float* r0_tm1_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 3); float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 4); float* r0_tm2_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 5); float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 6); float* r0_tm3_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 7); int step = img0_tm.w * tiles * 2 * 4 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%8] \n" "add %8, %8, #128 \n" "vld1.f32 {d20-d23}, [%9] \n" "add %9, %9, #128 \n" "vld1.f32 {d24-d27}, [%10] \n" "add %10, %10, #128 \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%11] \n" "add %11, %11, #128 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f25[1] \n" "vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f25[0] \n" "vmls.f32 q5, q14, %f25[0] \n" "vst1.f32 {d4[0]}, [%0]! \n" "vst1.f32 {d4[1]}, [%2]! \n" "vmov q3, q7 \n" // use q7 "vst1.f32 {d5[0]}, [%4]! \n" "vst1.f32 {d5[1]}, [%6]! \n" "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e24[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f24[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e24[0] \n" "vmla.f32 q3, q11, %f24[1] \n" "vst1.f32 {d16[0]}, [%0]! \n" "vst1.f32 {d16[1]}, [%2]! \n" "vmla.f32 q4, q6, %e25[1] \n" "vst1.f32 {d17[0]}, [%4]! \n" "vst1.f32 {d17[1]}, [%6]! \n" "vmla.f32 q5, q11, %e24[1] \n" "vst1.f32 {d18[0]}, [%0]! \n" "vst1.f32 {d18[1]}, [%2]! \n" "vadd.f32 q8, q2, q3 \n" "vst1.f32 {d19[0]}, [%4]! \n" "vst1.f32 {d19[1]}, [%6]! \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16[0]}, [%0], %26 \n" "vst1.f32 {d16[1]}, [%2], %26 \n" "vmla.f32 q6, q7, %f25[1] \n" "vst1.f32 {d17[0]}, [%4], %26 \n" "vst1.f32 {d17[1]}, [%6], %26 \n" "vtrn.32 q9, q2 \n" "vtrn.32 q3, q6 \n" "sub %0, %0, #12 \n" "sub %2, %2, #12 \n" "sub %4, %4, #12 \n" "sub %6, %6, #12 \n" "vswp d19, d6 \n" "vswp d5, d12 \n" "vst1.f32 {d18-d19}, [%1], %26 \n" "vst1.f32 {d4-d5}, [%3], %26 \n" "vst1.f32 {d6-d7}, [%5], %26 \n" "vst1.f32 {d12-d13}, [%7], %26 \n" // loop1 "vld1.f32 {d16-d19}, [%8] \n" "vld1.f32 {d20-d23}, [%9] \n" "vld1.f32 {d24-d27}, [%10] \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%11] \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f25[1] \n" "vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f25[0] \n" "vmls.f32 q5, q14, %f25[0] \n" "vst1.f32 {d4[0]}, [%0]! \n" "vst1.f32 {d4[1]}, [%2]! \n" "vmov q3, q7 \n" // use q7 "vst1.f32 {d5[0]}, [%4]! \n" "vst1.f32 {d5[1]}, [%6]! \n" "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e24[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f24[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e24[0] \n" "vmla.f32 q3, q11, %f24[1] \n" "vst1.f32 {d16[0]}, [%0]! \n" "vst1.f32 {d16[1]}, [%2]! \n" "vmla.f32 q4, q6, %e25[1] \n" "vst1.f32 {d17[0]}, [%4]! \n" "vst1.f32 {d17[1]}, [%6]! \n" "vmla.f32 q5, q11, %e24[1] \n" "vst1.f32 {d18[0]}, [%0]! \n" "vst1.f32 {d18[1]}, [%2]! \n" "vadd.f32 q8, q2, q3 \n" "vst1.f32 {d19[0]}, [%4]! \n" "vst1.f32 {d19[1]}, [%6]! \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16[0]}, [%0] \n" "vst1.f32 {d16[1]}, [%2] \n" "vmla.f32 q6, q7, %f25[1] \n" "vst1.f32 {d17[0]}, [%4] \n" "vst1.f32 {d17[1]}, [%6] \n" "vtrn.32 q9, q2 \n" "vtrn.32 q3, q6 \n" "vswp d19, d6 \n" "vswp d5, d12 \n" "vst1.f32 {d18-d19}, [%1] \n" "vst1.f32 {d4-d5}, [%3] \n" "vst1.f32 {d6-d7}, [%5] \n" "vst1.f32 {d12-d13}, [%7] \n" : "=r"(r0_tm0_0), // %0 "=r"(r0_tm0_4), // %1 "=r"(r0_tm1_0), // %2 "=r"(r0_tm1_4), // %3 "=r"(r0_tm2_0), // %4 "=r"(r0_tm2_4), // %5 "=r"(r0_tm3_0), // %6 "=r"(r0_tm3_4), // %7 "=r"(t0), // %8 "=r"(t1), // %9 "=r"(t2), // %10 "=r"(t3) // %11 : "0"(r0_tm0_0), "1"(r0_tm0_4), "2"(r0_tm1_0), "3"(r0_tm1_4), "4"(r0_tm2_0), "5"(r0_tm2_4), "6"(r0_tm3_0), "7"(r0_tm3_4), "8"(t0), "9"(t1), "10"(t2), "11"(t3), "w"(_coeff0), // %24 "w"(_coeff1), // %25 "r"(step) // %26 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else const float* r0 = img0.row(i * 6) + j * 6; for (int m = 0; m < 8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25f; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25f; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25f); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25f); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25f - r0[4] * 1.25f); float tmp34b = (r0[1] * 0.5f - r0[3] * 2.5f + r0[5] * 2.f); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25f) * 4.f); float tmp56b = (r0[1] * 2.f - r0[3] * 2.5f + r0[5] * 0.5f); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tm_0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm_4 = img0_tm.row(i * w_tm / 8 + j + tiles); for (int m = 0; m < 8; m++) { const float* tmp0 = tmp[m]; r0_tm_0[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25f; r0_tm_4[3] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25f; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25f); float tmp12b = (tmp0[1] - tmp0[3] * 4.25f + tmp0[5]); r0_tm_0[1] = tmp12a + tmp12b; r0_tm_0[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25f - tmp0[4] * 1.25f); float tmp34b = (tmp0[1] * 0.5f - tmp0[3] * 2.5f + tmp0[5] * 2.f); r0_tm_0[3] = tmp34a + tmp34b; r0_tm_4[0] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25f) * 4.f); float tmp56b = (tmp0[1] * 2.f - tmp0[3] * 2.5f + tmp0[5] * 0.5f); r0_tm_4[1] = tmp56a + tmp56b; r0_tm_4[2] = tmp56a - tmp56b; r0_tm_0 += img0_tm.w * tiles * 2; r0_tm_4 += img0_tm.w * tiles * 2; } #endif // __ARM_NEON } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(4, 16 * w_tm / 8 * h_tm / 8, outch, 4u, opt.workspace_allocator); const int tiles = h_tm / 8 * w_tm / 8; int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p + 1); Mat out2_tm = top_blob_tm.channel(p + 2); Mat out3_tm = top_blob_tm.channel(p + 3); const float* ktm = kernel_tm.channel(pp); out0_tm.fill(0.f); out1_tm.fill(0.f); out2_tm.fill(0.f); out3_tm.fill(0.f); int q = 0; #if __ARM_NEON && __aarch64__ for (; q + 3 < inch; q += 4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q + 1); const float* r2 = bottom_blob_tm.channel(q + 2); const float* r3 = bottom_blob_tm.channel(q + 3); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; asm volatile( "mov w0, #16 \n" // w0 = r = 16 "0: \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%8], #64 \n" // v0 v1 v2 v3 = _k00 _k01 _k02 _k03 "prfm pldl1keep, [%8, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%8], #64 \n" // v4 v5 v6 v7 = _k10 _k11 _k12 _k13 "prfm pldl1keep, [%8, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" // v8 v9 v10 v11 = _k20 _k21 _k22 _k23 "prfm pldl1keep, [%8, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n" // v12 v13 v14 v15 = _k30 _k31 _k32 _k33 // tile loop "lsr w1, %w18, #2 \n" // w1 = nn = tiles >> 2 "cmp w1, #0 \n" "beq 2f \n" //BEGIN tile loop "prfm pldl1keep, [%4, #128] \n" // "ld1 {v16.4s}, [%4], #16 \n" "1: \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v20.4s}, [%0] \n" "add x4, %0, #16 \n" // x4 = %0 next "fmla v20.4s, v16.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v21.4s}, [%1] \n" "add x5, %1, #16 \n" // x5 = %1 next "fmla v21.4s, v16.4s, v4.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v22.4s}, [%2] \n" "add x6, %2, #16 \n" // x6 = %2 next "fmla v22.4s, v16.4s, v8.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v23.4s}, [%3] \n" "add x7, %3, #16 \n" // x7 = %3 next "prfm pldl1keep, [%5, #128] \n" "ld1 {v17.4s}, [%5], #16 \n" "fmla v23.4s, v16.4s, v12.4s \n" "prfm pldl1keep, [x4, #128] \n" "ld1 {v24.4s}, [x4] \n" "fmla v20.4s, v17.4s, v1.4s \n" "fmla v21.4s, v17.4s, v5.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v18.4s}, [%6], #16 \n" "fmla v22.4s, v17.4s, v9.4s \n" "fmla v23.4s, v17.4s, v13.4s \n" "prfm pldl1keep, [x5, #128] \n" "ld1 {v25.4s}, [x5] \n" "fmla v20.4s, v18.4s, v2.4s \n" "fmla v21.4s, v18.4s, v6.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v19.4s}, [%7], #16 \n" "fmla v22.4s, v18.4s, v10.4s \n" "fmla v23.4s, v18.4s, v14.4s \n" "prfm pldl1keep, [x6, #128] \n" "ld1 {v26.4s}, [x6] \n" "fmla v20.4s, v19.4s, v3.4s \n" "fmla v21.4s, v19.4s, v7.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "fmla v22.4s, v19.4s, v11.4s \n" "fmla v23.4s, v19.4s, v15.4s \n" /////// "prfm pldl1keep, [x7, #128] \n" "ld1 {v27.4s}, [x7] \n" "st1 {v20.4s}, [%0] \n" "add %0, %0, #32 \n" "fmla v24.4s, v16.4s, v0.4s \n" "fmla v25.4s, v16.4s, v4.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v17.4s}, [%5], #16 \n" "fmla v26.4s, v16.4s, v8.4s \n" "fmla v27.4s, v16.4s, v12.4s \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "add %1, %1, #32 \n" "fmla v24.4s, v17.4s, v1.4s \n" "fmla v25.4s, v17.4s, v5.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v18.4s}, [%6], #16 \n" "fmla v26.4s, v17.4s, v9.4s \n" "fmla v27.4s, v17.4s, v13.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "add %2, %2, #32 \n" "fmla v24.4s, v18.4s, v2.4s \n" "fmla v25.4s, v18.4s, v6.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v19.4s}, [%7], #16 \n" "fmla v26.4s, v18.4s, v10.4s \n" "fmla v27.4s, v18.4s, v14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" "add %3, %3, #32 \n" "fmla v24.4s, v19.4s, v3.4s \n" "fmla v25.4s, v19.4s, v7.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "fmla v26.4s, v19.4s, v11.4s \n" "fmla v27.4s, v19.4s, v15.4s \n" /////// "prfm pldl1keep, [%3, #128] \n" "ld1 {v23.4s}, [%3] \n" "st1 {v24.4s}, [x4] \n" "add x4, x4, #32 \n" "fmla v20.4s, v16.4s, v0.4s \n" "fmla v21.4s, v16.4s, v4.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v17.4s}, [%5], #16 \n" "fmla v22.4s, v16.4s, v8.4s \n" "fmla v23.4s, v16.4s, v12.4s \n" "prfm pldl1keep, [x4, #128] \n" "ld1 {v24.4s}, [x4] \n" "st1 {v25.4s}, [x5] \n" "add x5, x5, #32 \n" "fmla v20.4s, v17.4s, v1.4s \n" "fmla v21.4s, v17.4s, v5.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v18.4s}, [%6], #16 \n" "fmla v22.4s, v17.4s, v9.4s \n" "fmla v23.4s, v17.4s, v13.4s \n" "prfm pldl1keep, [x5, #128] \n" "ld1 {v25.4s}, [x5] \n" "st1 {v26.4s}, [x6] \n" "add x6, x6, #32 \n" "fmla v20.4s, v18.4s, v2.4s \n" "fmla v21.4s, v18.4s, v6.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v19.4s}, [%7], #16 \n" "fmla v22.4s, v18.4s, v10.4s \n" "fmla v23.4s, v18.4s, v14.4s \n" "prfm pldl1keep, [x6, #128] \n" "ld1 {v26.4s}, [x6] \n" "st1 {v27.4s}, [x7] \n" "add x7, x7, #32 \n" "fmla v20.4s, v19.4s, v3.4s \n" "fmla v21.4s, v19.4s, v7.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "fmla v22.4s, v19.4s, v11.4s \n" "fmla v23.4s, v19.4s, v15.4s \n" /////// "prfm pldl1keep, [x7, #128] \n" "ld1 {v27.4s}, [x7] \n" "st1 {v20.4s}, [%0] \n" "fmla v24.4s, v16.4s, v0.4s \n" "fmla v25.4s, v16.4s, v4.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v17.4s}, [%5], #16 \n" "fmla v26.4s, v16.4s, v8.4s \n" "fmla v27.4s, v16.4s, v12.4s \n" "st1 {v21.4s}, [%1] \n" "fmla v24.4s, v17.4s, v1.4s \n" "fmla v25.4s, v17.4s, v5.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v18.4s}, [%6], #16 \n" "fmla v26.4s, v17.4s, v9.4s \n" "fmla v27.4s, v17.4s, v13.4s \n" "st1 {v22.4s}, [%2] \n" "fmla v24.4s, v18.4s, v2.4s \n" "fmla v25.4s, v18.4s, v6.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v19.4s}, [%7], #16 \n" "fmla v26.4s, v18.4s, v10.4s \n" "fmla v27.4s, v18.4s, v14.4s \n" "st1 {v23.4s}, [%3] \n" "fmla v24.4s, v19.4s, v3.4s \n" "fmla v25.4s, v19.4s, v7.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "fmla v26.4s, v19.4s, v11.4s \n" "fmla v27.4s, v19.4s, v15.4s \n" "st1 {v24.4s}, [x4], #16 \n" "mov %0, x4 \n" "st1 {v25.4s}, [x5], #16 \n" "mov %1, x5 \n" "subs w1, w1, #1 \n" "st1 {v26.4s}, [x6], #16 \n" "mov %2, x6 \n" "st1 {v27.4s}, [x7], #16 \n" "mov %3, x7 \n" "bne 1b \n" "sub %4, %4, #16 \n" //END tile loop "2: \n" // remain loop "and w1, %w18, #3 \n" // w1 = remain = tiles & 3 "cmp w1, #0 \n" "beq 4f \n" //BEGIN remain loop "3: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v20.4s}, [%0] \n" "fmla v20.4s, v16.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v21.4s}, [%1] \n" "fmla v21.4s, v16.4s, v4.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v22.4s}, [%2] \n" "fmla v22.4s, v16.4s, v8.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v23.4s}, [%3] \n" "fmla v23.4s, v16.4s, v12.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v17.4s}, [%5], #16 \n" "fmla v20.4s, v17.4s, v1.4s \n" "fmla v21.4s, v17.4s, v5.4s \n" "fmla v22.4s, v17.4s, v9.4s \n" "fmla v23.4s, v17.4s, v13.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v18.4s}, [%6], #16 \n" "fmla v20.4s, v18.4s, v2.4s \n" "fmla v21.4s, v18.4s, v6.4s \n" "fmla v22.4s, v18.4s, v10.4s \n" "fmla v23.4s, v18.4s, v14.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v19.4s}, [%7], #16 \n" "fmla v20.4s, v19.4s, v3.4s \n" "fmla v21.4s, v19.4s, v7.4s \n" "fmla v22.4s, v19.4s, v11.4s \n" "fmla v23.4s, v19.4s, v15.4s \n" "st1 {v20.4s}, [%0], #16 \n" "st1 {v21.4s}, [%1], #16 \n" "subs w1, w1, #1 \n" "st1 {v22.4s}, [%2], #16 \n" "st1 {v23.4s}, [%3], #16 \n" "bne 3b \n" //END remain loop "4: \n" "subs w0, w0, #1 \n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(r2), // %6 "=r"(r3), // %7 "=r"(ktm) // %8 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "6"(r2), "7"(r3), "8"(ktm), "r"(tiles) // %18 : "cc", "memory", "x0", "x1", "x4", "x5", "x6", "x7", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); } #endif // __ARM_NEON && __aarch64__ for (; q + 1 < inch; q += 2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q + 1); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; #if __ARM_NEON #if __aarch64__ asm volatile( "mov w0, #16 \n" // w0 = r = 16 "0: \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v0.4s, v1.4s}, [%6], #32 \n" // v0 v1 = _k00 _k01 "prfm pldl1keep, [%6, #256] \n" "ld1 {v2.4s, v3.4s}, [%6], #32 \n" // v2 v3 = _k10 _k11 "prfm pldl1keep, [%6, #256] \n" "ld1 {v4.4s, v5.4s}, [%6], #32 \n" // v4 v5 = _k20 _k21 "prfm pldl1keep, [%6, #256] \n" "ld1 {v6.4s, v7.4s}, [%6], #32 \n" // v6 v7 = _k30 _k31 // tile loop "lsr w1, %w14, #2 \n" // w1 = nn = tiles >> 2 "cmp w1, #0 \n" "beq 2f \n" //BEGIN tile loop "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "1: \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, v2.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, v4.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, v6.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, v1.4s \n" "fmla v17.4s, v21.4s, v3.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "fmla v18.4s, v21.4s, v5.4s \n" "fmla v19.4s, v21.4s, v7.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" //// "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, v2.4s \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, v4.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, v6.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, v1.4s \n" "fmla v17.4s, v21.4s, v3.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "fmla v18.4s, v21.4s, v5.4s \n" "fmla v19.4s, v21.4s, v7.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" //// "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, v2.4s \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, v4.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, v6.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, v1.4s \n" "fmla v17.4s, v21.4s, v3.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "fmla v18.4s, v21.4s, v5.4s \n" "fmla v19.4s, v21.4s, v7.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" //// "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, v2.4s \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, v4.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, v6.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, v1.4s \n" "fmla v17.4s, v21.4s, v3.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "fmla v18.4s, v21.4s, v5.4s \n" "fmla v19.4s, v21.4s, v7.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "subs w1, w1, #1 \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "bne 1b \n" "sub %4, %4, #16 \n" //END tile loop "2: \n" // remain loop "and w1, %w14, #3 \n" // w1 = remain = tiles & 3 "cmp w1, #0 \n" "beq 4f \n" //BEGIN remain loop "3: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, v2.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, v4.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, v6.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, v1.4s \n" "fmla v17.4s, v21.4s, v3.4s \n" "fmla v18.4s, v21.4s, v5.4s \n" "fmla v19.4s, v21.4s, v7.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "subs w1, w1, #1 \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "bne 3b \n" //END remain loop "4: \n" "subs w0, w0, #1 \n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(ktm) // %6 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "6"(ktm), "r"(tiles) // %14 : "cc", "memory", "x0", "x1", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21"); #else asm volatile( "mov r0, #16 \n" // r0 = r = 16 "0: \n" "pld [%6, #256] \n" "vld1.f32 {d0-d3}, [%6 :128]! \n" // q0 q1 = _k00 _k01 "pld [%6, #256] \n" "vld1.f32 {d4-d7}, [%6 :128]! \n" // q2 q3 = _k10 _k11 "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]! \n" // q4 q5 = _k20 _k21 "pld [%6, #256] \n" "vld1.f32 {d12-d15}, [%6 :128]! \n" // q6 q7 = _k30 _k31 // tile loop "lsr r1, %14, #2 \n" // r1 = nn = tiles >> 2 "cmp r1, #0 \n" "beq 2f \n" //BEGIN tile loop "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "1: \n" "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q2 \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q4 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q6 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1 "vmla.f32 q8, q13, q1 \n" "vmla.f32 q9, q13, q3 \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "vmla.f32 q10, q13, q5 \n" "vmla.f32 q11, q13, q7 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" //// "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q2 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q4 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q6 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1 "vmla.f32 q8, q13, q1 \n" "vmla.f32 q9, q13, q3 \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "vmla.f32 q10, q13, q5 \n" "vmla.f32 q11, q13, q7 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" //// "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q2 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q4 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q6 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1 "vmla.f32 q8, q13, q1 \n" "vmla.f32 q9, q13, q3 \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "vmla.f32 q10, q13, q5 \n" "vmla.f32 q11, q13, q7 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" //// "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q2 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q4 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q6 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1 "vmla.f32 q8, q13, q1 \n" "vmla.f32 q9, q13, q3 \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "vmla.f32 q10, q13, q5 \n" "vmla.f32 q11, q13, q7 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "subs r1, #1 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "bne 1b \n" "sub %4, %4, #16 \n" //END tile loop "2: \n" // remain loop "and r1, %14, #3 \n" // r1 = remain = tiles & 3 "cmp r1, #0 \n" "beq 4f \n" //BEGIN remain loop "3: \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q2 \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q4 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q6 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1 "vmla.f32 q8, q13, q1 \n" "vmla.f32 q9, q13, q3 \n" "vmla.f32 q10, q13, q5 \n" "vmla.f32 q11, q13, q7 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "subs r1, #1 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "bne 3b \n" //END remain loop "4: \n" "subs r0, #1 \n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(ktm) // %6 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "6"(ktm), "r"(tiles) // %14 : "cc", "memory", "r0", "r1", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13"); #endif // __aarch64__ #else for (int r = 0; r < 16; r++) { for (int t = 0; t < tiles; t++) { for (int m = 0; m < 4; m++) { output0_tm[m] += r0[m] * ktm[0 + m]; output0_tm[m] += r1[m] * ktm[4 + m]; output1_tm[m] += r0[m] * ktm[8 + m]; output1_tm[m] += r1[m] * ktm[12 + m]; output2_tm[m] += r0[m] * ktm[16 + m]; output2_tm[m] += r1[m] * ktm[20 + m]; output3_tm[m] += r0[m] * ktm[24 + m]; output3_tm[m] += r1[m] * ktm[28 + m]; } r0 += 4; r1 += 4; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; } ktm += 32; } #endif // __ARM_NEON } for (; q < inch; q++) { const float* r0 = bottom_blob_tm.channel(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; #if __ARM_NEON #if __aarch64__ asm volatile( "mov w0, #16 \n" // w0 = r = 16 "0: \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v0.4s, v1.4s}, [%5], #32 \n" // v0 v1 = _k00 _k10 "prfm pldl1keep, [%5, #256] \n" "ld1 {v2.4s, v3.4s}, [%5], #32 \n" // v2 v3 = _k20 _k30 // tile loop "mov w1, %w12 \n" // w1 = tiles "cmp w1, #0 \n" "beq 2f \n" //BEGIN tile loop "1: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v17.4s}, [%0] \n" "fmla v17.4s, v16.4s, v0.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "fmla v18.4s, v16.4s, v1.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "fmla v19.4s, v16.4s, v2.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v20.4s}, [%3] \n" "fmla v20.4s, v16.4s, v3.4s \n" "st1 {v17.4s}, [%0], #16 \n" "st1 {v18.4s}, [%1], #16 \n" "subs w1, w1, #1 \n" "st1 {v19.4s}, [%2], #16 \n" "st1 {v20.4s}, [%3], #16 \n" "bne 1b \n" //END tile loop "2: \n" "subs w0, w0, #1 \n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(ktm) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(ktm), "r"(tiles) // %12 : "cc", "memory", "x0", "x1", "v0", "v1", "v2", "v3", "v16", "v17", "v18", "v19", "v20"); #else asm volatile( "mov r0, #16 \n" // r0 = r = 16 "0: \n" "pld [%5, #256] \n" "vld1.f32 {d0-d3}, [%5 :128]! \n" // q0 q1 = _k00 _k10 "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" // q2 q3 = _k20 _k30 // tile loop "mov r1, %12 \n" // r1 = tiles "cmp r1, #0 \n" "beq 2f \n" //BEGIN tile loop "1: \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q12, q0 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm "vmla.f32 q9, q12, q1 \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm "vmla.f32 q10, q12, q2 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm "vmla.f32 q11, q12, q3 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "subs r1, #1 \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" "bne 1b \n" //END tile loop "2: \n" "subs r0, #1 \n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(ktm) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(ktm), "r"(tiles) // %12 : "cc", "memory", "r0", "r1", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13"); #endif // __aarch64__ #else for (int r = 0; r < 16; r++) { for (int t = 0; t < tiles; t++) { for (int m = 0; m < 4; m++) { output0_tm[m] += r0[m] * ktm[0 + m]; output1_tm[m] += r0[m] * ktm[4 + m]; output2_tm[m] += r0[m] * ktm[8 + m]; output3_tm[m] += r0[m] * ktm[12 + m]; } r0 += 4; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; } ktm += 16; } #endif // __ARM_NEON } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const float* ktm = (const float*)kernel_tm.channel(nn_outch) + 8 * 8 * inch * (p - remain_outch_start); out0_tm.fill(0.f); int q = 0; for (; q < inch; q++) { const float* r0 = bottom_blob_tm.channel(q); float* output0_tm = out0_tm; for (int r = 0; r < 16; r++) { #if __ARM_NEON float32x4_t _k00 = vld1q_f32(ktm); ktm += 4; #endif // __ARM_NEON // tile for (int i = 0; i < tiles; i++) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v17.4s, %4.4s \n" "st1 {v16.4s}, [%0], #16 \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00) // %4 : "cc", "memory", "v16", "v17"); #else asm volatile( "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128]! \n" // q9 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm "vmla.f32 q8, q9, %q4 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00) // %4 : "cc", "memory", "q8", "q9"); #endif // __aarch64__ #else for (int m = 0; m < 4; m++) { output0_tm[m] += r0[m] * ktm[m]; } r0 += 4; output0_tm += 4; #endif // __ARM_NEON } #if !__ARM_NEON ktm += 4; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) #if __ARM_NEON const float coeff[4] = {4.f, 8.f, 16.f, 32.f}; float32x4_t _coeff = vld1q_f32(coeff); #endif // __ARM_NEON int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; #if __ARM_NEON float32x2_t _bias0 = vdup_n_f32(bias0); #endif // __ARM_NEON float tmp[6][8]; // tile for (int i = 0; i < outh / 6; i++) { for (int j = 0; j < outw / 6; j++) { #if __ARM_NEON const float* output0_tm0_0 = out0_tm.row(i * w_tm / 8 + j); const float* output0_tm0_4 = out0_tm.row(i * w_tm / 8 + j + tiles); const float* output0_tm1_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 2); const float* output0_tm1_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 3); const float* output0_tm2_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 4); const float* output0_tm2_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 5); const float* output0_tm3_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 6); const float* output0_tm3_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 7); #if __aarch64__ for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _output0_tm0_0123 = vld1q_f32(output0_tm0_0); float32x4_t _output0_tm0_4567 = vld1q_f32(output0_tm0_4); float32x4_t _output0_tm1_0123 = vld1q_f32(output0_tm1_0); float32x4_t _output0_tm1_4567 = vld1q_f32(output0_tm1_4); float32x4_t _output0_tm2_0123 = vld1q_f32(output0_tm2_0); float32x4_t _output0_tm2_4567 = vld1q_f32(output0_tm2_4); float32x4_t _output0_tm3_0123 = vld1q_f32(output0_tm3_0); float32x4_t _output0_tm3_4567 = vld1q_f32(output0_tm3_4); float32x4x2_t _output0_tm01_00221133 = vtrnq_f32(_output0_tm0_0123, _output0_tm1_0123); float32x4x2_t _output0_tm01_44665577 = vtrnq_f32(_output0_tm0_4567, _output0_tm1_4567); float32x4x2_t _output0_tm23_00221133 = vtrnq_f32(_output0_tm2_0123, _output0_tm3_0123); float32x4x2_t _output0_tm23_44665577 = vtrnq_f32(_output0_tm2_4567, _output0_tm3_4567); // no vswp intrinsic :( float32x4_t _output0_tm_00 = vcombine_f32(vget_low_f32(_output0_tm01_00221133.val[0]), vget_low_f32(_output0_tm23_00221133.val[0])); float32x4_t _output0_tm_11 = vcombine_f32(vget_low_f32(_output0_tm01_00221133.val[1]), vget_low_f32(_output0_tm23_00221133.val[1])); float32x4_t _output0_tm_22 = vcombine_f32(vget_high_f32(_output0_tm01_00221133.val[0]), vget_high_f32(_output0_tm23_00221133.val[0])); float32x4_t _output0_tm_33 = vcombine_f32(vget_high_f32(_output0_tm01_00221133.val[1]), vget_high_f32(_output0_tm23_00221133.val[1])); float32x4_t _output0_tm_44 = vcombine_f32(vget_low_f32(_output0_tm01_44665577.val[0]), vget_low_f32(_output0_tm23_44665577.val[0])); float32x4_t _output0_tm_55 = vcombine_f32(vget_low_f32(_output0_tm01_44665577.val[1]), vget_low_f32(_output0_tm23_44665577.val[1])); float32x4_t _output0_tm_66 = vcombine_f32(vget_high_f32(_output0_tm01_44665577.val[0]), vget_high_f32(_output0_tm23_44665577.val[0])); float32x4_t _output0_tm_77 = vcombine_f32(vget_high_f32(_output0_tm01_44665577.val[1]), vget_high_f32(_output0_tm23_44665577.val[1])); float32x4_t _tmp024a = vaddq_f32(_output0_tm_11, _output0_tm_22); float32x4_t _tmp135a = vsubq_f32(_output0_tm_11, _output0_tm_22); float32x4_t _tmp024b = vaddq_f32(_output0_tm_33, _output0_tm_44); float32x4_t _tmp135b = vsubq_f32(_output0_tm_33, _output0_tm_44); float32x4_t _tmp024c = vaddq_f32(_output0_tm_55, _output0_tm_66); float32x4_t _tmp135c = vsubq_f32(_output0_tm_55, _output0_tm_66); float32x4_t _tmp0 = vaddq_f32(_output0_tm_00, _tmp024a); _tmp0 = vmlaq_lane_f32(_tmp0, _tmp024c, vget_high_f32(_coeff), 1); _tmp0 = vaddq_f32(_tmp0, _tmp024b); float32x4_t _tmp2 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0); _tmp2 = vmlaq_lane_f32(_tmp2, _tmp024c, vget_low_f32(_coeff), 1); float32x4_t _tmp4 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0); _tmp4 = vaddq_f32(_tmp4, _tmp024c); _tmp4 = vaddq_f32(_tmp4, _tmp024c); vst1q_f32(&tmp[0][m], _tmp0); vst1q_f32(&tmp[2][m], _tmp2); vst1q_f32(&tmp[4][m], _tmp4); float32x4_t _tmp1 = vmlaq_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0); _tmp1 = vaddq_f32(_tmp1, _tmp135b); _tmp1 = vaddq_f32(_tmp1, _tmp135b); float32x4_t _tmp3 = vmlaq_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1); _tmp3 = vmlaq_lane_f32(_tmp3, _tmp135c, vget_low_f32(_coeff), 0); float32x4_t _tmp5 = vaddq_f32(_output0_tm_77, _tmp135a); _tmp5 = vmlaq_lane_f32(_tmp5, _tmp135b, vget_high_f32(_coeff), 1); _tmp5 = vaddq_f32(_tmp5, _tmp135c); vst1q_f32(&tmp[1][m], _tmp1); vst1q_f32(&tmp[3][m], _tmp3); vst1q_f32(&tmp[5][m], _tmp5); output0_tm0_0 += out0_tm.w * tiles * 2 * 4; output0_tm0_4 += out0_tm.w * tiles * 2 * 4; output0_tm1_0 += out0_tm.w * tiles * 2 * 4; output0_tm1_4 += out0_tm.w * tiles * 2 * 4; output0_tm2_0 += out0_tm.w * tiles * 2 * 4; output0_tm2_4 += out0_tm.w * tiles * 2 * 4; output0_tm3_0 += out0_tm.w * tiles * 2 * 4; output0_tm3_4 += out0_tm.w * tiles * 2 * 4; } const float* t0 = tmp[0]; const float* t1 = tmp[1]; float* output0 = out0.row(i * 6) + j * 6; float* output1 = output0 + outw; for (int m = 0; m + 1 < 6; m += 2) { float32x4_t _t0_0123 = vld1q_f32(t0); float32x4_t _t0_4567 = vld1q_f32(t0 + 4); float32x4_t _t1_0123 = vld1q_f32(t1); float32x4_t _t1_4567 = vld1q_f32(t1 + 4); float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123); float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567); float32x2_t _t_00 = vget_low_f32(_t01_00221133.val[0]); float32x2_t _t_11 = vget_low_f32(_t01_00221133.val[1]); float32x2_t _t_22 = vget_high_f32(_t01_00221133.val[0]); float32x2_t _t_33 = vget_high_f32(_t01_00221133.val[1]); float32x2_t _t_44 = vget_low_f32(_t01_44665577.val[0]); float32x2_t _t_55 = vget_low_f32(_t01_44665577.val[1]); float32x2_t _t_66 = vget_high_f32(_t01_44665577.val[0]); float32x2_t _t_77 = vget_high_f32(_t01_44665577.val[1]); float32x2_t _tmp024a = vadd_f32(_t_11, _t_22); float32x2_t _tmp135a = vsub_f32(_t_11, _t_22); float32x2_t _tmp024b = vadd_f32(_t_33, _t_44); float32x2_t _tmp135b = vsub_f32(_t_33, _t_44); float32x2_t _tmp024c = vadd_f32(_t_55, _t_66); float32x2_t _tmp135c = vsub_f32(_t_55, _t_66); float32x2_t _output_0 = vadd_f32(_t_00, _tmp024a); _output_0 = vmla_lane_f32(_output_0, _tmp024c, vget_high_f32(_coeff), 1); _output_0 = vadd_f32(_output_0, _tmp024b); _output_0 = vadd_f32(_output_0, _bias0); float32x2_t _output_2 = vmla_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0); _output_2 = vmla_lane_f32(_output_2, _tmp024c, vget_low_f32(_coeff), 1); _output_2 = vadd_f32(_output_2, _bias0); float32x2_t _output_4 = vmla_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0); _output_4 = vadd_f32(_output_4, _tmp024c); _output_4 = vadd_f32(_output_4, _tmp024c); _output_4 = vadd_f32(_output_4, _bias0); output0[0] = vget_lane_f32(_output_0, 0); output1[0] = vget_lane_f32(_output_0, 1); output0[2] = vget_lane_f32(_output_2, 0); output1[2] = vget_lane_f32(_output_2, 1); output0[4] = vget_lane_f32(_output_4, 0); output1[4] = vget_lane_f32(_output_4, 1); float32x2_t _output_1 = vmla_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0); _output_1 = vadd_f32(_output_1, _tmp135b); _output_1 = vadd_f32(_output_1, _tmp135b); _output_1 = vadd_f32(_output_1, _bias0); float32x2_t _output_3 = vmla_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1); _output_3 = vmla_lane_f32(_output_3, _tmp135c, vget_low_f32(_coeff), 0); _output_3 = vadd_f32(_output_3, _bias0); float32x2_t _output_5 = vadd_f32(_t_77, _tmp135a); _output_5 = vmla_lane_f32(_output_5, _tmp135b, vget_high_f32(_coeff), 1); _output_5 = vadd_f32(_output_5, _tmp135c); _output_5 = vadd_f32(_output_5, _bias0); output0[1] = vget_lane_f32(_output_1, 0); output1[1] = vget_lane_f32(_output_1, 1); output0[3] = vget_lane_f32(_output_3, 0); output1[3] = vget_lane_f32(_output_3, 1); output0[5] = vget_lane_f32(_output_5, 0); output1[5] = vget_lane_f32(_output_5, 1); t0 += 8 * 2; t1 += 8 * 2; output0 += outw * 2; output1 += outw * 2; } #else // __aarch64__ float* t0 = tmp[0]; float* t1 = tmp[1]; int step = out0_tm.w * tiles * 2 * 4 * 4; asm volatile( // loop0 "vld1.f32 {d16-d17}, [%2], %21 \n" "vld1.f32 {d18-d19}, [%3], %21 \n" "vld1.f32 {d20-d21}, [%4], %21 \n" "vld1.f32 {d22-d23}, [%5], %21 \n" "vld1.f32 {d24-d25}, [%6], %21 \n" "vld1.f32 {d26-d27}, [%7], %21 \n" "vld1.f32 {d28-d29}, [%8], %21 \n" "vld1.f32 {d30-d31}, [%9], %21 \n" "vtrn.32 q8, q10 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vadd.f32 q2, q10, q12 \n" "vsub.f32 q3, q10, q12 \n" "vadd.f32 q4, q14, q9 \n" "vsub.f32 q5, q14, q9 \n" "vadd.f32 q6, q11, q13 \n" "vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14 "vmov q9, q3 \n" "vadd.f32 q8, q8, q2 \n" "vmla.f32 q9, q7, %f20[0] \n" "vmov q12, q2 \n" "vmov q10, q2 \n" "vmov q11, q3 \n" "vmla.f32 q12, q4, %f20[0] \n" "vadd.f32 q15, q15, q3 \n" "vmla.f32 q8, q6, %f20[1] \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q4, %e20[0] \n" "vmla.f32 q11, q5, %e20[1] \n" "vadd.f32 q12, q12, q6 \n" "vmla.f32 q15, q5, %f20[1] \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q6, %e20[1] \n" "vmla.f32 q11, q7, %e20[0] \n" "vadd.f32 q12, q12, q6 \n" "vadd.f32 q15, q15, q7 \n" "vst1.f32 {d16-d17}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d18-d19}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d20-d21}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d22-d23}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d24-d25}, [%0] \n" "sub %0, %0, #112 \n" "vst1.f32 {d30-d31}, [%1] \n" "sub %1, %1, #112 \n" // loop1 "vld1.f32 {d16-d17}, [%2] \n" "vld1.f32 {d18-d19}, [%3] \n" "vld1.f32 {d20-d21}, [%4] \n" "vld1.f32 {d22-d23}, [%5] \n" "vld1.f32 {d24-d25}, [%6] \n" "vld1.f32 {d26-d27}, [%7] \n" "vld1.f32 {d28-d29}, [%8] \n" "vld1.f32 {d30-d31}, [%9] \n" "vtrn.32 q8, q10 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vadd.f32 q2, q10, q12 \n" "vsub.f32 q3, q10, q12 \n" "vadd.f32 q4, q14, q9 \n" "vsub.f32 q5, q14, q9 \n" "vadd.f32 q6, q11, q13 \n" "vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14 "vmov q9, q3 \n" "vadd.f32 q8, q8, q2 \n" "vmla.f32 q9, q7, %f20[0] \n" "vmov q12, q2 \n" "vmov q10, q2 \n" "vmov q11, q3 \n" "vmla.f32 q12, q4, %f20[0] \n" "vadd.f32 q15, q15, q3 \n" "vmla.f32 q8, q6, %f20[1] \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q4, %e20[0] \n" "vmla.f32 q11, q5, %e20[1] \n" "vadd.f32 q12, q12, q6 \n" "vmla.f32 q15, q5, %f20[1] \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q6, %e20[1] \n" "vmla.f32 q11, q7, %e20[0] \n" "vadd.f32 q12, q12, q6 \n" "vadd.f32 q15, q15, q7 \n" "vst1.f32 {d16-d17}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d18-d19}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d20-d21}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d22-d23}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d24-d25}, [%0] \n" "vst1.f32 {d30-d31}, [%1] \n" : "=r"(t0), // %0 "=r"(t1), // %1 "=r"(output0_tm0_0), // %2 "=r"(output0_tm0_4), // %3 "=r"(output0_tm1_0), // %4 "=r"(output0_tm1_4), // %5 "=r"(output0_tm2_0), // %6 "=r"(output0_tm2_4), // %7 "=r"(output0_tm3_0), // %8 "=r"(output0_tm3_4) // %9 : "0"(t0), "1"(t1), "2"(output0_tm0_0), "3"(output0_tm0_4), "4"(output0_tm1_0), "5"(output0_tm1_4), "6"(output0_tm2_0), "7"(output0_tm2_4), "8"(output0_tm3_0), "9"(output0_tm3_4), "w"(_coeff), // %20 "r"(step) // %21 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); t0 = tmp[0]; t1 = tmp[1]; float* output0 = out0.row(i * 6) + j * 6; float* output1 = output0 + outw; int stepw = outw * 2 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" // loop1 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" // loop2 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(t0), // %2 "=r"(t1) // %3 : "0"(output0), "1"(output1), "2"(t0), "3"(t1), "w"(_coeff), // %8 "w"(_bias0), // %9 "r"(stepw) // %10 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else const float* output0_tm_0 = out0_tm.row(i * w_tm / 8 + j); const float* output0_tm_4 = out0_tm.row(i * w_tm / 8 + j + tiles); for (int m = 0; m < 8; m++) { float tmp024a = output0_tm_0[1] + output0_tm_0[2]; float tmp135a = output0_tm_0[1] - output0_tm_0[2]; float tmp024b = output0_tm_0[3] + output0_tm_4[0]; float tmp135b = output0_tm_0[3] - output0_tm_4[0]; float tmp024c = output0_tm_4[1] + output0_tm_4[2]; float tmp135c = output0_tm_4[1] - output0_tm_4[2]; tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm_4[3] + tmp135a + tmp135b * 32 + tmp135c; output0_tm_0 += out0_tm.w * tiles * 2; output0_tm_4 += out0_tm.w * tiles * 2; } float* output0 = out0.row(i * 6) + j * 6; for (int m = 0; m < 6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } #endif // __ARM_NEON } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_winograd64_neon5(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; bottom_blob_tm.create(1, 64 * tiles, inch, 4u, opt.workspace_allocator); // bottom_blob_tm.create(inch, tiles, 64); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #if __ARM_NEON const float coeff[8] = { 0.25f, 0.5f, -1.25f, 2.f, -2.5f, 4.f, 4.25f, 5.25f }; float32x4_t _coeff0 = vld1q_f32(coeff); float32x4_t _coeff1 = vld1q_f32(coeff + 4); #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i = 0; i < h_tm / 8; i++) { for (int j = 0; j < w_tm / 8; j++) { #if __ARM_NEON const float* r0 = img0.row(i * 6) + j * 6; const float* r1 = r0 + w; const float* r2 = r0 + w * 2; const float* r3 = r0 + w * 3; #if __aarch64__ for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _r0_0123 = vld1q_f32(r0); float32x4_t _r0_4567 = vld1q_f32(r0 + 4); float32x4_t _r1_0123 = vld1q_f32(r1); float32x4_t _r1_4567 = vld1q_f32(r1 + 4); float32x4_t _r2_0123 = vld1q_f32(r2); float32x4_t _r2_4567 = vld1q_f32(r2 + 4); float32x4_t _r3_0123 = vld1q_f32(r3); float32x4_t _r3_4567 = vld1q_f32(r3 + 4); float32x4x2_t _r01_00221133 = vtrnq_f32(_r0_0123, _r1_0123); float32x4x2_t _r01_44665577 = vtrnq_f32(_r0_4567, _r1_4567); float32x4x2_t _r23_00221133 = vtrnq_f32(_r2_0123, _r3_0123); float32x4x2_t _r23_44665577 = vtrnq_f32(_r2_4567, _r3_4567); // no vswp intrinsic :( float32x4_t _r_00 = vcombine_f32(vget_low_f32(_r01_00221133.val[0]), vget_low_f32(_r23_00221133.val[0])); float32x4_t _r_11 = vcombine_f32(vget_low_f32(_r01_00221133.val[1]), vget_low_f32(_r23_00221133.val[1])); float32x4_t _r_22 = vcombine_f32(vget_high_f32(_r01_00221133.val[0]), vget_high_f32(_r23_00221133.val[0])); float32x4_t _r_33 = vcombine_f32(vget_high_f32(_r01_00221133.val[1]), vget_high_f32(_r23_00221133.val[1])); float32x4_t _r_44 = vcombine_f32(vget_low_f32(_r01_44665577.val[0]), vget_low_f32(_r23_44665577.val[0])); float32x4_t _r_55 = vcombine_f32(vget_low_f32(_r01_44665577.val[1]), vget_low_f32(_r23_44665577.val[1])); float32x4_t _r_66 = vcombine_f32(vget_high_f32(_r01_44665577.val[0]), vget_high_f32(_r23_44665577.val[0])); float32x4_t _r_77 = vcombine_f32(vget_high_f32(_r01_44665577.val[1]), vget_high_f32(_r23_44665577.val[1])); float32x4_t _r_0_m_6 = vsubq_f32(_r_00, _r_66); float32x4_t _r_7_m_1 = vsubq_f32(_r_77, _r_11); float32x4_t _r_4_m_2 = vsubq_f32(_r_44, _r_22); float32x4_t _r_3_m_5 = vsubq_f32(_r_33, _r_55); float32x4_t _tmp0 = vmlaq_lane_f32(_r_0_m_6, _r_4_m_2, vget_high_f32(_coeff1), 1); float32x4_t _tmp7 = vmlaq_lane_f32(_r_7_m_1, _r_3_m_5, vget_high_f32(_coeff1), 1); vst1q_f32(&tmp[0][m], _tmp0); vst1q_f32(&tmp[7][m], _tmp7); float32x4_t _r_2_a_6 = vaddq_f32(_r_22, _r_66); float32x4_t _r_1_a_5 = vaddq_f32(_r_11, _r_55); float32x4_t _tmp12a = vmlsq_lane_f32(_r_2_a_6, _r_44, vget_high_f32(_coeff1), 0); float32x4_t _tmp12b = vmlsq_lane_f32(_r_1_a_5, _r_33, vget_high_f32(_coeff1), 0); float32x4_t _tmp1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _tmp2 = vsubq_f32(_tmp12a, _tmp12b); vst1q_f32(&tmp[1][m], _tmp1); vst1q_f32(&tmp[2][m], _tmp2); float32x4_t _r_4_x_c = vmulq_lane_f32(_r_44, vget_high_f32(_coeff0), 0); float32x4_t _r_3_x_c = vmulq_lane_f32(_r_33, vget_low_f32(_coeff1), 0); float32x4_t _tmp34a = vaddq_f32(_r_66, _r_4_x_c); _tmp34a = vmlaq_lane_f32(_tmp34a, _r_22, vget_low_f32(_coeff0), 0); float32x4_t _tmp34b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_low_f32(_coeff0), 1); _tmp34b = vmlaq_lane_f32(_tmp34b, _r_55, vget_high_f32(_coeff0), 1); float32x4_t _tmp3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _tmp4 = vsubq_f32(_tmp34a, _tmp34b); vst1q_f32(&tmp[3][m], _tmp3); vst1q_f32(&tmp[4][m], _tmp4); // reuse r04 * 1.25 // reuse r03 * 2.5 float32x4_t _r_2_a_4c = vaddq_f32(_r_22, _r_4_x_c); float32x4_t _tmp56a = vmlaq_lane_f32(_r_66, _r_2_a_4c, vget_low_f32(_coeff1), 1); float32x4_t _tmp56b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_high_f32(_coeff0), 1); _tmp56b = vmlaq_lane_f32(_tmp56b, _r_55, vget_low_f32(_coeff0), 1); float32x4_t _tmp5 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _tmp6 = vsubq_f32(_tmp56a, _tmp56b); vst1q_f32(&tmp[5][m], _tmp5); vst1q_f32(&tmp[6][m], _tmp6); r0 += w * 4; r1 += w * 4; r2 += w * 4; r3 += w * 4; } const float* t0 = tmp[0]; const float* t1 = tmp[1]; const float* t2 = tmp[2]; const float* t3 = tmp[3]; float* r0_tm0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm1 = img0_tm.row(i * w_tm / 8 + j + tiles * 8); float* r0_tm2 = img0_tm.row(i * w_tm / 8 + j + tiles * 16); float* r0_tm3 = img0_tm.row(i * w_tm / 8 + j + tiles * 24); for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _t0_0123 = vld1q_f32(t0); float32x4_t _t0_4567 = vld1q_f32(t0 + 4); float32x4_t _t1_0123 = vld1q_f32(t1); float32x4_t _t1_4567 = vld1q_f32(t1 + 4); float32x4_t _t2_0123 = vld1q_f32(t2); float32x4_t _t2_4567 = vld1q_f32(t2 + 4); float32x4_t _t3_0123 = vld1q_f32(t3); float32x4_t _t3_4567 = vld1q_f32(t3 + 4); float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123); float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567); float32x4x2_t _t23_00221133 = vtrnq_f32(_t2_0123, _t3_0123); float32x4x2_t _t23_44665577 = vtrnq_f32(_t2_4567, _t3_4567); // no vswp intrinsic :( float32x4_t _t_00 = vcombine_f32(vget_low_f32(_t01_00221133.val[0]), vget_low_f32(_t23_00221133.val[0])); float32x4_t _t_11 = vcombine_f32(vget_low_f32(_t01_00221133.val[1]), vget_low_f32(_t23_00221133.val[1])); float32x4_t _t_22 = vcombine_f32(vget_high_f32(_t01_00221133.val[0]), vget_high_f32(_t23_00221133.val[0])); float32x4_t _t_33 = vcombine_f32(vget_high_f32(_t01_00221133.val[1]), vget_high_f32(_t23_00221133.val[1])); float32x4_t _t_44 = vcombine_f32(vget_low_f32(_t01_44665577.val[0]), vget_low_f32(_t23_44665577.val[0])); float32x4_t _t_55 = vcombine_f32(vget_low_f32(_t01_44665577.val[1]), vget_low_f32(_t23_44665577.val[1])); float32x4_t _t_66 = vcombine_f32(vget_high_f32(_t01_44665577.val[0]), vget_high_f32(_t23_44665577.val[0])); float32x4_t _t_77 = vcombine_f32(vget_high_f32(_t01_44665577.val[1]), vget_high_f32(_t23_44665577.val[1])); float32x4_t _t_0_m_6 = vsubq_f32(_t_00, _t_66); float32x4_t _t_7_m_1 = vsubq_f32(_t_77, _t_11); float32x4_t _t_4_m_2 = vsubq_f32(_t_44, _t_22); float32x4_t _t_3_m_5 = vsubq_f32(_t_33, _t_55); float32x4_t _r0_tm_0_0 = vmlaq_lane_f32(_t_0_m_6, _t_4_m_2, vget_high_f32(_coeff1), 1); float32x4_t _r0_tm_4_3 = vmlaq_lane_f32(_t_7_m_1, _t_3_m_5, vget_high_f32(_coeff1), 1); r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_0, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_0, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_0, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_0, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; float32x4_t _t_2_m_6 = vaddq_f32(_t_22, _t_66); float32x4_t _t_1_m_5 = vaddq_f32(_t_11, _t_55); float32x4_t _tmp12a = vmlsq_lane_f32(_t_2_m_6, _t_44, vget_high_f32(_coeff1), 0); float32x4_t _tmp12b = vmlsq_lane_f32(_t_1_m_5, _t_33, vget_high_f32(_coeff1), 0); float32x4_t _r0_tm_0_1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _r0_tm_0_2 = vsubq_f32(_tmp12a, _tmp12b); r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_1, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_1, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_1, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_1, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_2, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_2, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_2, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_2, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; float32x4_t _t_4_x_c = vmulq_lane_f32(_t_44, vget_high_f32(_coeff0), 0); float32x4_t _t_3_x_c = vmulq_lane_f32(_t_33, vget_low_f32(_coeff1), 0); float32x4_t _tmp34a = vaddq_f32(_t_66, _t_4_x_c); _tmp34a = vmlaq_lane_f32(_tmp34a, _t_22, vget_low_f32(_coeff0), 0); float32x4_t _tmp34b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_low_f32(_coeff0), 1); _tmp34b = vmlaq_lane_f32(_tmp34b, _t_55, vget_high_f32(_coeff0), 1); float32x4_t _r0_tm_0_3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _r0_tm_4_0 = vsubq_f32(_tmp34a, _tmp34b); r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_3, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_3, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_3, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_3, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_0, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_0, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_0, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_0, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; float32x4_t _t_2_a_4c = vaddq_f32(_t_22, _t_4_x_c); float32x4_t _tmp56a = vmlaq_lane_f32(_t_66, _t_2_a_4c, vget_low_f32(_coeff1), 1); float32x4_t _tmp56b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_high_f32(_coeff0), 1); _tmp56b = vmlaq_lane_f32(_tmp56b, _t_55, vget_low_f32(_coeff0), 1); float32x4_t _r0_tm_4_1 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _r0_tm_4_2 = vsubq_f32(_tmp56a, _tmp56b); r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_1, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_1, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_1, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_1, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_2, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_2, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_2, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_2, 3); r0_tm0 += img0_tm.w * tiles; r0_tm1 += img0_tm.w * tiles; r0_tm2 += img0_tm.w * tiles; r0_tm3 += img0_tm.w * tiles; r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_3, 0); r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_3, 1); r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_3, 2); r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_3, 3); t0 += 8 * 4; t1 += 8 * 4; t2 += 8 * 4; t3 += 8 * 4; r0_tm0 += img0_tm.w * tiles * 25; r0_tm1 += img0_tm.w * tiles * 25; r0_tm2 += img0_tm.w * tiles * 25; r0_tm3 += img0_tm.w * tiles * 25; } #else // __aarch64__ float* t0 = tmp[0]; float* t1 = tmp[1]; float* t2 = tmp[2]; float* t3 = tmp[3]; int stepw = w * 4 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%4], %18 \n" "vld1.f32 {d20-d23}, [%5], %18 \n" "vld1.f32 {d24-d27}, [%6], %18 \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%7], %18 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f17[1] \n" "vmul.f32 q7, q14, %e17[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f16[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f17[0] \n" "vmls.f32 q5, q14, %f17[0] \n" "vst1.f32 {d4-d5}, [%0] \n" // tmp[0][m] "add %0, %0, #128 \n" "vmov q3, q7 \n" // use q7 "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e16[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f16[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e16[0] \n" "vmla.f32 q3, q11, %f16[1] \n" "vst1.f32 {d16-d17}, [%1] \n" // tmp[1][m] "add %1, %1, #128 \n" "vmla.f32 q4, q6, %e17[1] \n" "vmla.f32 q5, q11, %e16[1] \n" "vst1.f32 {d18-d19}, [%2] \n" // tmp[2][m] "add %2, %2, #128 \n" "vadd.f32 q8, q2, q3 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16-d17}, [%3] \n" // tmp[3][m] "add %3, %3, #128 \n" "vst1.f32 {d18-d19}, [%0] \n" // tmp[4][m] "sub %0, %0, #112 \n" "vmla.f32 q6, q7, %f17[1] \n" "vst1.f32 {d4-d5}, [%1] \n" // tmp[5][m] "sub %1, %1, #112 \n" "vst1.f32 {d6-d7}, [%2] \n" // tmp[6][m] "sub %2, %2, #112 \n" "vst1.f32 {d12-d13}, [%3] \n" // tmp[7][m] "sub %3, %3, #112 \n" // loop1 "vld1.f32 {d16-d19}, [%4] \n" "vld1.f32 {d20-d23}, [%5] \n" "vld1.f32 {d24-d27}, [%6] \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%7] \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f17[1] \n" "vmul.f32 q7, q14, %e17[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f16[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f17[0] \n" "vmls.f32 q5, q14, %f17[0] \n" "vst1.f32 {d4-d5}, [%0] \n" // tmp[0][m] "add %0, %0, #128 \n" "vmov q3, q7 \n" // use q7 "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e16[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f16[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e16[0] \n" "vmla.f32 q3, q11, %f16[1] \n" "vst1.f32 {d16-d17}, [%1] \n" // tmp[1][m] "add %1, %1, #128 \n" "vmla.f32 q4, q6, %e17[1] \n" "vmla.f32 q5, q11, %e16[1] \n" "vst1.f32 {d18-d19}, [%2] \n" // tmp[2][m] "add %2, %2, #128 \n" "vadd.f32 q8, q2, q3 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vadd.f32 q2, q4, q5 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d16-d17}, [%3] \n" // tmp[3][m] "add %3, %3, #128 \n" "vst1.f32 {d18-d19}, [%0] \n" // tmp[4][m] "vmla.f32 q6, q7, %f17[1] \n" "vst1.f32 {d4-d5}, [%1] \n" // tmp[5][m] "vst1.f32 {d6-d7}, [%2] \n" // tmp[6][m] "vst1.f32 {d12-d13}, [%3] \n" // tmp[7][m] : "=r"(t0), // %0 "=r"(t1), // %1 "=r"(t2), // %2 "=r"(t3), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(r2), // %6 "=r"(r3) // %7 : "0"(t0), "1"(t1), "2"(t2), "3"(t3), "4"(r0), "5"(r1), "6"(r2), "7"(r3), "w"(_coeff0), // %16 "w"(_coeff1), // %17 "r"(stepw) // %18 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); t0 = tmp[0]; t1 = tmp[1]; t2 = tmp[2]; t3 = tmp[3]; float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 8); float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 16); float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 24); int step = img0_tm.w * tiles * 4; int step2 = img0_tm.w * tiles * 25 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%4] \n" "add %4, %4, #128 \n" "vld1.f32 {d20-d23}, [%5] \n" "add %5, %5, #128 \n" "vld1.f32 {d24-d27}, [%6] \n" "add %6, %6, #128 \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%7] \n" "add %7, %7, #128 \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f17[1] \n" "vmul.f32 q7, q14, %e17[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f16[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f17[0] \n" "vmls.f32 q5, q14, %f17[0] \n" "vst1.f32 {d4[0]}, [%0], %18 \n" "vst1.f32 {d4[1]}, [%1], %18 \n" "vmov q3, q7 \n" // use q7 "vst1.f32 {d5[0]}, [%2], %18 \n" "vst1.f32 {d5[1]}, [%3], %18 \n" "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e16[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f16[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e16[0] \n" "vmla.f32 q3, q11, %f16[1] \n" "vst1.f32 {d16[0]}, [%0], %18 \n" "vst1.f32 {d16[1]}, [%1], %18 \n" "vmla.f32 q4, q6, %e17[1] \n" "vst1.f32 {d17[0]}, [%2], %18 \n" "vst1.f32 {d17[1]}, [%3], %18 \n" "vmla.f32 q5, q11, %e16[1] \n" "vst1.f32 {d18[0]}, [%0], %18 \n" "vst1.f32 {d18[1]}, [%1], %18 \n" "vadd.f32 q8, q2, q3 \n" "vst1.f32 {d19[0]}, [%2], %18 \n" "vst1.f32 {d19[1]}, [%3], %18 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vst1.f32 {d16[0]}, [%0], %18 \n" "vst1.f32 {d16[1]}, [%1], %18 \n" "vst1.f32 {d17[0]}, [%2], %18 \n" "vst1.f32 {d17[1]}, [%3], %18 \n" "vadd.f32 q2, q4, q5 \n" "vst1.f32 {d18[0]}, [%0], %18 \n" "vst1.f32 {d18[1]}, [%1], %18 \n" "vst1.f32 {d19[0]}, [%2], %18 \n" "vst1.f32 {d19[1]}, [%3], %18 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d4[0]}, [%0], %18 \n" "vst1.f32 {d4[1]}, [%1], %18 \n" "vst1.f32 {d5[0]}, [%2], %18 \n" "vst1.f32 {d5[1]}, [%3], %18 \n" "vmla.f32 q6, q7, %f17[1] \n" "vst1.f32 {d6[0]}, [%0], %18 \n" "vst1.f32 {d6[1]}, [%1], %18 \n" "vst1.f32 {d7[0]}, [%2], %18 \n" "vst1.f32 {d7[1]}, [%3], %18 \n" "vst1.f32 {d12[0]}, [%0], %19 \n" "vst1.f32 {d12[1]}, [%1], %19 \n" "vst1.f32 {d13[0]}, [%2], %19 \n" "vst1.f32 {d13[1]}, [%3], %19 \n" // loop1 "vld1.f32 {d16-d19}, [%4] \n" "vld1.f32 {d20-d23}, [%5] \n" "vld1.f32 {d24-d27}, [%6] \n" "vtrn.32 q8, q10 \n" "vld1.f32 {d28-d31}, [%7] \n" "vtrn.32 q9, q11 \n" "vtrn.32 q12, q14 \n" "vtrn.32 q13, q15 \n" "vswp d17, d24 \n" "vswp d19, d26 \n" "vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55 "vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77 "vsub.f32 q2, q8, q13 \n" "vsub.f32 q3, q9, q12 \n" "vadd.f32 q4, q12, q13 \n" "vadd.f32 q5, q10, q11 \n" "vmla.f32 q2, q3, %f17[1] \n" "vmul.f32 q7, q14, %e17[0] \n" // q7 = _r_3_x_c "vmul.f32 q6, q9, %f16[0] \n" // q6 = _r_4_x_c "vmls.f32 q4, q9, %f17[0] \n" "vmls.f32 q5, q14, %f17[0] \n" "vst1.f32 {d4[0]}, [%0], %18 \n" "vst1.f32 {d4[1]}, [%1], %18 \n" "vmov q3, q7 \n" // use q7 "vst1.f32 {d5[0]}, [%2], %18 \n" "vst1.f32 {d5[1]}, [%3], %18 \n" "vadd.f32 q2, q13, q6 \n" // use q6 "vmla.f32 q3, q10, %e16[1] \n" "vadd.f32 q8, q4, q5 \n" "vsub.f32 q9, q4, q5 \n" "vmov q5, q7 \n" // use q7 "vadd.f32 q6, q12, q6 \n" // use q6 "vmla.f32 q5, q10, %f16[1] \n" "vmov q4, q13 \n" "vmla.f32 q2, q12, %e16[0] \n" "vmla.f32 q3, q11, %f16[1] \n" "vst1.f32 {d16[0]}, [%0], %18 \n" "vst1.f32 {d16[1]}, [%1], %18 \n" "vmla.f32 q4, q6, %e17[1] \n" "vst1.f32 {d17[0]}, [%2], %18 \n" "vst1.f32 {d17[1]}, [%3], %18 \n" "vmla.f32 q5, q11, %e16[1] \n" "vst1.f32 {d18[0]}, [%0], %18 \n" "vst1.f32 {d18[1]}, [%1], %18 \n" "vadd.f32 q8, q2, q3 \n" "vst1.f32 {d19[0]}, [%2], %18 \n" "vst1.f32 {d19[1]}, [%3], %18 \n" "vsub.f32 q9, q2, q3 \n" "vsub.f32 q6, q15, q10 \n" "vsub.f32 q7, q14, q11 \n" "vst1.f32 {d16[0]}, [%0], %18 \n" "vst1.f32 {d16[1]}, [%1], %18 \n" "vst1.f32 {d17[0]}, [%2], %18 \n" "vst1.f32 {d17[1]}, [%3], %18 \n" "vadd.f32 q2, q4, q5 \n" "vst1.f32 {d18[0]}, [%0], %18 \n" "vst1.f32 {d18[1]}, [%1], %18 \n" "vst1.f32 {d19[0]}, [%2], %18 \n" "vst1.f32 {d19[1]}, [%3], %18 \n" "vsub.f32 q3, q4, q5 \n" "vst1.f32 {d4[0]}, [%0], %18 \n" "vst1.f32 {d4[1]}, [%1], %18 \n" "vst1.f32 {d5[0]}, [%2], %18 \n" "vst1.f32 {d5[1]}, [%3], %18 \n" "vmla.f32 q6, q7, %f17[1] \n" "vst1.f32 {d6[0]}, [%0], %18 \n" "vst1.f32 {d6[1]}, [%1], %18 \n" "vst1.f32 {d7[0]}, [%2], %18 \n" "vst1.f32 {d7[1]}, [%3], %18 \n" "vst1.f32 {d12[0]}, [%0] \n" "vst1.f32 {d12[1]}, [%1] \n" "vst1.f32 {d13[0]}, [%2] \n" "vst1.f32 {d13[1]}, [%3] \n" : "=r"(r0_tm0_0), // %0 "=r"(r0_tm1_0), // %1 "=r"(r0_tm2_0), // %2 "=r"(r0_tm3_0), // %3 "=r"(t0), // %4 "=r"(t1), // %5 "=r"(t2), // %6 "=r"(t3) // %7 : "0"(r0_tm0_0), "1"(r0_tm1_0), "2"(r0_tm2_0), "3"(r0_tm3_0), "4"(t0), "5"(t1), "6"(t2), "7"(t3), "w"(_coeff0), // %16 "w"(_coeff1), // %17 "r"(step), // %18 "r"(step2) // %19 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else const float* r0 = img0.row(i * 6) + j * 6; for (int m = 0; m < 8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25f; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25f; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25f); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25f); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25f - r0[4] * 1.25f); float tmp34b = (r0[1] * 0.5f - r0[3] * 2.5f + r0[5] * 2.f); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25f) * 4.f); float tmp56b = (r0[1] * 2.f - r0[3] * 2.5f + r0[5] * 0.5f); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tm_0 = img0_tm.row(i * w_tm / 8 + j); float* r0_tm_1 = img0_tm.row(i * w_tm / 8 + j + tiles); float* r0_tm_2 = img0_tm.row(i * w_tm / 8 + j + tiles * 2); float* r0_tm_3 = img0_tm.row(i * w_tm / 8 + j + tiles * 3); float* r0_tm_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 4); float* r0_tm_5 = img0_tm.row(i * w_tm / 8 + j + tiles * 5); float* r0_tm_6 = img0_tm.row(i * w_tm / 8 + j + tiles * 6); float* r0_tm_7 = img0_tm.row(i * w_tm / 8 + j + tiles * 7); for (int m = 0; m < 8; m++) { const float* tmp0 = tmp[m]; r0_tm_0[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25f; r0_tm_7[0] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25f; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25f); float tmp12b = (tmp0[1] - tmp0[3] * 4.25f + tmp0[5]); r0_tm_1[0] = tmp12a + tmp12b; r0_tm_2[0] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25f - tmp0[4] * 1.25f); float tmp34b = (tmp0[1] * 0.5f - tmp0[3] * 2.5f + tmp0[5] * 2.f); r0_tm_3[0] = tmp34a + tmp34b; r0_tm_4[0] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25f) * 4.f); float tmp56b = (tmp0[1] * 2.f - tmp0[3] * 2.5f + tmp0[5] * 0.5f); r0_tm_5[0] = tmp56a + tmp56b; r0_tm_6[0] = tmp56a - tmp56b; r0_tm_0 += img0_tm.w * tiles * 8; r0_tm_1 += img0_tm.w * tiles * 8; r0_tm_2 += img0_tm.w * tiles * 8; r0_tm_3 += img0_tm.w * tiles * 8; r0_tm_4 += img0_tm.w * tiles * 8; r0_tm_5 += img0_tm.w * tiles * 8; r0_tm_6 += img0_tm.w * tiles * 8; r0_tm_7 += img0_tm.w * tiles * 8; } #endif // __ARM_NEON } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; // permute // bottom_blob_tm.create(1, 64 * tiles, inch); // Mat bottom_blob_tm2(inch, tiles, 64); Mat bottom_blob_tm2(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 4u, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { float* tm2p = tm2.row(i / 8); const float* r0 = bottom_blob_tm; r0 += r * tiles + i; for (int q = 0; q < inch; q++) { #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0 + 4); vst1q_f32(tm2p, _r0); vst1q_f32(tm2p + 4, _r0n); #else tm2p[0] = r0[0]; tm2p[1] = r0[1]; tm2p[2] = r0[2]; tm2p[3] = r0[3]; tm2p[4] = r0[4]; tm2p[5] = r0[5]; tm2p[6] = r0[6]; tm2p[7] = r0[7]; #endif // __ARM_NEON r0 += bottom_blob_tm.cstep; tm2p += 8; } } for (; i + 3 < tiles; i += 4) { float* tm2p = tm2.row(i / 8 + (i % 8) / 4); const float* r0 = bottom_blob_tm; r0 += r * tiles + i; for (int q = 0; q < inch; q++) { #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); vst1q_f32(tm2p, _r0); #else tm2p[0] = r0[0]; tm2p[1] = r0[1]; tm2p[2] = r0[2]; tm2p[3] = r0[3]; #endif // __ARM_NEON r0 += bottom_blob_tm.cstep; tm2p += 4; } } for (; i < tiles; i++) { float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + i % 4); const float* r0 = bottom_blob_tm; r0 += r * tiles + i; for (int q = 0; q < inch; q++) { tm2p[0] = r0[0]; r0 += bottom_blob_tm.cstep; tm2p += 1; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(1, 64 * tiles, outch); int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; const Mat kernel_tm0 = kernel_tm.channel(p / 8); Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p + 1); Mat out2_tm = top_blob_tm.channel(p + 2); Mat out3_tm = top_blob_tm.channel(p + 3); Mat out4_tm = top_blob_tm.channel(p + 4); Mat out5_tm = top_blob_tm.channel(p + 5); Mat out6_tm = top_blob_tm.channel(p + 6); Mat out7_tm = top_blob_tm.channel(p + 7); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; float* output4_tm = out4_tm; float* output5_tm = out5_tm; float* output6_tm = out6_tm; float* output7_tm = out7_tm; for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { const float* bb2p0 = bb2.row(i / 8); const float* ktm0 = kernel_tm0.row(r); asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" // inch loop "lsr w4, %w20, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "fmla v18.4s, v8.4s, v0.s[1] \n" "fmla v19.4s, v9.4s, v0.s[1] \n" "fmla v20.4s, v8.4s, v0.s[2] \n" "fmla v21.4s, v9.4s, v0.s[2] \n" "fmla v22.4s, v8.4s, v0.s[3] \n" "fmla v23.4s, v9.4s, v0.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n" "fmla v24.4s, v8.4s, v1.s[0] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v26.4s, v8.4s, v1.s[1] \n" "fmla v27.4s, v9.4s, v1.s[1] \n" "fmla v28.4s, v8.4s, v1.s[2] \n" "fmla v29.4s, v9.4s, v1.s[2] \n" "fmla v30.4s, v8.4s, v1.s[3] \n" "fmla v31.4s, v9.4s, v1.s[3] \n" "fmla v16.4s, v10.4s, v2.s[0] \n" "fmla v17.4s, v11.4s, v2.s[0] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v19.4s, v11.4s, v2.s[1] \n" "fmla v20.4s, v10.4s, v2.s[2] \n" "fmla v21.4s, v11.4s, v2.s[2] \n" "fmla v22.4s, v10.4s, v2.s[3] \n" "fmla v23.4s, v11.4s, v2.s[3] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n" "fmla v24.4s, v10.4s, v3.s[0] \n" "fmla v25.4s, v11.4s, v3.s[0] \n" "fmla v26.4s, v10.4s, v3.s[1] \n" "fmla v27.4s, v11.4s, v3.s[1] \n" "fmla v28.4s, v10.4s, v3.s[2] \n" "fmla v29.4s, v11.4s, v3.s[2] \n" "fmla v30.4s, v10.4s, v3.s[3] \n" "fmla v31.4s, v11.4s, v3.s[3] \n" "fmla v16.4s, v12.4s, v4.s[0] \n" "fmla v17.4s, v13.4s, v4.s[0] \n" "fmla v18.4s, v12.4s, v4.s[1] \n" "fmla v19.4s, v13.4s, v4.s[1] \n" "fmla v20.4s, v12.4s, v4.s[2] \n" "fmla v21.4s, v13.4s, v4.s[2] \n" "fmla v22.4s, v12.4s, v4.s[3] \n" "fmla v23.4s, v13.4s, v4.s[3] \n" "fmla v24.4s, v12.4s, v5.s[0] \n" "fmla v25.4s, v13.4s, v5.s[0] \n" "fmla v26.4s, v12.4s, v5.s[1] \n" "fmla v27.4s, v13.4s, v5.s[1] \n" "fmla v28.4s, v12.4s, v5.s[2] \n" "fmla v29.4s, v13.4s, v5.s[2] \n" "fmla v30.4s, v12.4s, v5.s[3] \n" "fmla v31.4s, v13.4s, v5.s[3] \n" "fmla v16.4s, v14.4s, v6.s[0] \n" "fmla v17.4s, v15.4s, v6.s[0] \n" "fmla v18.4s, v14.4s, v6.s[1] \n" "fmla v19.4s, v15.4s, v6.s[1] \n" "fmla v20.4s, v14.4s, v6.s[2] \n" "fmla v21.4s, v15.4s, v6.s[2] \n" "fmla v22.4s, v14.4s, v6.s[3] \n" "fmla v23.4s, v15.4s, v6.s[3] \n" "subs w4, w4, #1 \n" "fmla v24.4s, v14.4s, v7.s[0] \n" "fmla v25.4s, v15.4s, v7.s[0] \n" "fmla v26.4s, v14.4s, v7.s[1] \n" "fmla v27.4s, v15.4s, v7.s[1] \n" "fmla v28.4s, v14.4s, v7.s[2] \n" "fmla v29.4s, v15.4s, v7.s[2] \n" "fmla v30.4s, v14.4s, v7.s[3] \n" "fmla v31.4s, v15.4s, v7.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w20, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v8.4s, v9.4s}, [%8], #32 \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v0.4s, v1.4s}, [%9], #32 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "fmla v18.4s, v8.4s, v0.s[1] \n" "fmla v19.4s, v9.4s, v0.s[1] \n" "fmla v20.4s, v8.4s, v0.s[2] \n" "fmla v21.4s, v9.4s, v0.s[2] \n" "fmla v22.4s, v8.4s, v0.s[3] \n" "fmla v23.4s, v9.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "fmla v24.4s, v8.4s, v1.s[0] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v26.4s, v8.4s, v1.s[1] \n" "fmla v27.4s, v9.4s, v1.s[1] \n" "fmla v28.4s, v8.4s, v1.s[2] \n" "fmla v29.4s, v9.4s, v1.s[2] \n" "fmla v30.4s, v8.4s, v1.s[3] \n" "fmla v31.4s, v9.4s, v1.s[3] \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0], #32 \n" "st1 {v18.4s, v19.4s}, [%1], #32 \n" "st1 {v20.4s, v21.4s}, [%2], #32 \n" "st1 {v22.4s, v23.4s}, [%3], #32 \n" "st1 {v24.4s, v25.4s}, [%4], #32 \n" "st1 {v26.4s, v27.4s}, [%5], #32 \n" "st1 {v28.4s, v29.4s}, [%6], #32 \n" "st1 {v30.4s, v31.4s}, [%7], #32 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(output4_tm), // %4 "=r"(output5_tm), // %5 "=r"(output6_tm), // %6 "=r"(output7_tm), // %7 "=r"(bb2p0), // %8 "=r"(ktm0) // %9 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(output4_tm), "5"(output5_tm), "6"(output6_tm), "7"(output7_tm), "8"(bb2p0), "9"(ktm0), "r"(inch) // %20 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4); const float* ktm0 = kernel_tm0.row(r); asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" // inch loop "lsr w4, %w20, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v0.s[1] \n" "fmla v18.4s, v8.4s, v0.s[2] \n" "fmla v19.4s, v8.4s, v0.s[3] \n" "fmla v20.4s, v8.4s, v1.s[0] \n" "fmla v21.4s, v8.4s, v1.s[1] \n" "fmla v22.4s, v8.4s, v1.s[2] \n" "fmla v23.4s, v8.4s, v1.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n" "fmla v16.4s, v9.4s, v2.s[0] \n" "fmla v17.4s, v9.4s, v2.s[1] \n" "fmla v18.4s, v9.4s, v2.s[2] \n" "fmla v19.4s, v9.4s, v2.s[3] \n" "fmla v20.4s, v9.4s, v3.s[0] \n" "fmla v21.4s, v9.4s, v3.s[1] \n" "fmla v22.4s, v9.4s, v3.s[2] \n" "fmla v23.4s, v9.4s, v3.s[3] \n" "fmla v16.4s, v10.4s, v4.s[0] \n" "fmla v17.4s, v10.4s, v4.s[1] \n" "fmla v18.4s, v10.4s, v4.s[2] \n" "fmla v19.4s, v10.4s, v4.s[3] \n" "fmla v20.4s, v10.4s, v5.s[0] \n" "fmla v21.4s, v10.4s, v5.s[1] \n" "fmla v22.4s, v10.4s, v5.s[2] \n" "fmla v23.4s, v10.4s, v5.s[3] \n" "subs w4, w4, #1 \n" "fmla v16.4s, v11.4s, v6.s[0] \n" "fmla v17.4s, v11.4s, v6.s[1] \n" "fmla v18.4s, v11.4s, v6.s[2] \n" "fmla v19.4s, v11.4s, v6.s[3] \n" "fmla v20.4s, v11.4s, v7.s[0] \n" "fmla v21.4s, v11.4s, v7.s[1] \n" "fmla v22.4s, v11.4s, v7.s[2] \n" "fmla v23.4s, v11.4s, v7.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w20, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.4s}, [%8], #16 \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v0.4s, v1.4s}, [%9], #32 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v0.s[1] \n" "fmla v18.4s, v8.4s, v0.s[2] \n" "fmla v19.4s, v8.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "fmla v20.4s, v8.4s, v1.s[0] \n" "fmla v21.4s, v8.4s, v1.s[1] \n" "fmla v22.4s, v8.4s, v1.s[2] \n" "fmla v23.4s, v8.4s, v1.s[3] \n" "bne 2b \n" "3: \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "st1 {v20.4s}, [%4], #16 \n" "st1 {v21.4s}, [%5], #16 \n" "st1 {v22.4s}, [%6], #16 \n" "st1 {v23.4s}, [%7], #16 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(output4_tm), // %4 "=r"(output5_tm), // %5 "=r"(output6_tm), // %6 "=r"(output7_tm), // %7 "=r"(bb2p0), // %8 "=r"(ktm0) // %9 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(output4_tm), "5"(output5_tm), "6"(output6_tm), "7"(output7_tm), "8"(bb2p0), "9"(ktm0), "r"(inch) // %20 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); } for (; i < tiles; i++) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); const float* ktm0 = kernel_tm0.row(r); float32x4_t _sum0123 = vdupq_n_f32(0.f); float32x4_t _sum4567 = vdupq_n_f32(0.f); int q = 0; for (; q + 3 < inch; q += 4) { // asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :); float32x4_t _bb2p0 = vld1q_f32(bb2p0); bb2p0 += 4; // asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :); float32x4_t _ktm0 = vld1q_f32(ktm0 + 0); float32x4_t _ktm1 = vld1q_f32(ktm0 + 4); float32x4_t _ktm2 = vld1q_f32(ktm0 + 8); float32x4_t _ktm3 = vld1q_f32(ktm0 + 12); ktm0 += 16; _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm0, _bb2p0, 0); _sum4567 = vmlaq_laneq_f32(_sum4567, _ktm1, _bb2p0, 0); _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm2, _bb2p0, 1); _sum4567 = vmlaq_laneq_f32(_sum4567, _ktm3, _bb2p0, 1); // asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :); float32x4_t _ktm4 = vld1q_f32(ktm0 + 0); float32x4_t _ktm5 = vld1q_f32(ktm0 + 4); float32x4_t _ktm6 = vld1q_f32(ktm0 + 8); float32x4_t _ktm7 = vld1q_f32(ktm0 + 12); ktm0 += 16; _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm4, _bb2p0, 2); _sum4567 = vmlaq_laneq_f32(_sum4567, _ktm5, _bb2p0, 2); _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm6, _bb2p0, 3); _sum4567 = vmlaq_laneq_f32(_sum4567, _ktm7, _bb2p0, 3); } for (; q < inch; q++) { float32x4_t _bb2p0 = vld1q_dup_f32(bb2p0); float32x4_t _ktm0123 = vld1q_f32(ktm0 + 0); float32x4_t _ktm4567 = vld1q_f32(ktm0 + 4); _sum0123 = vmlaq_f32(_sum0123, _bb2p0, _ktm0123); _sum4567 = vmlaq_f32(_sum4567, _bb2p0, _ktm4567); bb2p0 += 1; ktm0 += 8; } float sum0 = vgetq_lane_f32(_sum0123, 0); float sum1 = vgetq_lane_f32(_sum0123, 1); float sum2 = vgetq_lane_f32(_sum0123, 2); float sum3 = vgetq_lane_f32(_sum0123, 3); float sum4 = vgetq_lane_f32(_sum4567, 0); float sum5 = vgetq_lane_f32(_sum4567, 1); float sum6 = vgetq_lane_f32(_sum4567, 2); float sum7 = vgetq_lane_f32(_sum4567, 3); output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output4_tm[0] = sum4; output5_tm[0] = sum5; output6_tm[0] = sum6; output7_tm[0] = sum7; output0_tm += 1; output1_tm += 1; output2_tm += 1; output3_tm += 1; output4_tm += 1; output5_tm += 1; output6_tm += 1; output7_tm += 1; } } } #endif // __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; #if __ARM_NEON && __aarch64__ const Mat kernel_tm0 = kernel_tm.channel(p / 8 + (p % 8) / 4); #else const Mat kernel_tm0 = kernel_tm.channel(p / 4); #endif Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p + 1); Mat out2_tm = top_blob_tm.channel(p + 2); Mat out3_tm = top_blob_tm.channel(p + 3); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { const float* bb2p0 = bb2.row(i / 8); const float* ktm0 = kernel_tm0.row(r); #if __ARM_NEON #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" // inch loop "lsr w4, %w12, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "fmla v10.4s, v4.4s, v0.s[1] \n" "fmla v11.4s, v5.4s, v0.s[1] \n" "fmla v12.4s, v4.4s, v0.s[2] \n" "fmla v13.4s, v5.4s, v0.s[2] \n" "fmla v14.4s, v4.4s, v0.s[3] \n" "fmla v15.4s, v5.4s, v0.s[3] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v8.4s, v6.4s, v1.s[0] \n" "fmla v9.4s, v7.4s, v1.s[0] \n" "fmla v10.4s, v6.4s, v1.s[1] \n" "fmla v11.4s, v7.4s, v1.s[1] \n" "fmla v12.4s, v6.4s, v1.s[2] \n" "fmla v13.4s, v7.4s, v1.s[2] \n" "fmla v14.4s, v6.4s, v1.s[3] \n" "fmla v15.4s, v7.4s, v1.s[3] \n" "fmla v8.4s, v16.4s, v2.s[0] \n" "fmla v9.4s, v17.4s, v2.s[0] \n" "fmla v10.4s, v16.4s, v2.s[1] \n" "fmla v11.4s, v17.4s, v2.s[1] \n" "fmla v12.4s, v16.4s, v2.s[2] \n" "fmla v13.4s, v17.4s, v2.s[2] \n" "fmla v14.4s, v16.4s, v2.s[3] \n" "fmla v15.4s, v17.4s, v2.s[3] \n" "fmla v8.4s, v18.4s, v3.s[0] \n" "fmla v9.4s, v19.4s, v3.s[0] \n" "fmla v10.4s, v18.4s, v3.s[1] \n" "fmla v11.4s, v19.4s, v3.s[1] \n" "fmla v12.4s, v18.4s, v3.s[2] \n" "fmla v13.4s, v19.4s, v3.s[2] \n" "fmla v14.4s, v18.4s, v3.s[3] \n" "fmla v15.4s, v19.4s, v3.s[3] \n" "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w12, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v4.4s, v5.4s}, [%4], #32 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "fmla v10.4s, v4.4s, v0.s[1] \n" "fmla v11.4s, v5.4s, v0.s[1] \n" "fmla v12.4s, v4.4s, v0.s[2] \n" "fmla v13.4s, v5.4s, v0.s[2] \n" "fmla v14.4s, v4.4s, v0.s[3] \n" "fmla v15.4s, v5.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v8.4s, v9.4s}, [%0], #32 \n" "st1 {v10.4s, v11.4s}, [%1], #32 \n" "st1 {v12.4s, v13.4s}, [%2], #32 \n" "st1 {v14.4s, v15.4s}, [%3], #32 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(bb2p0), // %4 "=r"(ktm0) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(bb2p0), "5"(ktm0), "r"(inch) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"); #else // __aarch64__ asm volatile( "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "veor q10, q10, q10 \n" "veor q11, q11, q11 \n" "veor q12, q12, q12 \n" "veor q13, q13, q13 \n" "veor q14, q14, q14 \n" "veor q15, q15, q15 \n" // inch loop "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" // "vld1.f32 {d0-d3}, [%5 :128]! \n" // "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q5, d0[0] \n" "vmla.f32 q10, q4, d0[1] \n" "vmla.f32 q11, q5, d0[1] \n" "vmla.f32 q12, q4, d1[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q4, d1[1] \n" "vmla.f32 q15, q5, d1[1] \n" "vmla.f32 q8, q6, d2[0] \n" "vmla.f32 q9, q7, d2[0] \n" "vmla.f32 q10, q6, d2[1] \n" "vmla.f32 q11, q7, d2[1] \n" "vmla.f32 q12, q6, d3[0] \n" "vmla.f32 q13, q7, d3[0] \n" "vmla.f32 q14, q6, d3[1] \n" "vmla.f32 q15, q7, d3[1] \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "vmla.f32 q8, q4, d4[0] \n" "vmla.f32 q9, q5, d4[0] \n" "vmla.f32 q10, q4, d4[1] \n" "vmla.f32 q11, q5, d4[1] \n" "vmla.f32 q12, q4, d5[0] \n" "vmla.f32 q13, q5, d5[0] \n" "vmla.f32 q14, q4, d5[1] \n" "vmla.f32 q15, q5, d5[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q6, d6[0] \n" "vmla.f32 q9, q7, d6[0] \n" "vmla.f32 q10, q6, d6[1] \n" "vmla.f32 q11, q7, d6[1] \n" "vmla.f32 q12, q6, d7[0] \n" "vmla.f32 q13, q7, d7[0] \n" "vmla.f32 q14, q6, d7[1] \n" "vmla.f32 q15, q7, d7[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %12, #3 \n" // r4 = remain = tiles & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #256] \n" "vld1.f32 {d8-d11}, [%4 :128]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q5, d0[0] \n" "vmla.f32 q10, q4, d0[1] \n" "vmla.f32 q11, q5, d0[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q12, q4, d1[0] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q14, q4, d1[1] \n" "vmla.f32 q15, q5, d1[1] \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d19}, [%0]! \n" "vst1.f32 {d20-d23}, [%1]! \n" "vst1.f32 {d24-d27}, [%2]! \n" "vst1.f32 {d28-d31}, [%3]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(bb2p0), // %4 "=r"(ktm0) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(bb2p0), "5"(ktm0), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else float sum0_0 = 0.f; float sum0_1 = 0.f; float sum0_2 = 0.f; float sum0_3 = 0.f; float sum0_4 = 0.f; float sum0_5 = 0.f; float sum0_6 = 0.f; float sum0_7 = 0.f; float sum1_0 = 0.f; float sum1_1 = 0.f; float sum1_2 = 0.f; float sum1_3 = 0.f; float sum1_4 = 0.f; float sum1_5 = 0.f; float sum1_6 = 0.f; float sum1_7 = 0.f; float sum2_0 = 0.f; float sum2_1 = 0.f; float sum2_2 = 0.f; float sum2_3 = 0.f; float sum2_4 = 0.f; float sum2_5 = 0.f; float sum2_6 = 0.f; float sum2_7 = 0.f; float sum3_0 = 0.f; float sum3_1 = 0.f; float sum3_2 = 0.f; float sum3_3 = 0.f; float sum3_4 = 0.f; float sum3_5 = 0.f; float sum3_6 = 0.f; float sum3_7 = 0.f; for (int q = 0; q < inch; q++) { sum0_0 += bb2p0[0] * ktm0[0]; sum0_1 += bb2p0[1] * ktm0[0]; sum0_2 += bb2p0[2] * ktm0[0]; sum0_3 += bb2p0[3] * ktm0[0]; sum0_4 += bb2p0[4] * ktm0[0]; sum0_5 += bb2p0[5] * ktm0[0]; sum0_6 += bb2p0[6] * ktm0[0]; sum0_7 += bb2p0[7] * ktm0[0]; sum1_0 += bb2p0[0] * ktm0[1]; sum1_1 += bb2p0[1] * ktm0[1]; sum1_2 += bb2p0[2] * ktm0[1]; sum1_3 += bb2p0[3] * ktm0[1]; sum1_4 += bb2p0[4] * ktm0[1]; sum1_5 += bb2p0[5] * ktm0[1]; sum1_6 += bb2p0[6] * ktm0[1]; sum1_7 += bb2p0[7] * ktm0[1]; sum2_0 += bb2p0[0] * ktm0[2]; sum2_1 += bb2p0[1] * ktm0[2]; sum2_2 += bb2p0[2] * ktm0[2]; sum2_3 += bb2p0[3] * ktm0[2]; sum2_4 += bb2p0[4] * ktm0[2]; sum2_5 += bb2p0[5] * ktm0[2]; sum2_6 += bb2p0[6] * ktm0[2]; sum2_7 += bb2p0[7] * ktm0[2]; sum3_0 += bb2p0[0] * ktm0[3]; sum3_1 += bb2p0[1] * ktm0[3]; sum3_2 += bb2p0[2] * ktm0[3]; sum3_3 += bb2p0[3] * ktm0[3]; sum3_4 += bb2p0[4] * ktm0[3]; sum3_5 += bb2p0[5] * ktm0[3]; sum3_6 += bb2p0[6] * ktm0[3]; sum3_7 += bb2p0[7] * ktm0[3]; bb2p0 += 8; ktm0 += 4; } output0_tm[0] = sum0_0; output0_tm[1] = sum0_1; output0_tm[2] = sum0_2; output0_tm[3] = sum0_3; output0_tm[4] = sum0_4; output0_tm[5] = sum0_5; output0_tm[6] = sum0_6; output0_tm[7] = sum0_7; output1_tm[0] = sum1_0; output1_tm[1] = sum1_1; output1_tm[2] = sum1_2; output1_tm[3] = sum1_3; output1_tm[4] = sum1_4; output1_tm[5] = sum1_5; output1_tm[6] = sum1_6; output1_tm[7] = sum1_7; output2_tm[0] = sum2_0; output2_tm[1] = sum2_1; output2_tm[2] = sum2_2; output2_tm[3] = sum2_3; output2_tm[4] = sum2_4; output2_tm[5] = sum2_5; output2_tm[6] = sum2_6; output2_tm[7] = sum2_7; output3_tm[0] = sum3_0; output3_tm[1] = sum3_1; output3_tm[2] = sum3_2; output3_tm[3] = sum3_3; output3_tm[4] = sum3_4; output3_tm[5] = sum3_5; output3_tm[6] = sum3_6; output3_tm[7] = sum3_7; output0_tm += 8; output1_tm += 8; output2_tm += 8; output3_tm += 8; #endif // __ARM_NEON } for (; i + 3 < tiles; i += 4) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4); const float* ktm0 = kernel_tm0.row(r); #if __ARM_NEON #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" // inch loop "lsr w4, %w12, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v8.4s, v5.4s, v1.s[0] \n" "fmla v9.4s, v5.4s, v1.s[1] \n" "fmla v10.4s, v5.4s, v1.s[2] \n" "fmla v11.4s, v5.4s, v1.s[3] \n" "fmla v8.4s, v6.4s, v2.s[0] \n" "fmla v9.4s, v6.4s, v2.s[1] \n" "fmla v10.4s, v6.4s, v2.s[2] \n" "fmla v11.4s, v6.4s, v2.s[3] \n" "fmla v8.4s, v7.4s, v3.s[0] \n" "fmla v9.4s, v7.4s, v3.s[1] \n" "fmla v10.4s, v7.4s, v3.s[2] \n" "fmla v11.4s, v7.4s, v3.s[3] \n" "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w12, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v4.4s}, [%4], #16 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v8.4s}, [%0], #16 \n" "st1 {v9.4s}, [%1], #16 \n" "st1 {v10.4s}, [%2], #16 \n" "st1 {v11.4s}, [%3], #16 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(bb2p0), // %4 "=r"(ktm0) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(bb2p0), "5"(ktm0), "r"(inch) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"); #else // __aarch64__ asm volatile( "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "veor q10, q10, q10 \n" "veor q11, q11, q11 \n" // inch loop "lsr r4, %12, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" // "vld1.f32 {d0-d3}, [%5 :128]! \n" // "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "vmla.f32 q8, q5, d2[0] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q10, q5, d3[0] \n" "vmla.f32 q11, q5, d3[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q6, d4[0] \n" "vmla.f32 q9, q6, d4[1] \n" "vmla.f32 q10, q6, d5[0] \n" "vmla.f32 q11, q6, d5[1] \n" "vmla.f32 q8, q7, d6[0] \n" "vmla.f32 q9, q7, d6[1] \n" "vmla.f32 q10, q7, d7[0] \n" "vmla.f32 q11, q7, d7[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %12, #3 \n" // r4 = remain = tiles & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #128] \n" "vld1.f32 {d8-d9}, [%4 :128]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d17}, [%0]! \n" "vst1.f32 {d18-d19}, [%1]! \n" "vst1.f32 {d20-d21}, [%2]! \n" "vst1.f32 {d22-d23}, [%3]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(bb2p0), // %4 "=r"(ktm0) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(bb2p0), "5"(ktm0), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"); #endif // __aarch64__ #else float sum0_0 = 0.f; float sum0_1 = 0.f; float sum0_2 = 0.f; float sum0_3 = 0.f; float sum1_0 = 0.f; float sum1_1 = 0.f; float sum1_2 = 0.f; float sum1_3 = 0.f; float sum2_0 = 0.f; float sum2_1 = 0.f; float sum2_2 = 0.f; float sum2_3 = 0.f; float sum3_0 = 0.f; float sum3_1 = 0.f; float sum3_2 = 0.f; float sum3_3 = 0.f; for (int q = 0; q < inch; q++) { sum0_0 += bb2p0[0] * ktm0[0]; sum0_1 += bb2p0[1] * ktm0[0]; sum0_2 += bb2p0[2] * ktm0[0]; sum0_3 += bb2p0[3] * ktm0[0]; sum1_0 += bb2p0[0] * ktm0[1]; sum1_1 += bb2p0[1] * ktm0[1]; sum1_2 += bb2p0[2] * ktm0[1]; sum1_3 += bb2p0[3] * ktm0[1]; sum2_0 += bb2p0[0] * ktm0[2]; sum2_1 += bb2p0[1] * ktm0[2]; sum2_2 += bb2p0[2] * ktm0[2]; sum2_3 += bb2p0[3] * ktm0[2]; sum3_0 += bb2p0[0] * ktm0[3]; sum3_1 += bb2p0[1] * ktm0[3]; sum3_2 += bb2p0[2] * ktm0[3]; sum3_3 += bb2p0[3] * ktm0[3]; bb2p0 += 4; ktm0 += 4; } output0_tm[0] = sum0_0; output0_tm[1] = sum0_1; output0_tm[2] = sum0_2; output0_tm[3] = sum0_3; output1_tm[0] = sum1_0; output1_tm[1] = sum1_1; output1_tm[2] = sum1_2; output1_tm[3] = sum1_3; output2_tm[0] = sum2_0; output2_tm[1] = sum2_1; output2_tm[2] = sum2_2; output2_tm[3] = sum2_3; output3_tm[0] = sum3_0; output3_tm[1] = sum3_1; output3_tm[2] = sum3_2; output3_tm[3] = sum3_3; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; #endif // __ARM_NEON } for (; i < tiles; i++) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); const float* ktm0 = kernel_tm0.row(r); #if __ARM_NEON float32x4_t _sum0123 = vdupq_n_f32(0.f); int q = 0; for (; q + 3 < inch; q += 4) { // asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :); float32x4_t _bb2p0 = vld1q_f32(bb2p0); bb2p0 += 4; // asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :); float32x4_t _ktm0 = vld1q_f32(ktm0 + 0); float32x4_t _ktm1 = vld1q_f32(ktm0 + 4); float32x4_t _ktm2 = vld1q_f32(ktm0 + 8); float32x4_t _ktm3 = vld1q_f32(ktm0 + 12); ktm0 += 16; #if __aarch64__ _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm0, _bb2p0, 0); _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm1, _bb2p0, 1); _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm2, _bb2p0, 2); _sum0123 = vmlaq_laneq_f32(_sum0123, _ktm3, _bb2p0, 3); #else _sum0123 = vmlaq_lane_f32(_sum0123, _ktm0, vget_low_f32(_bb2p0), 0); _sum0123 = vmlaq_lane_f32(_sum0123, _ktm1, vget_low_f32(_bb2p0), 1); _sum0123 = vmlaq_lane_f32(_sum0123, _ktm2, vget_high_f32(_bb2p0), 0); _sum0123 = vmlaq_lane_f32(_sum0123, _ktm3, vget_high_f32(_bb2p0), 1); #endif // __aarch64__ } for (; q < inch; q++) { float32x4_t _bb2p0 = vld1q_dup_f32(bb2p0); float32x4_t _ktm0 = vld1q_f32(ktm0); _sum0123 = vmlaq_f32(_sum0123, _bb2p0, _ktm0); bb2p0 += 1; ktm0 += 4; } float sum0 = vgetq_lane_f32(_sum0123, 0); float sum1 = vgetq_lane_f32(_sum0123, 1); float sum2 = vgetq_lane_f32(_sum0123, 2); float sum3 = vgetq_lane_f32(_sum0123, 3); #else float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; for (int q = 0; q < inch; q++) { sum0 += bb2p0[0] * ktm0[0]; sum1 += bb2p0[0] * ktm0[1]; sum2 += bb2p0[0] * ktm0[2]; sum3 += bb2p0[0] * ktm0[3]; bb2p0 += 1; ktm0 += 4; } #endif // __ARM_NEON output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output0_tm += 1; output1_tm += 1; output2_tm += 1; output3_tm += 1; } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { #if __ARM_NEON && __aarch64__ const Mat kernel_tm0 = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4); #else const Mat kernel_tm0 = kernel_tm.channel(p / 4 + p % 4); #endif Mat out0_tm = top_blob_tm.channel(p); float* output0_tm = out0_tm; for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { const float* bb2p0 = bb2.row(i / 8); const float* ktm0 = kernel_tm0.row(r); #if __ARM_NEON #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" // inch loop "lsr w4, %w6, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.4s}, [%2], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "fmla v8.4s, v6.4s, v0.s[1] \n" "fmla v9.4s, v7.4s, v0.s[1] \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "fmla v8.4s, v12.4s, v0.s[2] \n" "fmla v9.4s, v13.4s, v0.s[2] \n" "fmla v8.4s, v14.4s, v0.s[3] \n" "fmla v9.4s, v15.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w6, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v4.4s, v5.4s}, [%1], #32 \n" "prfm pldl1keep, [%2, #32] \n" "ld1r {v0.4s}, [%2], #4 \n" "fmla v8.4s, v4.4s, v0.4s \n" "fmla v9.4s, v5.4s, v0.4s \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v8.4s, v9.4s}, [%0], #32 \n" : "=r"(output0_tm), // %0 "=r"(bb2p0), // %1 "=r"(ktm0) // %2 : "0"(output0_tm), "1"(bb2p0), "2"(ktm0), "r"(inch) // %6 : "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v12", "v13", "v14", "v15"); #else // __aarch64__ asm volatile( "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" // inch loop "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%1, #512] \n" "vldm %1!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%1 :128]! \n" // "vld1.f32 {d12-d15}, [%1 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d0-d1}, [%2 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q5, d0[0] \n" "vmla.f32 q8, q6, d0[1] \n" "vmla.f32 q9, q7, d0[1] \n" "pld [%1, #512] \n" "vldm %1!, {d24-d31} \n" // "vld1.f32 {d24-d27}, [%1 :128]! \n" // "vld1.f32 {d28-d31}, [%1 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q12, d1[0] \n" "vmla.f32 q9, q13, d1[0] \n" "vmla.f32 q8, q14, d1[1] \n" "vmla.f32 q9, q15, d1[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = tiles & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%1, #256] \n" "vld1.f32 {d8-d11}, [%1 :128]! \n" "pld [%2, #32] \n" "vld1.f32 {d0[],d1[]}, [%2]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, q0 \n" "vmla.f32 q9, q5, q0 \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d19}, [%0]! \n" : "=r"(output0_tm), // %0 "=r"(bb2p0), // %1 "=r"(ktm0) // %2 : "0"(output0_tm), "1"(bb2p0), "2"(ktm0), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; float sum4 = 0.f; float sum5 = 0.f; float sum6 = 0.f; float sum7 = 0.f; for (int q = 0; q < inch; q++) { sum0 += bb2p0[0] * ktm0[0]; sum1 += bb2p0[1] * ktm0[0]; sum2 += bb2p0[2] * ktm0[0]; sum3 += bb2p0[3] * ktm0[0]; sum4 += bb2p0[4] * ktm0[0]; sum5 += bb2p0[5] * ktm0[0]; sum6 += bb2p0[6] * ktm0[0]; sum7 += bb2p0[7] * ktm0[0]; bb2p0 += 8; ktm0 += 1; } output0_tm[0] = sum0; output0_tm[1] = sum1; output0_tm[2] = sum2; output0_tm[3] = sum3; output0_tm[4] = sum4; output0_tm[5] = sum5; output0_tm[6] = sum6; output0_tm[7] = sum7; output0_tm += 8; #endif // __ARM_NEON } for (; i + 3 < tiles; i += 4) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4); const float* ktm0 = kernel_tm0.row(r); #if __ARM_NEON #if __aarch64__ asm volatile( "eor v8.16b, v8.16b, v8.16b \n" // inch loop "lsr w4, %w6, #2 \n" // w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v8.4s, v5.4s, v0.s[1] \n" "fmla v8.4s, v6.4s, v0.s[2] \n" "fmla v8.4s, v7.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w6, #3 \n" // w4 = remain = tiles & 3 "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v4.4s}, [%4], #16 \n" "prfm pldl1keep, [%5, #32] \n" "ld1r {v0.4s}, [%5], #4 \n" "fmla v8.4s, v4.4s, v0.4s \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v8.4s}, [%0], #16 \n" : "=r"(output0_tm), // %0 "=r"(bb2p0), // %1 "=r"(ktm0) // %2 : "0"(output0_tm), "1"(bb2p0), "2"(ktm0), "r"(inch) // %6 : "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8"); #else // __aarch64__ asm volatile( "veor q8, q8, q8 \n" // inch loop "lsr r4, %6, #2 \n" // r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q8, q7, d1[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %6, #3 \n" // r4 = remain = tiles & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #128] \n" "vld1.f32 {d8-d9}, [%4]! \n" "pld [%5, #32] \n" "vld1.f32 {d0[],d1[]}, [%5]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, q0 \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d17}, [%0]! \n" : "=r"(output0_tm), // %0 "=r"(bb2p0), // %1 "=r"(ktm0) // %2 : "0"(output0_tm), "1"(bb2p0), "2"(ktm0), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8"); #endif // __aarch64__ #else float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; for (int q = 0; q < inch; q++) { sum0 += bb2p0[0] * ktm0[0]; sum1 += bb2p0[1] * ktm0[0]; sum2 += bb2p0[2] * ktm0[0]; sum3 += bb2p0[3] * ktm0[0]; bb2p0 += 4; ktm0 += 1; } output0_tm[0] = sum0; output0_tm[1] = sum1; output0_tm[2] = sum2; output0_tm[3] = sum3; output0_tm += 4; #endif // __ARM_NEON } for (; i < tiles; i++) { const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); const float* ktm0 = kernel_tm0.row(r); int q = 0; #if __ARM_NEON float32x4_t _sum0 = vdupq_n_f32(0.f); for (; q + 3 < inch; q += 4) { // asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :); float32x4_t _bb2p0 = vld1q_f32(bb2p0); bb2p0 += 4; float32x4_t _ktm0 = vld1q_f32(ktm0); ktm0 += 4; _sum0 = vmlaq_f32(_sum0, _bb2p0, _ktm0); } #if __aarch64__ float sum0 = vaddvq_f32(_sum0); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float sum0 = vget_lane_f32(vpadd_f32(_ss0, _ss0), 0); #endif // __aarch64__ #else float sum0 = 0.f; #endif for (; q < inch; q++) { sum0 += bb2p0[0] * ktm0[0]; bb2p0 += 1; ktm0 += 1; } output0_tm[0] = sum0; output0_tm += 1; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); } { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) #if __ARM_NEON const float coeff[4] = {4.f, 8.f, 16.f, 32.f}; float32x4_t _coeff = vld1q_f32(coeff); #endif // __ARM_NEON int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; #if __ARM_NEON float32x2_t _bias0 = vdup_n_f32(bias0); #endif // __ARM_NEON float tmp[6][8]; // tile for (int i = 0; i < outh / 6; i++) { for (int j = 0; j < outw / 6; j++) { #if __ARM_NEON #if __aarch64__ const float* output0_tm0 = out0_tm.row(i * w_tm / 8 + j); const float* output0_tm1 = out0_tm.row(i * w_tm / 8 + j + tiles * 8); const float* output0_tm2 = out0_tm.row(i * w_tm / 8 + j + tiles * 16); const float* output0_tm3 = out0_tm.row(i * w_tm / 8 + j + tiles * 24); for (int m = 0; m + 3 < 8; m += 4) { float32x4_t _output0_tm_00 = {}; float32x4_t _output0_tm_11 = {}; float32x4_t _output0_tm_22 = {}; float32x4_t _output0_tm_33 = {}; float32x4_t _output0_tm_44 = {}; float32x4_t _output0_tm_55 = {}; float32x4_t _output0_tm_66 = {}; float32x4_t _output0_tm_77 = {}; _output0_tm_00 = vsetq_lane_f32(output0_tm0[0], _output0_tm_00, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_00 = vsetq_lane_f32(output0_tm1[0], _output0_tm_00, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_00 = vsetq_lane_f32(output0_tm2[0], _output0_tm_00, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_00 = vsetq_lane_f32(output0_tm3[0], _output0_tm_00, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_11 = vsetq_lane_f32(output0_tm0[0], _output0_tm_11, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_11 = vsetq_lane_f32(output0_tm1[0], _output0_tm_11, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_11 = vsetq_lane_f32(output0_tm2[0], _output0_tm_11, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_11 = vsetq_lane_f32(output0_tm3[0], _output0_tm_11, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_22 = vsetq_lane_f32(output0_tm0[0], _output0_tm_22, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_22 = vsetq_lane_f32(output0_tm1[0], _output0_tm_22, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_22 = vsetq_lane_f32(output0_tm2[0], _output0_tm_22, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_22 = vsetq_lane_f32(output0_tm3[0], _output0_tm_22, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_33 = vsetq_lane_f32(output0_tm0[0], _output0_tm_33, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_33 = vsetq_lane_f32(output0_tm1[0], _output0_tm_33, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_33 = vsetq_lane_f32(output0_tm2[0], _output0_tm_33, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_33 = vsetq_lane_f32(output0_tm3[0], _output0_tm_33, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_44 = vsetq_lane_f32(output0_tm0[0], _output0_tm_44, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_44 = vsetq_lane_f32(output0_tm1[0], _output0_tm_44, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_44 = vsetq_lane_f32(output0_tm2[0], _output0_tm_44, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_44 = vsetq_lane_f32(output0_tm3[0], _output0_tm_44, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_55 = vsetq_lane_f32(output0_tm0[0], _output0_tm_55, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_55 = vsetq_lane_f32(output0_tm1[0], _output0_tm_55, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_55 = vsetq_lane_f32(output0_tm2[0], _output0_tm_55, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_55 = vsetq_lane_f32(output0_tm3[0], _output0_tm_55, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_66 = vsetq_lane_f32(output0_tm0[0], _output0_tm_66, 0); output0_tm0 += out0_tm.w * tiles; _output0_tm_66 = vsetq_lane_f32(output0_tm1[0], _output0_tm_66, 1); output0_tm1 += out0_tm.w * tiles; _output0_tm_66 = vsetq_lane_f32(output0_tm2[0], _output0_tm_66, 2); output0_tm2 += out0_tm.w * tiles; _output0_tm_66 = vsetq_lane_f32(output0_tm3[0], _output0_tm_66, 3); output0_tm3 += out0_tm.w * tiles; _output0_tm_77 = vsetq_lane_f32(output0_tm0[0], _output0_tm_77, 0); _output0_tm_77 = vsetq_lane_f32(output0_tm1[0], _output0_tm_77, 1); _output0_tm_77 = vsetq_lane_f32(output0_tm2[0], _output0_tm_77, 2); _output0_tm_77 = vsetq_lane_f32(output0_tm3[0], _output0_tm_77, 3); float32x4_t _tmp024a = vaddq_f32(_output0_tm_11, _output0_tm_22); float32x4_t _tmp135a = vsubq_f32(_output0_tm_11, _output0_tm_22); float32x4_t _tmp024b = vaddq_f32(_output0_tm_33, _output0_tm_44); float32x4_t _tmp135b = vsubq_f32(_output0_tm_33, _output0_tm_44); float32x4_t _tmp024c = vaddq_f32(_output0_tm_55, _output0_tm_66); float32x4_t _tmp135c = vsubq_f32(_output0_tm_55, _output0_tm_66); float32x4_t _tmp0 = vaddq_f32(_output0_tm_00, _tmp024a); _tmp0 = vmlaq_lane_f32(_tmp0, _tmp024c, vget_high_f32(_coeff), 1); _tmp0 = vaddq_f32(_tmp0, _tmp024b); float32x4_t _tmp2 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0); _tmp2 = vmlaq_lane_f32(_tmp2, _tmp024c, vget_low_f32(_coeff), 1); float32x4_t _tmp4 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0); _tmp4 = vaddq_f32(_tmp4, _tmp024c); _tmp4 = vaddq_f32(_tmp4, _tmp024c); vst1q_f32(&tmp[0][m], _tmp0); vst1q_f32(&tmp[2][m], _tmp2); vst1q_f32(&tmp[4][m], _tmp4); float32x4_t _tmp1 = vmlaq_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0); _tmp1 = vaddq_f32(_tmp1, _tmp135b); _tmp1 = vaddq_f32(_tmp1, _tmp135b); float32x4_t _tmp3 = vmlaq_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1); _tmp3 = vmlaq_lane_f32(_tmp3, _tmp135c, vget_low_f32(_coeff), 0); float32x4_t _tmp5 = vaddq_f32(_output0_tm_77, _tmp135a); _tmp5 = vmlaq_lane_f32(_tmp5, _tmp135b, vget_high_f32(_coeff), 1); _tmp5 = vaddq_f32(_tmp5, _tmp135c); vst1q_f32(&tmp[1][m], _tmp1); vst1q_f32(&tmp[3][m], _tmp3); vst1q_f32(&tmp[5][m], _tmp5); output0_tm0 += out0_tm.w * tiles * 25; output0_tm1 += out0_tm.w * tiles * 25; output0_tm2 += out0_tm.w * tiles * 25; output0_tm3 += out0_tm.w * tiles * 25; } const float* t0 = tmp[0]; const float* t1 = tmp[1]; float* output0 = out0.row(i * 6) + j * 6; float* output1 = output0 + outw; for (int m = 0; m + 1 < 6; m += 2) { float32x4_t _t0_0123 = vld1q_f32(t0); float32x4_t _t0_4567 = vld1q_f32(t0 + 4); float32x4_t _t1_0123 = vld1q_f32(t1); float32x4_t _t1_4567 = vld1q_f32(t1 + 4); float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123); float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567); float32x2_t _t_00 = vget_low_f32(_t01_00221133.val[0]); float32x2_t _t_11 = vget_low_f32(_t01_00221133.val[1]); float32x2_t _t_22 = vget_high_f32(_t01_00221133.val[0]); float32x2_t _t_33 = vget_high_f32(_t01_00221133.val[1]); float32x2_t _t_44 = vget_low_f32(_t01_44665577.val[0]); float32x2_t _t_55 = vget_low_f32(_t01_44665577.val[1]); float32x2_t _t_66 = vget_high_f32(_t01_44665577.val[0]); float32x2_t _t_77 = vget_high_f32(_t01_44665577.val[1]); float32x2_t _tmp024a = vadd_f32(_t_11, _t_22); float32x2_t _tmp135a = vsub_f32(_t_11, _t_22); float32x2_t _tmp024b = vadd_f32(_t_33, _t_44); float32x2_t _tmp135b = vsub_f32(_t_33, _t_44); float32x2_t _tmp024c = vadd_f32(_t_55, _t_66); float32x2_t _tmp135c = vsub_f32(_t_55, _t_66); float32x2_t _output_0 = vadd_f32(_t_00, _tmp024a); _output_0 = vmla_lane_f32(_output_0, _tmp024c, vget_high_f32(_coeff), 1); _output_0 = vadd_f32(_output_0, _tmp024b); _output_0 = vadd_f32(_output_0, _bias0); float32x2_t _output_2 = vmla_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0); _output_2 = vmla_lane_f32(_output_2, _tmp024c, vget_low_f32(_coeff), 1); _output_2 = vadd_f32(_output_2, _bias0); float32x2_t _output_4 = vmla_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0); _output_4 = vadd_f32(_output_4, _tmp024c); _output_4 = vadd_f32(_output_4, _tmp024c); _output_4 = vadd_f32(_output_4, _bias0); output0[0] = vget_lane_f32(_output_0, 0); output1[0] = vget_lane_f32(_output_0, 1); output0[2] = vget_lane_f32(_output_2, 0); output1[2] = vget_lane_f32(_output_2, 1); output0[4] = vget_lane_f32(_output_4, 0); output1[4] = vget_lane_f32(_output_4, 1); float32x2_t _output_1 = vmla_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0); _output_1 = vadd_f32(_output_1, _tmp135b); _output_1 = vadd_f32(_output_1, _tmp135b); _output_1 = vadd_f32(_output_1, _bias0); float32x2_t _output_3 = vmla_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1); _output_3 = vmla_lane_f32(_output_3, _tmp135c, vget_low_f32(_coeff), 0); _output_3 = vadd_f32(_output_3, _bias0); float32x2_t _output_5 = vadd_f32(_t_77, _tmp135a); _output_5 = vmla_lane_f32(_output_5, _tmp135b, vget_high_f32(_coeff), 1); _output_5 = vadd_f32(_output_5, _tmp135c); _output_5 = vadd_f32(_output_5, _bias0); output0[1] = vget_lane_f32(_output_1, 0); output1[1] = vget_lane_f32(_output_1, 1); output0[3] = vget_lane_f32(_output_3, 0); output1[3] = vget_lane_f32(_output_3, 1); output0[5] = vget_lane_f32(_output_5, 0); output1[5] = vget_lane_f32(_output_5, 1); t0 += 8 * 2; t1 += 8 * 2; output0 += outw * 2; output1 += outw * 2; } #else // __aarch64__ const float* output0_tm0_0 = out0_tm.row(i * w_tm / 8 + j); const float* output0_tm1_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 8); const float* output0_tm2_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 16); const float* output0_tm3_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 24); float* t0 = tmp[0]; float* t1 = tmp[1]; int step = out0_tm.w * tiles * 4; int step2 = out0_tm.w * tiles * 25 * 4; asm volatile( // loop0 "vld1.f32 {d16[0]}, [%2], %13 \n" "vld1.f32 {d16[1]}, [%3], %13 \n" "vld1.f32 {d17[0]}, [%4], %13 \n" "vld1.f32 {d17[1]}, [%5], %13 \n" "vld1.f32 {d20[0]}, [%2], %13 \n" "vld1.f32 {d20[1]}, [%3], %13 \n" "vld1.f32 {d21[0]}, [%4], %13 \n" "vld1.f32 {d21[1]}, [%5], %13 \n" "vld1.f32 {d24[0]}, [%2], %13 \n" "vld1.f32 {d24[1]}, [%3], %13 \n" "vld1.f32 {d25[0]}, [%4], %13 \n" "vld1.f32 {d25[1]}, [%5], %13 \n" "vadd.f32 q2, q10, q12 \n" "vsub.f32 q3, q10, q12 \n" "vld1.f32 {d28[0]}, [%2], %13 \n" "vld1.f32 {d28[1]}, [%3], %13 \n" "vld1.f32 {d29[0]}, [%4], %13 \n" "vld1.f32 {d29[1]}, [%5], %13 \n" "vld1.f32 {d18[0]}, [%2], %13 \n" "vld1.f32 {d18[1]}, [%3], %13 \n" "vld1.f32 {d19[0]}, [%4], %13 \n" "vld1.f32 {d19[1]}, [%5], %13 \n" "vadd.f32 q4, q14, q9 \n" "vsub.f32 q5, q14, q9 \n" "vld1.f32 {d22[0]}, [%2], %13 \n" "vld1.f32 {d22[1]}, [%3], %13 \n" "vld1.f32 {d23[0]}, [%4], %13 \n" "vld1.f32 {d23[1]}, [%5], %13 \n" "vld1.f32 {d26[0]}, [%2], %13 \n" "vld1.f32 {d26[1]}, [%3], %13 \n" "vld1.f32 {d27[0]}, [%4], %13 \n" "vld1.f32 {d27[1]}, [%5], %13 \n" "vadd.f32 q6, q11, q13 \n" "vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14 "vld1.f32 {d30[0]}, [%2], %14 \n" "vld1.f32 {d30[1]}, [%3], %14 \n" "vld1.f32 {d31[0]}, [%4], %14 \n" "vld1.f32 {d31[1]}, [%5], %14 \n" "vmov q9, q3 \n" "vadd.f32 q8, q8, q2 \n" "vmla.f32 q9, q7, %f12[0] \n" "vmov q12, q2 \n" "vmov q10, q2 \n" "vmov q11, q3 \n" "vmla.f32 q12, q4, %f12[0] \n" "vadd.f32 q15, q15, q3 \n" "vmla.f32 q8, q6, %f12[1] \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q4, %e12[0] \n" "vmla.f32 q11, q5, %e12[1] \n" "vadd.f32 q12, q12, q6 \n" "vmla.f32 q15, q5, %f12[1] \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q6, %e12[1] \n" "vmla.f32 q11, q7, %e12[0] \n" "vadd.f32 q12, q12, q6 \n" "vadd.f32 q15, q15, q7 \n" "vst1.f32 {d16-d17}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d18-d19}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d20-d21}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d22-d23}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d24-d25}, [%0] \n" "sub %0, %0, #112 \n" "vst1.f32 {d30-d31}, [%1] \n" "sub %1, %1, #112 \n" // loop1 "vld1.f32 {d16[0]}, [%2], %13 \n" "vld1.f32 {d16[1]}, [%3], %13 \n" "vld1.f32 {d17[0]}, [%4], %13 \n" "vld1.f32 {d17[1]}, [%5], %13 \n" "vld1.f32 {d20[0]}, [%2], %13 \n" "vld1.f32 {d20[1]}, [%3], %13 \n" "vld1.f32 {d21[0]}, [%4], %13 \n" "vld1.f32 {d21[1]}, [%5], %13 \n" "vld1.f32 {d24[0]}, [%2], %13 \n" "vld1.f32 {d24[1]}, [%3], %13 \n" "vld1.f32 {d25[0]}, [%4], %13 \n" "vld1.f32 {d25[1]}, [%5], %13 \n" "vadd.f32 q2, q10, q12 \n" "vsub.f32 q3, q10, q12 \n" "vld1.f32 {d28[0]}, [%2], %13 \n" "vld1.f32 {d28[1]}, [%3], %13 \n" "vld1.f32 {d29[0]}, [%4], %13 \n" "vld1.f32 {d29[1]}, [%5], %13 \n" "vld1.f32 {d18[0]}, [%2], %13 \n" "vld1.f32 {d18[1]}, [%3], %13 \n" "vld1.f32 {d19[0]}, [%4], %13 \n" "vld1.f32 {d19[1]}, [%5], %13 \n" "vadd.f32 q4, q14, q9 \n" "vsub.f32 q5, q14, q9 \n" "vld1.f32 {d22[0]}, [%2], %13 \n" "vld1.f32 {d22[1]}, [%3], %13 \n" "vld1.f32 {d23[0]}, [%4], %13 \n" "vld1.f32 {d23[1]}, [%5], %13 \n" "vld1.f32 {d26[0]}, [%2], %13 \n" "vld1.f32 {d26[1]}, [%3], %13 \n" "vld1.f32 {d27[0]}, [%4], %13 \n" "vld1.f32 {d27[1]}, [%5], %13 \n" "vadd.f32 q6, q11, q13 \n" "vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14 "vld1.f32 {d30[0]}, [%2] \n" "vld1.f32 {d30[1]}, [%3] \n" "vld1.f32 {d31[0]}, [%4] \n" "vld1.f32 {d31[1]}, [%5] \n" "vmov q9, q3 \n" "vadd.f32 q8, q8, q2 \n" "vmla.f32 q9, q7, %f12[0] \n" "vmov q12, q2 \n" "vmov q10, q2 \n" "vmov q11, q3 \n" "vmla.f32 q12, q4, %f12[0] \n" "vadd.f32 q15, q15, q3 \n" "vmla.f32 q8, q6, %f12[1] \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q4, %e12[0] \n" "vmla.f32 q11, q5, %e12[1] \n" "vadd.f32 q12, q12, q6 \n" "vmla.f32 q15, q5, %f12[1] \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" "vmla.f32 q10, q6, %e12[1] \n" "vmla.f32 q11, q7, %e12[0] \n" "vadd.f32 q12, q12, q6 \n" "vadd.f32 q15, q15, q7 \n" "vst1.f32 {d16-d17}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d18-d19}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d20-d21}, [%0] \n" "add %0, %0, #64 \n" "vst1.f32 {d22-d23}, [%1] \n" "add %1, %1, #64 \n" "vst1.f32 {d24-d25}, [%0] \n" "vst1.f32 {d30-d31}, [%1] \n" : "=r"(t0), // %0 "=r"(t1), // %1 "=r"(output0_tm0_0), // %2 "=r"(output0_tm1_0), // %3 "=r"(output0_tm2_0), // %4 "=r"(output0_tm3_0) // %5 : "0"(t0), "1"(t1), "2"(output0_tm0_0), "3"(output0_tm1_0), "4"(output0_tm2_0), "5"(output0_tm3_0), "w"(_coeff), // %12 "r"(step), // %13 "r"(step2) // %14 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); t0 = tmp[0]; t1 = tmp[1]; float* output0 = out0.row(i * 6) + j * 6; float* output1 = output0 + outw; int stepw = outw * 2 * 4; asm volatile( // loop0 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" // loop1 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" // loop2 "vld1.f32 {d16-d19}, [%2] \n" "vld1.f32 {d20-d23}, [%3] \n" "add %2, %2, #64 \n" "add %3, %3, #64 \n" "vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3 "vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7 "vadd.f32 d4, d20, d17 \n" "vsub.f32 d5, d20, d17 \n" "vadd.f32 d6, d21, d18 \n" "vsub.f32 d7, d21, d18 \n" "vadd.f32 d8, d22, d19 \n" "vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22 "vmov d20, d5 \n" "vmov d18, d4 \n" "vadd.f32 d16, d16, d4 \n" "vmla.f32 d20, d9, %f8[0] \n" "vmov d17, d4 \n" "vmov d21, d5 \n" "vmla.f32 d18, d6, %f8[0] \n" "vadd.f32 d22, d23, d5 \n" "vmla.f32 d16, d8, %f8[1] \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d6, %e8[0] \n" "vmla.f32 d21, d7, %e8[1] \n" "vadd.f32 d18, d18, d8 \n" "vmla.f32 d22, d7, %f8[1] \n" "vadd.f32 d16, d16, d6 \n" "vadd.f32 d20, d20, d7 \n" "vmla.f32 d17, d8, %e8[1] \n" "vmla.f32 d21, d9, %e8[0] \n" "vadd.f32 d18, d18, d8 \n" "vadd.f32 d22, d22, d9 \n" "vadd.f32 d16, d16, %P9 \n" // _bias0 "vadd.f32 d20, d20, %P9 \n" // _bias0 "vadd.f32 d17, d17, %P9 \n" // _bias0 "vadd.f32 d21, d21, %P9 \n" // _bias0 "vadd.f32 d18, d18, %P9 \n" // _bias0 "vadd.f32 d22, d22, %P9 \n" // _bias0 "vtrn.f32 q8, q10 \n" "vtrn.f32 d18, d22 \n" "vst1.f32 {d16-d18}, [%0], %10 \n" "vst1.f32 {d20-d22}, [%1], %10 \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(t0), // %2 "=r"(t1) // %3 : "0"(output0), "1"(output1), "2"(t0), "3"(t1), "w"(_coeff), // %8 "w"(_bias0), // %9 "r"(stepw) // %10 : "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else const float* output0_tm_0 = out0_tm.row(i * w_tm / 8 + j); const float* output0_tm_1 = out0_tm.row(i * w_tm / 8 + j + tiles); const float* output0_tm_2 = out0_tm.row(i * w_tm / 8 + j + tiles * 2); const float* output0_tm_3 = out0_tm.row(i * w_tm / 8 + j + tiles * 3); const float* output0_tm_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 4); const float* output0_tm_5 = out0_tm.row(i * w_tm / 8 + j + tiles * 5); const float* output0_tm_6 = out0_tm.row(i * w_tm / 8 + j + tiles * 6); const float* output0_tm_7 = out0_tm.row(i * w_tm / 8 + j + tiles * 7); for (int m = 0; m < 8; m++) { float tmp024a = output0_tm_1[0] + output0_tm_2[0]; float tmp135a = output0_tm_1[0] - output0_tm_2[0]; float tmp024b = output0_tm_3[0] + output0_tm_4[0]; float tmp135b = output0_tm_3[0] - output0_tm_4[0]; float tmp024c = output0_tm_5[0] + output0_tm_6[0]; float tmp135c = output0_tm_5[0] - output0_tm_6[0]; tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm_7[0] + tmp135a + tmp135b * 32 + tmp135c; output0_tm_0 += out0_tm.w * tiles * 8; output0_tm_1 += out0_tm.w * tiles * 8; output0_tm_2 += out0_tm.w * tiles * 8; output0_tm_3 += out0_tm.w * tiles * 8; output0_tm_4 += out0_tm.w * tiles * 8; output0_tm_5 += out0_tm.w * tiles * 8; output0_tm_6 += out0_tm.w * tiles * 8; output0_tm_7 += out0_tm.w * tiles * 8; } float* output0 = out0.row(i * 6) + j * 6; for (int m = 0; m < 6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } #endif // __ARM_NEON } } } } // END transform output // cut result pad if (top_blob_bordered.w != top_blob.w || top_blob_bordered.h != top_blob.h) copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; out0.fill(bias0); out1.fill(bias1); const float* k0 = kernel + p * inch * 9; const float* k1 = kernel + (p + 1) * inch * 9; for (int q = 0; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; #if __ARM_NEON float32x4_t _k00 = vld1q_f32(k0); float32x4_t _k03 = vld1q_f32(k0 + 3); float32x4_t _k06 = vld1q_f32(k0 + 6); float32x4_t _k10 = vld1q_f32(k1); float32x4_t _k13 = vld1q_f32(k1 + 3); float32x4_t _k16 = vld1q_f32(k1 + 6); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%3, #256] \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" // v8 v9 = r0 "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v6.4s}, [%1] \n" // v6 = _sum0 "fmul v12.4s, v8.4s, %12.s[0] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v7.4s}, [%2] \n" // v7 = _sum1 "fmul v13.4s, v8.4s, %15.s[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld2 {v10.4s, v11.4s}, [%3] \n" // v10 "fmla v6.4s, v9.4s, %12.s[1] \n" "ext v14.16b, v8.16b, v10.16b, #4\n" "fmla v7.4s, v9.4s, %15.s[1] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" // r1 "fmla v12.4s, v14.4s, %12.s[2] \n" "fmla v13.4s, v14.4s, %15.s[2] \n" "prfm pldl1keep, [%4, #128] \n" "ld2 {v10.4s, v11.4s}, [%4] \n" "fmla v6.4s, v8.4s, %13.s[0] \n" "fmla v7.4s, v8.4s, %16.s[0] \n" "ext v14.16b, v8.16b, v10.16b, #4\n" "fmla v12.4s, v9.4s, %13.s[1] \n" "fmla v13.4s, v9.4s, %16.s[1] \n" "prfm pldl1keep, [%5, #256] \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" // r2 "fmla v6.4s, v14.4s, %13.s[2] \n" "fmla v7.4s, v14.4s, %16.s[2] \n" "prfm pldl1keep, [%5, #128] \n" "ld2 {v10.4s, v11.4s}, [%5] \n" "fmla v12.4s, v8.4s, %14.s[0] \n" "fmla v13.4s, v8.4s, %17.s[0] \n" "ext v14.16b, v8.16b, v10.16b, #4\n" "fmla v6.4s, v9.4s, %14.s[1] \n" "fmla v7.4s, v9.4s, %17.s[1] \n" "fmla v12.4s, v14.4s, %14.s[2] \n" "fmla v13.4s, v14.4s, %17.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" // v8 v9 = r0 "fadd v6.4s, v6.4s, v12.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "subs %w0, %w0, #1 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v7.4s}, [%2], #16 \n" "bne 0b \n" "sub %3, %3, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(r0), "4"(r1), "5"(r2), "w"(_k00), // %12 "w"(_k03), // %13 "w"(_k06), // %14 "w"(_k10), // %15 "w"(_k13), // %16 "w"(_k16) // %17 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%3, #256] \n" "vld2.f32 {d16-d19}, [%3]! \n" // q8 q9 = r0 "0: \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1] \n" // q6 = _sum0 "vmul.f32 q12, q8, %e12[0] \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2] \n" // q7 = _sum1 "vmul.f32 q13, q8, %e15[0] \n" "pld [%3, #128] \n" "vld2.f32 {d20-d21}, [%3] \n" // q10 "vmla.f32 q6, q9, %e12[1] \n" "vext.32 q11, q8, q10, #1 \n" "vmla.f32 q7, q9, %e15[1] \n" "pld [%4, #256] \n" "vld2.f32 {d16-d19}, [%4]! \n" // r1 "vmla.f32 q12, q11, %f12[0] \n" "vmla.f32 q13, q11, %f15[0] \n" "pld [%4, #128] \n" "vld2.f32 {d20-d21}, [%4] \n" "vmla.f32 q6, q8, %e13[0] \n" "vmla.f32 q7, q8, %e16[0] \n" "vext.32 q11, q8, q10, #1 \n" "vmla.f32 q12, q9, %e13[1] \n" "vmla.f32 q13, q9, %e16[1] \n" "pld [%5, #256] \n" "vld2.f32 {d16-d19}, [%5]! \n" // r2 "vmla.f32 q6, q11, %f13[0] \n" "vmla.f32 q7, q11, %f16[0] \n" "pld [%5, #128] \n" "vld2.f32 {d20-d21}, [%5] \n" "vmla.f32 q12, q8, %e14[0] \n" "vmla.f32 q13, q8, %e17[0] \n" "vext.32 q11, q8, q10, #1 \n" "vmla.f32 q6, q9, %e14[1] \n" "vmla.f32 q7, q9, %e17[1] \n" "vmla.f32 q12, q11, %f14[0] \n" "vmla.f32 q13, q11, %f17[0] \n" "pld [%3, #256] \n" "vld2.f32 {d16-d19}, [%3]! \n" // q8 q9 = r0 "vadd.f32 q6, q6, q12 \n" "vadd.f32 q7, q7, q13 \n" "subs %0, #1 \n" "vst1.f32 {d12-d13}, [%1]! \n" "vst1.f32 {d14-d15}, [%2]! \n" "bne 0b \n" "sub %3, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(r0), "4"(r1), "5"(r2), "w"(_k00), // %12 "w"(_k03), // %13 "w"(_k06), // %14 "w"(_k10), // %15 "w"(_k13), // %16 "w"(_k16) // %17 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum0 = vmulq_f32(_r00, _k00); float32x4_t _sum1 = vmulq_f32(_r00, _k10); _sum0 = vmlaq_f32(_sum0, _r10, _k03); _sum1 = vmlaq_f32(_sum1, _r10, _k13); _sum0 = vmlaq_f32(_sum0, _r20, _k06); _sum1 = vmlaq_f32(_sum1, _r20, _k16); _sum0 = vsetq_lane_f32(*outptr0, _sum0, 3); _sum1 = vsetq_lane_f32(*outptr1, _sum1, 3); #if __aarch64__ *outptr0 = vaddvq_f32(_sum0); *outptr1 = vaddvq_f32(_sum1); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1)); float32x2_t _ss01 = vpadd_f32(_ss0, _ss1); *outptr0 = vget_lane_f32(_ss01, 0); *outptr1 = vget_lane_f32(_ss01, 1); #endif // __aarch64__ #else float sum0 = 0.f; float sum1 = 0.f; sum0 += r0[0] * k0[0]; sum0 += r0[1] * k0[1]; sum0 += r0[2] * k0[2]; sum0 += r1[0] * k0[3]; sum0 += r1[1] * k0[4]; sum0 += r1[2] * k0[5]; sum0 += r2[0] * k0[6]; sum0 += r2[1] * k0[7]; sum0 += r2[2] * k0[8]; sum1 += r0[0] * k1[0]; sum1 += r0[1] * k1[1]; sum1 += r0[2] * k1[2]; sum1 += r1[0] * k1[3]; sum1 += r1[1] * k1[4]; sum1 += r1[2] * k1[5]; sum1 += r2[0] * k1[6]; sum1 += r2[1] * k1[7]; sum1 += r2[2] * k1[8]; *outptr0 += sum0; *outptr1 += sum1; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr0++; outptr1++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } k0 += 9; k1 += 9; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p * inch * 9; for (int q = 0; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.4s}, [%1] \n" "fmla v0.4s, v2.4s, %10.s[0] \n" "fmul v10.4s, v3.4s, %10.s[1] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmul v11.4s, v1.4s, %10.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %11.s[0] \n" "fmla v10.4s, v3.4s, %11.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v8.4s, v9.4s}, [%3] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %11.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %12.s[0] \n" "fmla v10.4s, v3.4s, %12.s[1] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v8.4s, v9.4s}, [%4] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %12.s[2] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "fadd v0.4s, v0.4s, v10.4s \n" "fadd v0.4s, v0.4s, v11.4s \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s}, [%1], #16 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmul.f32 q10, q3, %e10[1] \n" "pld [%2, #128] \n" "vld2.f32 {d16-d17}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmul.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #128] \n" "vld2.f32 {d16-d17}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #128] \n" "vld2.f32 {d16-d17}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "vadd.f32 q0, q0, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } } static void conv3x3s2_transform_kernel_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(8 * 9, inch, outch / 8 + outch % 8); const float* kernel = _kernel; int p = 0; for (; p + 7 < outch; p += 8) { const float* k0 = kernel + (p + 0) * inch * 9; const float* k1 = kernel + (p + 1) * inch * 9; const float* k2 = kernel + (p + 2) * inch * 9; const float* k3 = kernel + (p + 3) * inch * 9; const float* k4 = kernel + (p + 4) * inch * 9; const float* k5 = kernel + (p + 5) * inch * 9; const float* k6 = kernel + (p + 6) * inch * 9; const float* k7 = kernel + (p + 7) * inch * 9; float* ktmp = kernel_tm.channel(p / 8); for (int q = 0; q < inch; q++) { for (int k = 0; k < 9; k++) { ktmp[0] = k0[k]; ktmp[1] = k1[k]; ktmp[2] = k2[k]; ktmp[3] = k3[k]; ktmp[4] = k4[k]; ktmp[5] = k5[k]; ktmp[6] = k6[k]; ktmp[7] = k7[k]; ktmp += 8; } k0 += 9; k1 += 9; k2 += 9; k3 += 9; k4 += 9; k5 += 9; k6 += 9; k7 += 9; } } for (; p < outch; p++) { const float* k0 = kernel + (p + 0) * inch * 9; float* ktmp = kernel_tm.channel(p / 8 + p % 8); for (int q = 0; q < inch; q++) { for (int k = 0; k < 9; k++) { ktmp[k] = k0[k]; } ktmp += 9; k0 += 9; } } } static void conv3x3s2_packed_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; // const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 3; int remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; Mat out0 = top_blob.channel(p + 0); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); Mat out4 = top_blob.channel(p + 4); Mat out5 = top_blob.channel(p + 5); Mat out6 = top_blob.channel(p + 6); Mat out7 = top_blob.channel(p + 7); const float bias0 = bias ? bias[p + 0] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float bias4 = bias ? bias[p + 4] : 0.f; const float bias5 = bias ? bias[p + 5] : 0.f; const float bias6 = bias ? bias[p + 6] : 0.f; const float bias7 = bias ? bias[p + 7] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); out6.fill(bias6); out7.fill(bias7); const float* ktmp = _kernel.channel(p / 8); for (int q = 0; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v8.4s}, [%1] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v9.4s}, [%2] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v10.4s}, [%3] \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v11.4s}, [%4] \n" /// "prfm pldl1keep, [%9, #256] \n" "ld2 {v4.4s, v5.4s}, [%9], #32 \n" // v4=00 v5=01 "ld1 {v0.4s, v1.4s}, [%12], #32 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v12.4s}, [%5] \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v13.4s}, [%6] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v14.4s}, [%7] \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v15.4s}, [%8] \n" "ld1 {v2.4s, v3.4s}, [%12], #32 \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "prfm pldl1keep, [%9, #256] \n" "ld2 {v6.4s, v7.4s}, [%9] \n" // v6 "fmla v8.4s, v5.4s, v2.s[0] \n" "fmla v9.4s, v5.4s, v2.s[1] \n" "fmla v10.4s, v5.4s, v2.s[2] \n" "fmla v11.4s, v5.4s, v2.s[3] \n" "ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=02 "ld1 {v0.4s, v1.4s}, [%12], #32 \n" "fmla v12.4s, v5.4s, v3.s[0] \n" "fmla v13.4s, v5.4s, v3.s[1] \n" "fmla v14.4s, v5.4s, v3.s[2] \n" "fmla v15.4s, v5.4s, v3.s[3] \n" /// "prfm pldl1keep, [%10, #256] \n" "ld2 {v4.4s, v5.4s}, [%10], #32 \n" // v4=10 v5=11 "fmla v8.4s, v6.4s, v0.s[0] \n" "fmla v9.4s, v6.4s, v0.s[1] \n" "fmla v10.4s, v6.4s, v0.s[2] \n" "fmla v11.4s, v6.4s, v0.s[3] \n" "ld1 {v2.4s, v3.4s}, [%12], #32 \n" "fmla v12.4s, v6.4s, v1.s[0] \n" "fmla v13.4s, v6.4s, v1.s[1] \n" "fmla v14.4s, v6.4s, v1.s[2] \n" "fmla v15.4s, v6.4s, v1.s[3] \n" "fmla v8.4s, v4.4s, v2.s[0] \n" "fmla v9.4s, v4.4s, v2.s[1] \n" "fmla v10.4s, v4.4s, v2.s[2] \n" "fmla v11.4s, v4.4s, v2.s[3] \n" "ld1 {v0.4s, v1.4s}, [%12], #32 \n" "fmla v12.4s, v4.4s, v3.s[0] \n" "fmla v13.4s, v4.4s, v3.s[1] \n" "fmla v14.4s, v4.4s, v3.s[2] \n" "fmla v15.4s, v4.4s, v3.s[3] \n" "prfm pldl1keep, [%10, #256] \n" "ld2 {v6.4s, v7.4s}, [%10] \n" // v6 "fmla v8.4s, v5.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[1] \n" "fmla v10.4s, v5.4s, v0.s[2] \n" "fmla v11.4s, v5.4s, v0.s[3] \n" "ld1 {v2.4s, v3.4s}, [%12], #32 \n" "ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=12 "fmla v12.4s, v5.4s, v1.s[0] \n" "fmla v13.4s, v5.4s, v1.s[1] \n" "fmla v14.4s, v5.4s, v1.s[2] \n" "fmla v15.4s, v5.4s, v1.s[3] \n" /// "prfm pldl1keep, [%11, #256] \n" "ld2 {v4.4s, v5.4s}, [%11], #32 \n" // v4=20 v5=21 "fmla v8.4s, v6.4s, v2.s[0] \n" "fmla v9.4s, v6.4s, v2.s[1] \n" "fmla v10.4s, v6.4s, v2.s[2] \n" "fmla v11.4s, v6.4s, v2.s[3] \n" "ld1 {v0.4s, v1.4s}, [%12], #32 \n" "fmla v12.4s, v6.4s, v3.s[0] \n" "fmla v13.4s, v6.4s, v3.s[1] \n" "fmla v14.4s, v6.4s, v3.s[2] \n" "fmla v15.4s, v6.4s, v3.s[3] \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "ld1 {v2.4s, v3.4s}, [%12], #32 \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "prfm pldl1keep, [%11, #256] \n" "ld2 {v6.4s, v7.4s}, [%11] \n" // v6 "fmla v8.4s, v5.4s, v2.s[0] \n" "fmla v9.4s, v5.4s, v2.s[1] \n" "fmla v10.4s, v5.4s, v2.s[2] \n" "fmla v11.4s, v5.4s, v2.s[3] \n" "ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=22 "ld1 {v0.4s, v1.4s}, [%12], #32 \n" "fmla v12.4s, v5.4s, v3.s[0] \n" "fmla v13.4s, v5.4s, v3.s[1] \n" "fmla v14.4s, v5.4s, v3.s[2] \n" "fmla v15.4s, v5.4s, v3.s[3] \n" "fmla v8.4s, v6.4s, v0.s[0] \n" "fmla v9.4s, v6.4s, v0.s[1] \n" "fmla v10.4s, v6.4s, v0.s[2] \n" "fmla v11.4s, v6.4s, v0.s[3] \n" "fmla v12.4s, v6.4s, v1.s[0] \n" "fmla v13.4s, v6.4s, v1.s[1] \n" "st1 {v8.4s}, [%1], #16 \n" "st1 {v9.4s}, [%2], #16 \n" "fmla v14.4s, v6.4s, v1.s[2] \n" "fmla v15.4s, v6.4s, v1.s[3] \n" "st1 {v10.4s}, [%3], #16 \n" "st1 {v11.4s}, [%4], #16 \n" "sub %12, %12, #288 \n" "st1 {v12.4s}, [%5], #16 \n" "st1 {v13.4s}, [%6], #16 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s}, [%7], #16 \n" "st1 {v15.4s}, [%8], #16 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(r0), // %9 "=r"(r1), // %10 "=r"(r2), // %11 "=r"(ktmp) // %12 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(r0), "10"(r1), "11"(r2), "12"(ktmp) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else // __aarch64__ for (; nn > 0; nn--) { asm volatile( "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0] \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1] \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2] \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3] \n" /// "pld [%8, #256] \n" "vld2.f32 {d8-d11}, [%8]! \n" // q4=00 q5=01 "vld1.f32 {d0-d3}, [%11 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4] \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "pld [%6, #128] \n" "vld1.f32 {d28-d29}, [%6] \n" "pld [%7, #128] \n" "vld1.f32 {d30-d31}, [%7] \n" "vld1.f32 {d4-d7}, [%11 :128]! \n" "vmla.f32 q12, q4, d2[0] \n" "vmla.f32 q13, q4, d2[1] \n" "vmla.f32 q14, q4, d3[0] \n" "vmla.f32 q15, q4, d3[1] \n" "pld [%8, #128] \n" "vld2.f32 {d12-d13}, [%8] \n" // q6 "vmla.f32 q8, q5, d4[0] \n" "vmla.f32 q9, q5, d4[1] \n" "vmla.f32 q10, q5, d5[0] \n" "vmla.f32 q11, q5, d5[1] \n" "vext.f32 q6, q4, q6, #1 \n" // q6=02 "vld1.f32 {d0-d3}, [%11 :128]! \n" "vmla.f32 q12, q5, d6[0] \n" "vmla.f32 q13, q5, d6[1] \n" "vmla.f32 q14, q5, d7[0] \n" "vmla.f32 q15, q5, d7[1] \n" /// "pld [%9, #256] \n" "vld2.f32 {d8-d11}, [%9]! \n" // q4=10 q5=11 "vmla.f32 q8, q6, d0[0] \n" "vmla.f32 q9, q6, d0[1] \n" "vmla.f32 q10, q6, d1[0] \n" "vmla.f32 q11, q6, d1[1] \n" "vld1.f32 {d4-d7}, [%11 :128]! \n" "vmla.f32 q12, q6, d2[0] \n" "vmla.f32 q13, q6, d2[1] \n" "vmla.f32 q14, q6, d3[0] \n" "vmla.f32 q15, q6, d3[1] \n" "vmla.f32 q8, q4, d4[0] \n" "vmla.f32 q9, q4, d4[1] \n" "vmla.f32 q10, q4, d5[0] \n" "vmla.f32 q11, q4, d5[1] \n" "vld1.f32 {d0-d3}, [%11 :128]! \n" "vmla.f32 q12, q4, d6[0] \n" "vmla.f32 q13, q4, d6[1] \n" "vmla.f32 q14, q4, d7[0] \n" "vmla.f32 q15, q4, d7[1] \n" "pld [%9, #128] \n" "vld2.f32 {d12-d13}, [%9] \n" // q6 "vmla.f32 q8, q5, d0[0] \n" "vmla.f32 q9, q5, d0[1] \n" "vmla.f32 q10, q5, d1[0] \n" "vmla.f32 q11, q5, d1[1] \n" "vld1.f32 {d4-d7}, [%11 :128]! \n" "vext.f32 q6, q4, q6, #1 \n" // q6=12 "vmla.f32 q12, q5, d2[0] \n" "vmla.f32 q13, q5, d2[1] \n" "vmla.f32 q14, q5, d3[0] \n" "vmla.f32 q15, q5, d3[1] \n" /// "pld [%10, #256] \n" "vld2.f32 {d8-d11}, [%10]! \n" // q4=20 q5=21 "vmla.f32 q8, q6, d4[0] \n" "vmla.f32 q9, q6, d4[1] \n" "vmla.f32 q10, q6, d5[0] \n" "vmla.f32 q11, q6, d5[1] \n" "vld1.f32 {d0-d3}, [%11 :128]! \n" "vmla.f32 q12, q6, d6[0] \n" "vmla.f32 q13, q6, d6[1] \n" "vmla.f32 q14, q6, d7[0] \n" "vmla.f32 q15, q6, d7[1] \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "vld1.f32 {d4-d7}, [%11 :128]! \n" "vmla.f32 q12, q4, d2[0] \n" "vmla.f32 q13, q4, d2[1] \n" "vmla.f32 q14, q4, d3[0] \n" "vmla.f32 q15, q4, d3[1] \n" "pld [%10, #128] \n" "vld2.f32 {d12-d13}, [%10] \n" // q6 "vmla.f32 q8, q5, d4[0] \n" "vmla.f32 q9, q5, d4[1] \n" "vmla.f32 q10, q5, d5[0] \n" "vmla.f32 q11, q5, d5[1] \n" "vext.f32 q6, q4, q6, #1 \n" // q6=22 "vld1.f32 {d0-d3}, [%11 :128]! \n" "vmla.f32 q12, q5, d6[0] \n" "vmla.f32 q13, q5, d6[1] \n" "vmla.f32 q14, q5, d7[0] \n" "vmla.f32 q15, q5, d7[1] \n" "vmla.f32 q8, q6, d0[0] \n" "vmla.f32 q9, q6, d0[1] \n" "vmla.f32 q10, q6, d1[0] \n" "vmla.f32 q11, q6, d1[1] \n" "vmla.f32 q12, q6, d2[0] \n" "vmla.f32 q13, q6, d2[1] \n" "vst1.f32 {d16-d17}, [%0]! \n" "vst1.f32 {d18-d19}, [%1]! \n" "vmla.f32 q14, q6, d3[0] \n" "vmla.f32 q15, q6, d3[1] \n" "vst1.f32 {d20-d21}, [%2]! \n" "vst1.f32 {d22-d23}, [%3]! \n" "sub %11, %11, #288 \n" "vst1.f32 {d24-d25}, [%4]! \n" "vst1.f32 {d26-d27}, [%5]! \n" "vst1.f32 {d28-d29}, [%6]! \n" "vst1.f32 {d30-d31}, [%7]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(r0), // %8 "=r"(r1), // %9 "=r"(r2), // %10 "=r"(ktmp) // %11 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(r0), "9"(r1), "10"(r2), "11"(ktmp) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v10.4s, v11.4s}, [%11], #32 \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v0.4s}, [%8] \n" "ld1 {v12.4s, v13.4s}, [%11], #32 \n" "ld1 {v8.s}[0], [%0] \n" "ld1 {v8.s}[1], [%1] \n" "ld1 {v8.s}[2], [%2] \n" "ld1 {v8.s}[3], [%3] \n" "fmul v14.4s, v10.4s, v0.s[0] \n" "fmul v15.4s, v11.4s, v0.s[0] \n" "ld1 {v9.s}[0], [%4] \n" "ld1 {v9.s}[1], [%5] \n" "ld1 {v9.s}[2], [%6] \n" "ld1 {v9.s}[3], [%7] \n" "ld1 {v10.4s, v11.4s}, [%11], #32 \n" "fmla v8.4s, v12.4s, v0.s[1] \n" "fmla v9.4s, v13.4s, v0.s[1] \n" "ld1 {v12.4s, v13.4s}, [%11], #32 \n" "fmla v14.4s, v10.4s, v0.s[2] \n" "fmla v15.4s, v11.4s, v0.s[2] \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v1.4s}, [%9] \n" "ld1 {v10.4s, v11.4s}, [%11], #32 \n" "fmla v8.4s, v12.4s, v1.s[0] \n" "fmla v9.4s, v13.4s, v1.s[0] \n" "ld1 {v12.4s, v13.4s}, [%11], #32 \n" "fmla v14.4s, v10.4s, v1.s[1] \n" "fmla v15.4s, v11.4s, v1.s[1] \n" "ld1 {v10.4s, v11.4s}, [%11], #32 \n" "fmla v8.4s, v12.4s, v1.s[2] \n" "fmla v9.4s, v13.4s, v1.s[2] \n" "prfm pldl1keep, [%10, #128] \n" "ld1 {v0.4s}, [%10] \n" "ld1 {v12.4s, v13.4s}, [%11], #32 \n" "fmla v14.4s, v10.4s, v0.s[0] \n" "fmla v15.4s, v11.4s, v0.s[0] \n" "ld1 {v10.4s, v11.4s}, [%11], #32 \n" "fmla v8.4s, v12.4s, v0.s[1] \n" "fmla v9.4s, v13.4s, v0.s[1] \n" "fmla v14.4s, v10.4s, v0.s[2] \n" "fmla v15.4s, v11.4s, v0.s[2] \n" "fadd v8.4s, v8.4s, v14.4s \n" "fadd v9.4s, v9.4s, v15.4s \n" "sub %11, %11, #288 \n" "st1 {v8.s}[0], [%0], #4 \n" "st1 {v8.s}[1], [%1], #4 \n" "st1 {v8.s}[2], [%2], #4 \n" "st1 {v8.s}[3], [%3], #4 \n" "st1 {v9.s}[0], [%4], #4 \n" "st1 {v9.s}[1], [%5], #4 \n" "st1 {v9.s}[2], [%6], #4 \n" "st1 {v9.s}[3], [%7], #4 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(r0), // %8 "=r"(r1), // %9 "=r"(r2), // %10 "=r"(ktmp) // %11 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(r0), "9"(r1), "10"(r2), "11"(ktmp) : "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); #else // __aarch64__ asm volatile( "vld1.f32 {d20-d23}, [%11 :128]! \n" "pld [%8, #128] \n" "vld1.f32 {d0-d1}, [%8] \n" "vld1.f32 {d24-d27}, [%11 :128]! \n" "vld1.f32 {d16[0]}, [%0] \n" "vld1.f32 {d16[1]}, [%1] \n" "vld1.f32 {d17[0]}, [%2] \n" "vld1.f32 {d17[1]}, [%3] \n" "vmul.f32 q14, q10, d0[0] \n" "vmul.f32 q15, q11, d0[0] \n" "vld1.f32 {d18[0]}, [%4] \n" "vld1.f32 {d18[1]}, [%5] \n" "vld1.f32 {d19[0]}, [%6] \n" "vld1.f32 {d19[1]}, [%7] \n" "vld1.f32 {d20-d23}, [%11 :128]! \n" "vmla.f32 q8, q12, d0[1] \n" "vmla.f32 q9, q13, d0[1] \n" "vld1.f32 {d24-d27}, [%11 :128]! \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q11, d1[0] \n" "pld [%9, #128] \n" "vld1.f32 {d2-d3}, [%9] \n" "vld1.f32 {d20-d23}, [%11 :128]! \n" "vmla.f32 q8, q12, d2[0] \n" "vmla.f32 q9, q13, d2[0] \n" "vld1.f32 {d24-d27}, [%11 :128]! \n" "vmla.f32 q14, q10, d2[1] \n" "vmla.f32 q15, q11, d2[1] \n" "vld1.f32 {d20-d23}, [%11 :128]! \n" "vmla.f32 q8, q12, d3[0] \n" "vmla.f32 q9, q13, d3[0] \n" "pld [%10, #128] \n" "vld1.f32 {d0-d1}, [%10] \n" "vld1.f32 {d24-d27}, [%11 :128]! \n" "vmla.f32 q14, q10, d0[0] \n" "vmla.f32 q15, q11, d0[0] \n" "vld1.f32 {d20-d23}, [%11 :128]! \n" "vmla.f32 q8, q12, d0[1] \n" "vmla.f32 q9, q13, d0[1] \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q11, d1[0] \n" "vadd.f32 q8, q8, q14 \n" "vadd.f32 q9, q9, q15 \n" "sub %11, %11, #288 \n" "vst1.f32 {d16[0]}, [%0]! \n" "vst1.f32 {d16[1]}, [%1]! \n" "vst1.f32 {d17[0]}, [%2]! \n" "vst1.f32 {d17[1]}, [%3]! \n" "vst1.f32 {d18[0]}, [%4]! \n" "vst1.f32 {d18[1]}, [%5]! \n" "vst1.f32 {d19[0]}, [%6]! \n" "vst1.f32 {d19[1]}, [%7]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(r0), // %8 "=r"(r1), // %9 "=r"(r2), // %10 "=r"(ktmp) // %11 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(r0), "9"(r1), "10"(r2), "11"(ktmp) : "memory", "q0", "q1", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ #else // __ARM_NEON float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; float sum4 = 0.f; float sum5 = 0.f; float sum6 = 0.f; float sum7 = 0.f; sum0 += r0[0] * ktmp[0]; sum1 += r0[0] * ktmp[1]; sum2 += r0[0] * ktmp[2]; sum3 += r0[0] * ktmp[3]; sum4 += r0[0] * ktmp[4]; sum5 += r0[0] * ktmp[5]; sum6 += r0[0] * ktmp[6]; sum7 += r0[0] * ktmp[7]; ktmp += 8; sum0 += r0[1] * ktmp[0]; sum1 += r0[1] * ktmp[1]; sum2 += r0[1] * ktmp[2]; sum3 += r0[1] * ktmp[3]; sum4 += r0[1] * ktmp[4]; sum5 += r0[1] * ktmp[5]; sum6 += r0[1] * ktmp[6]; sum7 += r0[1] * ktmp[7]; ktmp += 8; sum0 += r0[2] * ktmp[0]; sum1 += r0[2] * ktmp[1]; sum2 += r0[2] * ktmp[2]; sum3 += r0[2] * ktmp[3]; sum4 += r0[2] * ktmp[4]; sum5 += r0[2] * ktmp[5]; sum6 += r0[2] * ktmp[6]; sum7 += r0[2] * ktmp[7]; ktmp += 8; sum0 += r1[0] * ktmp[0]; sum1 += r1[0] * ktmp[1]; sum2 += r1[0] * ktmp[2]; sum3 += r1[0] * ktmp[3]; sum4 += r1[0] * ktmp[4]; sum5 += r1[0] * ktmp[5]; sum6 += r1[0] * ktmp[6]; sum7 += r1[0] * ktmp[7]; ktmp += 8; sum0 += r1[1] * ktmp[0]; sum1 += r1[1] * ktmp[1]; sum2 += r1[1] * ktmp[2]; sum3 += r1[1] * ktmp[3]; sum4 += r1[1] * ktmp[4]; sum5 += r1[1] * ktmp[5]; sum6 += r1[1] * ktmp[6]; sum7 += r1[1] * ktmp[7]; ktmp += 8; sum0 += r1[2] * ktmp[0]; sum1 += r1[2] * ktmp[1]; sum2 += r1[2] * ktmp[2]; sum3 += r1[2] * ktmp[3]; sum4 += r1[2] * ktmp[4]; sum5 += r1[2] * ktmp[5]; sum6 += r1[2] * ktmp[6]; sum7 += r1[2] * ktmp[7]; ktmp += 8; sum0 += r2[0] * ktmp[0]; sum1 += r2[0] * ktmp[1]; sum2 += r2[0] * ktmp[2]; sum3 += r2[0] * ktmp[3]; sum4 += r2[0] * ktmp[4]; sum5 += r2[0] * ktmp[5]; sum6 += r2[0] * ktmp[6]; sum7 += r2[0] * ktmp[7]; ktmp += 8; sum0 += r2[1] * ktmp[0]; sum1 += r2[1] * ktmp[1]; sum2 += r2[1] * ktmp[2]; sum3 += r2[1] * ktmp[3]; sum4 += r2[1] * ktmp[4]; sum5 += r2[1] * ktmp[5]; sum6 += r2[1] * ktmp[6]; sum7 += r2[1] * ktmp[7]; ktmp += 8; sum0 += r2[2] * ktmp[0]; sum1 += r2[2] * ktmp[1]; sum2 += r2[2] * ktmp[2]; sum3 += r2[2] * ktmp[3]; sum4 += r2[2] * ktmp[4]; sum5 += r2[2] * ktmp[5]; sum6 += r2[2] * ktmp[6]; sum7 += r2[2] * ktmp[7]; ktmp += 8; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; ktmp -= 8 * 9; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } ktmp += 8 * 9; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* ktmp = _kernel.channel(p / 8 + p % 8); for (int q = 0; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* k0 = ktmp; const float* k1 = ktmp + 3; const float* k2 = ktmp + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.4s}, [%1] \n" "fmla v0.4s, v2.4s, %10.s[0] \n" "fmul v10.4s, v3.4s, %10.s[1] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmul v11.4s, v1.4s, %10.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %11.s[0] \n" "fmla v10.4s, v3.4s, %11.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v8.4s, v9.4s}, [%3] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %11.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %12.s[0] \n" "fmla v10.4s, v3.4s, %12.s[1] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v8.4s, v9.4s}, [%4] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %12.s[2] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "fadd v0.4s, v0.4s, v10.4s \n" "fadd v0.4s, v0.4s, v11.4s \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s}, [%1], #16 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmul.f32 q10, q3, %e10[1] \n" "pld [%2, #128] \n" "vld2.f32 {d16-d17}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmul.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #128] \n" "vld2.f32 {d16-d17}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #128] \n" "vld2.f32 {d16-d17}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "vadd.f32 q0, q0, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * ktmp[0]; sum += r0[1] * ktmp[1]; sum += r0[2] * ktmp[2]; sum += r1[0] * ktmp[3]; sum += r1[1] * ktmp[4]; sum += r1[2] * ktmp[5]; sum += r2[0] * ktmp[6]; sum += r2[1] * ktmp[7]; sum += r2[2] * ktmp[8]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } ktmp += 9; } } }
pr29947-1.c
/* PR libgomp/29947 */ /* { dg-do run } */ extern void abort (void); int cnt; void test1 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (dynamic) for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test2 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (dynamic) for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test3 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (guided) for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test4 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (guided) for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test5 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (dynamic) ordered for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test6 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (dynamic) ordered for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test7 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (guided) ordered for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test8 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel reduction (+:e,c) { #pragma omp for schedule (guided) ordered for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } #pragma omp atomic ++cnt; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test9 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (dynamic) for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test10 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (dynamic) for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test11 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (guided) for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test12 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (guided) for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test13 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (dynamic) ordered for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test14 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (dynamic) ordered for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test15 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (guided) ordered for (i = j1; i <= k1; ++i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } void test16 (long j1, long k1, long j2, long k2) { long i, e = 0, c = 0; #pragma omp parallel for reduction (+:e,c) schedule (guided) ordered for (i = k1; i >= j1; --i) { if (i < j2 || i > k2) ++e; #pragma omp ordered ++c; } if (e || (c != j2 > k2 ? 0 : k2 - j2 + 1)) abort (); } int __attribute__((noinline)) test (long j1, long k1, long j2, long k2) { test1 (j1, k1, j2, k2); test2 (j1, k1, j2, k2); test3 (j1, k1, j2, k2); test4 (j1, k1, j2, k2); test5 (j1, k1, j2, k2); test6 (j1, k1, j2, k2); test7 (j1, k1, j2, k2); test8 (j1, k1, j2, k2); test9 (j1, k1, j2, k2); test10 (j1, k1, j2, k2); test11 (j1, k1, j2, k2); test12 (j1, k1, j2, k2); test13 (j1, k1, j2, k2); test14 (j1, k1, j2, k2); test15 (j1, k1, j2, k2); test16 (j1, k1, j2, k2); return cnt; } int main (void) { test (1, 5, 1, 5); test (5, 5, 5, 5); test (5, 4, 5, 4); test (5, 1, 5, 1); return 0; }
generator_spgemm_csr_asparse.c
/****************************************************************************** ** Copyright (c) 2015-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include "generator_spgemm_csr_asparse.h" #include "generator_common.h" #include "libxsmm_main.h" #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET)) #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #if defined(LIBXSMM_OFFLOAD_TARGET) # pragma offload_attribute(pop) #endif LIBXSMM_API_INTERN void libxsmm_generator_spgemm_csr_asparse( libxsmm_generated_code* io_generated_code, const libxsmm_gemm_descriptor* i_xgemm_desc, const char* i_arch, const unsigned int* i_row_idx, const unsigned int* i_column_idx, const double* i_values ) { unsigned int l_m; unsigned int l_z; unsigned int l_row_elements; unsigned int l_flop_count = 0; char l_new_code[512]; int l_max_code_length = 511; int l_code_length = 0; LIBXSMM_UNUSED(i_values); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_n = 0;\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* reset C if beta is zero */ if ( i_xgemm_desc->beta == 0 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_m = 0;\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_m = 0; l_m < %u; l_m++) {\n", (unsigned int)i_xgemm_desc->m); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); if ( i_xgemm_desc->m > 1 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) { C[(l_m*%u)+l_n] = 0.0; }\n", (unsigned int)i_xgemm_desc->ldc, (unsigned int)i_xgemm_desc->ldc); } else { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) { C[(l_m*%u)+l_n] = 0.0f; }\n", (unsigned int)i_xgemm_desc->ldc, (unsigned int)i_xgemm_desc->ldc); } libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* determine the correct simd pragma for each architecture */ if ( ( strcmp( i_arch, "noarch" ) == 0 ) || ( strcmp( i_arch, "wsm" ) == 0 ) || ( strcmp( i_arch, "snb" ) == 0 ) || ( strcmp( i_arch, "hsw" ) == 0 ) ) { if ( i_xgemm_desc->n > 7 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(8)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else if ( i_xgemm_desc->n > 3 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(4)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else if ( i_xgemm_desc->n > 1 ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(2)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } else {} } else if ( ( strcmp( i_arch, "knc" ) == 0 ) || ( strcmp( i_arch, "knl" ) == 0 ) || ( strcmp( i_arch, "skx" ) == 0 ) ) { if ( (i_xgemm_desc->n > 1) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(16)\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_ARCH ); return; } if ( (i_xgemm_desc->n > 1) && ((LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0) && ((LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0) ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } /* generate the actuel kernel */ l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) {\n", (unsigned int)i_xgemm_desc->n); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); for ( l_m = 0; l_m < (unsigned int)i_xgemm_desc->m; l_m++ ) { l_row_elements = i_row_idx[l_m+1] - i_row_idx[l_m]; for ( l_z = 0; l_z < l_row_elements; l_z++ ) { /* check k such that we just use columns which actually need to be multiplied */ if ( i_column_idx[i_row_idx[l_m] + l_z] < (unsigned int)i_xgemm_desc->k ) { l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " C[%u+l_n] += A[%u] * B[%u+l_n];\n", l_m * i_xgemm_desc->ldc, i_row_idx[l_m] + l_z, i_column_idx[i_row_idx[l_m] + l_z]*i_xgemm_desc->ldb ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_flop_count += 2; } } } l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n"); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); /* add flop counter */ l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n#ifndef NDEBUG\n#ifdef _OPENMP\n#pragma omp atomic\n#endif\nlibxsmm_num_total_flops += %u;\n#endif\n", l_flop_count * (unsigned int)i_xgemm_desc->m); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); }
quantized_conv2d.h
/* Copyright 2018 The Blueoil Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef DLK_FUNC_QUANTIZED_CONV2D_H_INCLUDED #define DLK_FUNC_QUANTIZED_CONV2D_H_INCLUDED #include <vector> #include <memory> #include <stdexcept> #include "global.h" #include "tensor_view.h" #include "tensor_convert.h" #include "operators.h" #include "time_measurement.h" #include "func/impl/quantized_conv2d_tiling.h" #include "func/impl/quantized_conv2d_kn2row.h" #include "func/impl/quantized_conv2d_accelerator.h" #ifdef _OPENMP #include <omp.h> #endif template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void QuantizedConv2D( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, binary_convolution_parameters p) { Measurement::Start("QuantizedConv2D"); constexpr T_UINT TilingInTypeBitWidth = dlk::impl::tiling_input_elem_t::BitCount; T_UINT kh = p.normal_conv_params.kernel_height; T_UINT kw = p.normal_conv_params.kernel_width; T_UINT padding = p.normal_conv_params.padding; T_UINT ih = p.normal_conv_params.input_height; T_UINT iw = p.normal_conv_params.input_width; T_UINT ic = p.normal_conv_params.kernel_depth; T_UINT oc = p.normal_conv_params.output_channels; T_UINT maxa = (1 << p.n_bit) - 1; auto size = oc * ih * iw; if (p.device_output_buf == nullptr) p.device_output_buf = new BIN_CONV_OUTPUT[size](); assert(kh == kw); // kernel rectangle must be square assert(kh % 2 == 1); // kernel size must be odd assert(1 <= kh && kh <= 5); // Only 1x1, 3x3, 5x5 are supported assert(ic * kh * kw * maxa <= std::numeric_limits<BIN_CONV_OUTPUT>::max()); // overflow check #ifdef RUN_ON_FPGA dlk::impl::tca_input_t::tensor_info_t<std::size_t> shape = { (ic + QUANTIZED_PACKED::BitCount - 1) / QUANTIZED_PACKED::BitCount, ih, iw, p.bin_input_bitwidth, QUANTIZED_PACKED::BitCount }; dlk::impl::tca_input_t tmp((QUANTIZED_PACKED*)p.device_input_buf, shape); convert_tensor(input, tmp); dlk::impl::TCAConv2d(tmp, kernel, p); #elif defined USE_NEON || defined USE_AVX dlk::impl::tiling_input_t::tensor_info_t<std::size_t> shape = { ic / TilingInTypeBitWidth, ih, iw, p.bin_input_bitwidth, TilingInTypeBitWidth }; dlk::impl::tiling_input_t tmp(reinterpret_cast<dlk::impl::tiling_input_elem_t*>(p.device_input_buf), shape); convert_tensor(input, tmp); dlk::impl::QuantizedConv2DTiling(tmp, kernel, p); #else dlk::impl::kn2row_input_t::tensor_info_t<std::size_t> shape = { ih, iw, ic / QUANTIZED_PACKED::BitCount, p.bin_input_bitwidth, QUANTIZED_PACKED::BitCount }; dlk::impl::kn2row_input_t tmp(reinterpret_cast<QUANTIZED_PACKED*>(p.device_input_buf), shape); convert_tensor(input, tmp); dlk::impl::QuantizedConv2DKn2Row(tmp, kernel, p); #endif Measurement::Stop(); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2D( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, const TensorView<T_FLOAT, MemoryLayout::NHWC>& output, const T_FLOAT scaling_factor, const binary_convolution_parameters& p) { QuantizedConv2D(input, kernel, p); Measurement::Start("QuantizedConv2D_ApplyScalingFactor"); unsigned out_elems = p.normal_conv_params.output_height * p.normal_conv_params.output_width * p.normal_conv_params.output_channels; // temporary: (2^n - 1) * (max - min) const T_FLOAT post_qtz_factor = 2.0f / 3.0f; const T_FLOAT coeff = scaling_factor * post_qtz_factor; size_t b = 32; auto &ncp(p.normal_conv_params); auto true_out_channels = output.get_shape()[3]; auto channel_blocks = true_out_channels / b; size_t area = ncp.output_height * ncp.output_width; auto out_buf = reinterpret_cast<VOLATILE_IF_FPGA BIN_CONV_OUTPUT*>(p.device_output_buf); #pragma omp parallel for for (size_t hw = 0; hw < area; ++hw) { size_t out_index = hw * true_out_channels; for (size_t s = 0; s < channel_blocks; ++s) for (size_t d = 0; d < b; ++d) output.data()[out_index++] = coeff * out_buf[hw * b + s * (area * b) + d]; for (size_t d = 0; d < true_out_channels - channel_blocks*b; ++d) output.data()[out_index++] = coeff * out_buf[hw * b + channel_blocks * (area * b) + d]; } Measurement::Stop(); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2D( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, const TensorView<T_FLOAT, MemoryLayout::NHWC>& output, T_FLOAT scaling_factor[], binary_convolution_parameters p) { QuantizedConv2D(input, kernel, p); unsigned out_elems = p.normal_conv_params.output_height * p.normal_conv_params.output_width; unsigned out_channels = p.normal_conv_params.output_channels; size_t b = 32; auto& ncp(p.normal_conv_params); auto true_out_channels = output.get_shape()[3]; auto channel_blocks = true_out_channels / b; // temporary: (2^n - 1) * (max - min) T_FLOAT post_qtz_factor = 2.0 / 3.0; Measurement::Start("QuantizedConv2D_ApplyScalingFactor"); size_t area = ncp.output_height * ncp.output_width; auto out_buf = reinterpret_cast<VOLATILE_IF_FPGA BIN_CONV_OUTPUT*>(p.device_output_buf); #pragma omp parallel for for (size_t hw = 0; hw < area; ++hw) { size_t out_index = hw * true_out_channels; for (size_t s = 0; s < channel_blocks; ++s) for (size_t d = 0; d < b; ++d) output.data()[out_index++] = (scaling_factor[s*b + d] * post_qtz_factor) * out_buf[hw * b + s * (area * b) + d]; for (size_t d = 0; d < true_out_channels - channel_blocks*b; ++d) output.data()[out_index++] = (scaling_factor[channel_blocks*b + d] * post_qtz_factor) * out_buf[hw * b + channel_blocks * (area * b) + d]; } Measurement::Stop(); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2DWithThreshold( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, const TensorView<QUANTIZED_PACKED, MemoryLayout::ChHWBCl>& output, const T_FLOAT scaling_factor, const binary_convolution_parameters& p) { QuantizedConv2D(input, kernel, p); unsigned out_elems = p.normal_conv_params.output_height * p.normal_conv_params.output_width * p.normal_conv_params.output_channels; const auto bytes = out_elems / 8 * p.n_bit; Measurement::Start("Memcpy"); #ifdef _OPENMP const int num_blocks = bytes / sizeof(QUANTIZED_PACKED); const int num_threads = omp_get_max_threads(); const int chunk_size = (num_blocks + num_threads - 1) / num_threads; #pragma omp parallel for for (int i = 0; i < num_blocks; i += chunk_size) { memcpy(output.data() + i, (QUANTIZED_PACKED*)(p.device_output_buf) + i, std::min(chunk_size, num_blocks - i) * sizeof(QUANTIZED_PACKED)); } #else memcpy(output.data(), (void*)p.device_output_buf, bytes); #endif Measurement::Stop(); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2DWithThreshold( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, const TensorView<T_FLOAT, MemoryLayout::NHWC>& output, const T_FLOAT scaling_factor, const binary_convolution_parameters& p) { QuantizedConv2D(input, kernel, p); Measurement::Start("linear_to_float"); T_FLOAT n = (1 << p.n_bit) - 1; const auto& np = p.normal_conv_params; const auto out_height = np.output_height; const auto out_width = np.output_width; const auto out_channels = np.output_channels; const auto true_out_channels = output.get_shape()[3]; auto out_buf = reinterpret_cast<VOLATILE_IF_FPGA QUANTIZED_PACKED::base_t*>(p.device_output_buf); for (unsigned r = 0; r < out_height; ++r) { for (unsigned c = 0; c < out_width; ++c) { for (unsigned d = 0; d < true_out_channels; ++d) { const auto i = r * out_width * p.n_bit + c * p.n_bit; QUANTIZED_PACKED::base_t bits = 0; for (unsigned digit = 0; digit < p.n_bit; ++digit) { bits |= ((out_buf[i + digit] >> d) & 1) << digit; } T_FLOAT tmp = (T_FLOAT)bits; tmp = tmp / n; output(0, r, c, d) = tmp * p.max_value; } } } Measurement::Stop(); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2DWithThreshold( const TensorView<QuantizedPacked<T_input>, layout_input>& input, const TensorView<QuantizedPacked<T_kernel>, layout_kernel>& kernel, const TensorView<QUANTIZED_PACKED, MemoryLayout::ChHWBCl>& output, const T_FLOAT scaling_factor[], const binary_convolution_parameters& p) { func_QuantizedConv2DWithThreshold(input, kernel, output, scaling_factor[0], p); } template <typename T_input, MemoryLayout layout_input, typename T_kernel, MemoryLayout layout_kernel> void func_QuantizedConv2DWithThreshold( const TensorView<T_input, layout_input>& input, const TensorView<T_kernel, layout_kernel>& kernel, const TensorView<T_FLOAT, MemoryLayout::NHWC>& output, T_FLOAT scaling_factor[], binary_convolution_parameters p) { func_QuantizedConv2DWithThreshold(input, kernel, output, scaling_factor[0], p); } #endif // DLK_FUNC_QUANTIZED_CONV2D_H_INCLUDED
TBBHashmap.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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. // ---------------------------------------------------------------------------- #pragma once #include <tbb/concurrent_unordered_map.h> #include <limits> #include <unordered_map> #include "open3d/core/hashmap/CPU/CPUHashmapBufferAccessor.hpp" #include "open3d/core/hashmap/DeviceHashmap.h" #include "open3d/utility/Parallel.h" namespace open3d { namespace core { template <typename Key, typename Hash> class TBBHashmap : public DeviceHashmap { public: TBBHashmap(int64_t init_capacity, int64_t dsize_key, int64_t dsize_value, const Device& device); ~TBBHashmap(); void Rehash(int64_t buckets) override; void Insert(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Activate(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Find(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Erase(const void* input_keys, bool* output_masks, int64_t count) override; int64_t GetActiveIndices(addr_t* output_indices) override; void Clear() override; int64_t Size() const override; int64_t GetBucketCount() const override; std::vector<int64_t> BucketSizes() const override; float LoadFactor() const override; std::shared_ptr<tbb::concurrent_unordered_map<Key, addr_t, Hash>> GetImpl() const { return impl_; } protected: std::shared_ptr<tbb::concurrent_unordered_map<Key, addr_t, Hash>> impl_; std::shared_ptr<CPUHashmapBufferAccessor> buffer_ctx_; void InsertImpl(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count); void Allocate(int64_t capacity); }; template <typename Key, typename Hash> TBBHashmap<Key, Hash>::TBBHashmap(int64_t init_capacity, int64_t dsize_key, int64_t dsize_value, const Device& device) : DeviceHashmap(init_capacity, dsize_key, dsize_value, device) { Allocate(init_capacity); } template <typename Key, typename Hash> TBBHashmap<Key, Hash>::~TBBHashmap() {} template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::Size() const { return impl_->size(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Insert(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) { int64_t new_size = Size() + count; if (new_size > this->capacity_) { int64_t bucket_count = GetBucketCount(); float avg_capacity_per_bucket = float(this->capacity_) / float(bucket_count); int64_t expected_buckets = std::max( bucket_count * 2, int64_t(std::ceil(new_size / avg_capacity_per_bucket))); Rehash(expected_buckets); } InsertImpl(input_keys, input_values, output_addrs, output_masks, count); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Activate(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) { Insert(input_keys, nullptr, output_addrs, output_masks, count); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Find(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; output_addrs[i] = flag ? iter->second : 0; } } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Erase(const void* input_keys, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; if (flag) { buffer_ctx_->DeviceFree(iter->second); impl_->unsafe_erase(iter); } } } template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::GetActiveIndices(addr_t* output_indices) { int64_t count = impl_->size(); int64_t i = 0; for (auto iter = impl_->begin(); iter != impl_->end(); ++iter, ++i) { output_indices[i] = static_cast<int64_t>(iter->second); } return count; } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Clear() { impl_->clear(); buffer_ctx_->Reset(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Rehash(int64_t buckets) { int64_t iterator_count = Size(); Tensor active_keys; Tensor active_values; if (iterator_count > 0) { Tensor active_addrs({iterator_count}, core::Int32, this->device_); GetActiveIndices(static_cast<addr_t*>(active_addrs.GetDataPtr())); Tensor active_indices = active_addrs.To(core::Int64); active_keys = this->GetKeyBuffer().IndexGet({active_indices}); active_values = this->GetValueBuffer().IndexGet({active_indices}); } float avg_capacity_per_bucket = float(this->capacity_) / float(GetBucketCount()); int64_t new_capacity = int64_t(std::ceil(buckets * avg_capacity_per_bucket)); Allocate(new_capacity); if (iterator_count > 0) { Tensor output_addrs({iterator_count}, core::Int32, this->device_); Tensor output_masks({iterator_count}, core::Bool, this->device_); InsertImpl(active_keys.GetDataPtr(), active_values.GetDataPtr(), static_cast<addr_t*>(output_addrs.GetDataPtr()), output_masks.GetDataPtr<bool>(), iterator_count); } impl_->rehash(buckets); } template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::GetBucketCount() const { return impl_->unsafe_bucket_count(); } template <typename Key, typename Hash> std::vector<int64_t> TBBHashmap<Key, Hash>::BucketSizes() const { int64_t bucket_count = impl_->unsafe_bucket_count(); std::vector<int64_t> ret; for (int64_t i = 0; i < bucket_count; ++i) { ret.push_back(impl_->unsafe_bucket_size(i)); } return ret; } template <typename Key, typename Hash> float TBBHashmap<Key, Hash>::LoadFactor() const { return impl_->load_factor(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::InsertImpl(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { output_addrs[i] = 0; output_masks[i] = false; const Key& key = input_keys_templated[i]; // Try to insert a dummy address. auto res = impl_->insert({key, 0}); // Lazy copy key value pair to buffer only if succeeded if (res.second) { addr_t dst_kv_addr = buffer_ctx_->DeviceAllocate(); auto dst_kv_iter = buffer_ctx_->ExtractIterator(dst_kv_addr); // Copy templated key to buffer *static_cast<Key*>(dst_kv_iter.first) = key; // Copy/reset non-templated value in buffer uint8_t* dst_value = static_cast<uint8_t*>(dst_kv_iter.second); if (input_values != nullptr) { const uint8_t* src_value = static_cast<const uint8_t*>(input_values) + this->dsize_value_ * i; std::memcpy(dst_value, src_value, this->dsize_value_); } else { std::memset(dst_value, 0, this->dsize_value_); } // Update from dummy 0 res.first->second = dst_kv_addr; // Write to return variables output_addrs[i] = dst_kv_addr; output_masks[i] = true; } } } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Allocate(int64_t capacity) { this->capacity_ = capacity; this->buffer_ = std::make_shared<HashmapBuffer>(this->capacity_, this->dsize_key_, this->dsize_value_, this->device_); buffer_ctx_ = std::make_shared<CPUHashmapBufferAccessor>( this->capacity_, this->dsize_key_, this->dsize_value_, this->buffer_->GetKeyBuffer(), this->buffer_->GetValueBuffer(), this->buffer_->GetHeap()); buffer_ctx_->Reset(); impl_ = std::make_shared<tbb::concurrent_unordered_map<Key, addr_t, Hash>>( capacity, Hash()); } } // namespace core } // namespace open3d
zlanhe.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" /***************************************************************************//** * * @ingroup plasma_lanhe * * Returns the norm of a Hermitian matrix as * * zlanhe = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm * ( * ( norm1(A), NORM = PlasmaOneNorm * ( * ( normI(A), NORM = PlasmaInfNorm * ( * ( normF(A), NORM = PlasmaFrobeniusNorm * * where norm1 denotes the one norm of a matrix (maximum column sum), * normI denotes the infinity norm of a matrix (maximum row sum) and * normF denotes the Frobenius norm of a matrix (square root of sum * of squares). Note that max(abs(A(i,j))) is not a consistent matrix * norm. * ******************************************************************************* * * @param[in] norm * - PlasmaMaxNorm: Max norm * - PlasmaOneNorm: One norm * - PlasmaInfNorm: Infinity norm * - PlasmaFrobeniusNorm: Frobenius norm * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] pA * On entry, the Hermitian matrix A. * If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A * contains the upper triangular part of the matrix A, and the strictly * lower triangular part of A is not referenced. * If uplo = PlasmaLower, the leading N-by-N lower triangular part of A * contains the lower triangular part of the matrix A, and the strictly * upper triangular part of A is not referenced. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,m). * ******************************************************************************* * * @retval double * The specified norm of the Hermitian matrix A. * ******************************************************************************* * * @sa plasma_omp_zlanhe * @sa plasma_clanhe * ******************************************************************************/ double plasma_zlanhe(plasma_enum_t norm, plasma_enum_t uplo, int n, plasma_complex64_t *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 ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) && (norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm) ) { plasma_error("illegal value of norm"); return -1; } if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); 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 (n == 0) return 0.0; // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } // Allocate workspace. double *work = NULL; switch (norm) { case PlasmaMaxNorm: work = (double*)malloc((size_t)A.mt*A.nt*sizeof(double)); break; case PlasmaOneNorm: case PlasmaInfNorm: work = (double*)malloc(((size_t)A.mt*A.n+A.n)*sizeof(double)); break; case PlasmaFrobeniusNorm: work = (double*)malloc((size_t)2*A.mt*A.nt*sizeof(double)); break; } if (work == NULL) { plasma_error("malloc() failed"); return PlasmaErrorOutOfMemory; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; double value; // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, sequence, &request); // Call tile async function. plasma_omp_zlanhe(norm, uplo, A, work, &value, sequence, &request); } // implicit synchronization free(work); // Free matrix in tile layout. plasma_desc_destroy(&A); // Destroy sequence. plasma_sequence_destroy(sequence); // Return the norm. return value; } /***************************************************************************//** * * @ingroup plasma_lanhe * * Calculates the max, one, infinity or Frobenius norm of a Hermitian matrix. * Non-blocking equivalent of plasma_zlanhe(). May return before the * computation is finished. Operates on matrices stored by tiles. All matrices * are passed through descriptors. All dimensions are taken from the * descriptors. Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] norm * - PlasmaMaxNorm: Max norm * - PlasmaOneNorm: One norm * - PlasmaInfNorm: Infinity norm * - PlasmaFrobeniusNorm: Frobenius norm * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] A * The descriptor of matrix A. * * @param[out] work * Workspace of size: * - PlasmaMaxNorm: A.mt*A.nt * - PlasmaOneNorm: A.mt*A.n + A.n * - PlasmaInfNorm: A.mt*A.n + A.n * - PlasmaFrobeniusNorm: 2*A.mt*A.nt * * @param[out] value * The calculated value of the norm requested. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). * * @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_zlanhe * @sa plasma_omp_clanhe * ******************************************************************************/ void plasma_omp_zlanhe(plasma_enum_t norm, plasma_enum_t uplo, plasma_desc_t A, double *work, double *value, 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 ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) && (norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm)) { plasma_error("illegal value of norm"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid descriptor 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.m == 0) { *value = 0.0; return; } // Call the parallel function. plasma_pzlanhe(norm, uplo, A, work, value, sequence, request); }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 8; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/annotate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define DrawEpsilon (1.0e-10) #define MaxBezierCoordinates 2097152 #define ThrowPointExpectedException(image,token) \ { \ (void) ThrowMagickException(&(image)->exception,GetMagickModule(),DrawError, \ "NonconformingDrawingPrimitiveDefinition","`%s'",token); \ status=MagickFalse; \ break; \ } /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static Image *DrawClippingMask(Image *,const DrawInfo *,const char *,const char *, ExceptionInfo *); static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *); static PrimitiveInfo *TraceStrokePolygon(const Image *,const DrawInfo *,const PrimitiveInfo *); static size_t TracePath(Image *,PrimitiveInfo *,const char *); static void TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(PrimitiveInfo *,const size_t), TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo, PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*draw_info)); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); if (clone_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->compliance=draw_info->compliance; clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, &draw_info->fill_pattern->exception); else if (draw_info->tile != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->tile,0,0,MagickTrue, &draw_info->tile->exception); clone_info->tile=NewImageList(); /* tile is deprecated */ if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,&draw_info->stroke_pattern->exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= DrawEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL, sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; clone_info->fill_opacity=draw_info->fill_opacity; clone_info->stroke_opacity=draw_info->stroke_opacity; clone_info->element_reference=draw_info->element_reference; clone_info->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,&draw_info->clipping_mask->exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,&draw_info->composite_mask->exception); clone_info->render=draw_info->render; clone_info->debug=IsEventLogging(); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) % % A description of each parameter follows: % % o Method ConvertPathToPolygon returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int CompareEdges(const void *x,const void *y) { register const EdgeInfo *p, *q; /* Compare two edges. */ p=(const EdgeInfo *) x; q=(const EdgeInfo *) y; if ((p->points[0].y-DrawEpsilon) > q->points[0].y) return(1); if ((p->points[0].y+DrawEpsilon) < q->points[0].y) return(-1); if ((p->points[0].x-DrawEpsilon) > q->points[0].x) return(1); if ((p->points[0].x+DrawEpsilon) < q->points[0].x) return(-1); if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)- (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0) return(1); return(-1); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { register EdgeInfo *p; register ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; register ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; register ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) return((PolygonInfo *) NULL); number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); (void) memset(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) memset(&point,0,sizeof(point)); (void) memset(&bounds,0,sizeof(bounds)); polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=0.0; polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) direction; polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->number_edges=0; for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < DrawEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; ghostline=MagickFalse; edge++; } } polygon_info->number_edges=edge; qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),CompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o Method ConvertPrimitiveToPath returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % % */ static void LogPathInfo(const PathInfo *path_info) { register const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath( const DrawInfo *magick_unused(draw_info),const PrimitiveInfo *primitive_info) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; register ssize_t i, n; ssize_t coordinates, start; magick_unreferenced(draw_info); /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case PointPrimitive: case ColorPrimitive: case MattePrimitive: case TextPrimitive: case ImagePrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (3UL*i+1UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) return((PathInfo *) NULL); coordinates=0; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { /* New subpath. */ coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; closed_subpath=primitive_info[i].closed_subpath; } coordinates--; if ((code == MoveToCode) || (coordinates <= 0) || (fabs(q.x-primitive_info[i].point.x) >= DrawEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= DrawEpsilon)) { /* Eliminate duplicate points. */ path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; /* next point in current subpath */ if (closed_subpath != MagickFalse) { closed_subpath=MagickFalse; continue; } /* Mark the p point as open if the subpath is not closed. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->tile != (Image *) NULL) draw_info->tile=DestroyImage(draw_info->tile); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask); if (draw_info->composite_mask != (Image *) NULL) draw_info->composite_mask=DestroyImage(draw_info->composite_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y E d g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyEdge() destroys the specified polygon edge. % % The format of the DestroyEdge method is: % % ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % % o edge: the polygon edge number to destroy. % */ static size_t DestroyEdge(PolygonInfo *polygon_info, const size_t edge) { assert(edge < polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < polygon_info->number_edges) (void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P o l y g o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPolygonInfo() destroys the PolygonInfo data structure. % % The format of the DestroyPolygonInfo method is: % % PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { register ssize_t i; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges); return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; register double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= DrawEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -DrawEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= DrawEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -DrawEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; ExceptionInfo *exception; MagickBooleanType status; MagickPixelPacket zero; PointInfo extent[4], min, max, point; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetMagickPixelPacket(image,&zero); exception=(&image->exception); start=(ssize_t) ceil(edge.y1-0.5); stop=(ssize_t) floor(edge.y2+0.5); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,image,stop-start,1) #endif for (y=start; y <= stop; y++) { MagickPixelPacket composite, pixel; PointInfo point; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1- 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1), 1,exception); if (q == (PixelPacket *) NULL) continue; indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; composite=zero; x_offset=0; for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; status=InterpolateMagickPixelPacket(source,source_view, UndefinedInterpolatePixel,point.x,point.y,&pixel,exception); if (status == MagickFalse) break; SetMagickPixelPacket(image,q,indexes+x_offset,&composite); MagickPixelCompositeOver(&pixel,pixel.opacity,&composite, composite.opacity,&composite); SetPixelPacket(image,&composite,q,indexes+x_offset); x_offset++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, % PolygonInfo *polygon_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % */ static inline double SaneStrokeWidth(const Image *image, const DrawInfo *draw_info) { return(MagickMin((double) draw_info->stroke_width, (2.0*sqrt(2.0)+DrawEpsilon)*MagickMax(image->columns,image->rows))); } static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, const PolygonInfo *polygon_info) { double mid; DrawInfo *clone_info; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register ssize_t i; SegmentInfo bounds; ssize_t coordinates; (void) memset(primitive_info,0,sizeof(primitive_info)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) QueryColorDatabase("#0000",&clone_info->fill,&image->exception); resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)* SaneStrokeWidth(image,clone_info)/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) (void) QueryColorDatabase("red",&clone_info->stroke, &image->exception); else (void) QueryColorDatabase("green",&clone_info->stroke, &image->exception); start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info); } } (void) QueryColorDatabase("blue",&clone_info->stroke,&image->exception); start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *id) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the id of the clip path. % */ static char *GetNodeByURL(const char *,const char *); MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *id) { const char *clip_path; Image *clipping_mask; MagickBooleanType status; clip_path=GetImageArtifact(image,id); if (clip_path == (const char *) NULL) return(MagickFalse); clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path, &image->exception); if (clipping_mask == (Image *) NULL) return(MagickFalse); status=SetImageClipMask(image,clipping_mask); clipping_mask=DestroyImage(clipping_mask); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p p i n g M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClippingMask() draws the clip path and returns it as an image clipping % mask. % % The format of the DrawClippingMask method is: % % Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *clip_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o clip_path: the clip path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, const char *id,const char *clip_path,ExceptionInfo *exception) { DrawInfo *clone_info; Image *clip_mask; MagickStatusType status; /* Draw a clip path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return((Image *) NULL); (void) SetImageClipMask(image,(Image *) NULL); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,clip_path); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); if (clone_info->clip_mask != (char *) NULL) clone_info->clip_mask=DestroyString(clone_info->clip_mask); (void) QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->opacity=OpaqueOpacity; clone_info->clip_path=MagickTrue; status=DrawImage(clip_mask,clone_info); clone_info=DestroyDrawInfo(clone_info); status&=SeparateImageChannel(clip_mask,TrueAlphaChannel); status&=NegateImage(clip_mask,MagickFalse); if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(clip_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C o m p o s i t e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawCompositeMask() draws the mask path and returns it as an image mask. % % The format of the DrawCompositeMask method is: % % Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *mask_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the mask path id. % % o mask_path: the mask path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, const char *id,const char *mask_path,ExceptionInfo *exception) { Image *composite_mask; DrawInfo *clone_info; MagickStatusType status; /* Draw a mask path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); composite_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (composite_mask == (Image *) NULL) return((Image *) NULL); (void) SetImageMask(image,(Image *) NULL); (void) QueryColorCompliance("#0000",AllCompliance, &composite_mask->background_color,exception); composite_mask->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,mask_path); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); (void) QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->opacity=OpaqueOpacity; status=DrawImage(composite_mask,clone_info); clone_info=DestroyDrawInfo(clone_info); status&=SeparateImageChannel(composite_mask,TrueAlphaChannel); status&=NegateImage(composite_mask,MagickFalse); if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path"); return(composite_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image) { double length, maximum_length, offset, scale, total_length; DrawInfo *clone_info; MagickStatusType status; PrimitiveInfo *dash_polygon; register double dx, dy; register ssize_t i; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+32UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); (void) memset(dash_polygon,0,(2UL*number_vertices+32UL)* sizeof(*dash_polygon)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=fabs(draw_info->dash_offset) >= DrawEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > MaxBezierCoordinates) break; if (fabs(length) < DrawEpsilon) { n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon); } n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=DrawEpsilon; dash_polygon[j].point.y+=DrawEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image: the image. % % o _info: the draw info. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.x); v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.y); return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; ExceptionInfo *exception; MagickBooleanType status; MagickPixelPacket zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; exception=(&image->exception); GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,bounding_box.height-bounding_box.y,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { double alpha, offset; MagickPixelPacket composite, pixel; register IndexPacket *magick_restrict indexes; register ssize_t i, x; register PixelPacket *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { double repeat; MagickBooleanType antialias; antialias=MagickFalse; repeat=0.0; if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=PerceptibleReciprocal(length)*repeat; } else { repeat=fmod(offset,(double) gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat, (double) gradient->radius); else repeat=fmod(offset,(double) gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat/gradient->radius; } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } MagickPixelCompositeOver(&composite,composite.opacity,&pixel, pixel.opacity,&pixel); SetPixelPacket(image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % */ static char *GetNodeByURL(const char *primitive,const char *url) { char *token; const char *q, *start; register const char *p; size_t extent, length; ssize_t n; /* Find and return node by ID. */ if (primitive == (const char *) NULL) return((char *) NULL); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; length=0; n=0; start=(const char *) NULL; p=(const char *) NULL; for (q=primitive; (*q != '\0') && (length == 0); ) { p=q; GetNextToken(q,&q,extent,token); if (*token == '\0') break; if (*token == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } if (LocaleCompare("pop",token) == 0) { GetNextToken(q,&q,extent,token); if ((n == 0) && (start != (const char *) NULL)) { /* End of node by ID. */ length=(size_t) (p-start+1); break; } n--; } if (LocaleCompare("push",token) == 0) { GetNextToken(q,&q,extent,token); n++; if (*q == '"') { GetNextToken(q,&q,extent,token); if (LocaleCompare(url,token) == 0) { /* Start of node by ID. */ n=0; start=q; } } } } if (start == (const char *) NULL) return(DestroyString(token)); (void) CopyMagickString(token,start,length); return(token); } static size_t ReckonEllipseCoordinates(const PointInfo radii, const PointInfo arc) { double delta, step, y; PointInfo angle; /* Ellipses are just short segmented polys. */ if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon)) return(0); delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/(4.0*(MagickPI*PerceptibleReciprocal(delta)/2.0)); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); return((size_t) floor((angle.y-angle.x)/step+0.5)+3); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(point,&p); return((fabs(value) < DrawEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static size_t ReckonRoundRectangleCoordinates(const PointInfo start, const PointInfo end,PointInfo arc) { PointInfo degrees, offset; size_t coordinates; offset.x=fabs(end.x-start.x); offset.y=fabs(end.y-start.y); if ((offset.x < DrawEpsilon) || (offset.y < DrawEpsilon)) return(0); coordinates=0; if (arc.x > (0.5*offset.x)) arc.x=0.5*offset.x; if (arc.y > (0.5*offset.y)) arc.y=0.5*offset.y; degrees.x=270.0; degrees.y=360.0; coordinates+=ReckonEllipseCoordinates(arc,degrees); degrees.x=0.0; degrees.y=90.0; coordinates+=ReckonEllipseCoordinates(arc,degrees); degrees.x=90.0; degrees.y=180.0; coordinates+=ReckonEllipseCoordinates(arc,degrees); degrees.x=180.0; degrees.y=270.0; coordinates+=ReckonEllipseCoordinates(arc,degrees); return(coordinates+1); } static inline void TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->closed_subpath=MagickFalse; primitive_info->point=point; } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char key[2*MaxTextExtent], keyword[MaxTextExtent], geometry[MaxTextExtent], name[MaxTextExtent], *next_token, pattern[MaxTextExtent], *primitive, *token; const char *q; double angle, factor, primitive_extent; DrawInfo **graphic_context; MagickBooleanType proceed; MagickSizeType number_points; MagickStatusType status; PointInfo point; PixelPacket start_color; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t coordinates, extent; ssize_t defsDepth, j, k, n, symbolDepth; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); primitive=(char *) NULL; if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else if ((strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-')) primitive=FileToString(draw_info->primitive+1,~0UL,&image->exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=4096; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(primitive_info,0,(size_t) number_points* sizeof(*primitive_info)); graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MaxTextExtent; (void) QueryColorDatabase("#000000",&start_color,&image->exception); defsDepth=0; symbolDepth=0; status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetNextToken(q,&q,MaxTextExtent,keyword); if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { GetNextToken(q,&q,extent,token); status&=QueryColorDatabase(token,&graphic_context[n]->border_color, &image->exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { char *clip_path; /* Take a node from within the MVG document, and duplicate it here. */ GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } clip_path=GetNodeByURL(primitive,token); if (clip_path != (char *) NULL) { if (graphic_context[n]->clipping_mask != (Image *) NULL) graphic_context[n]->clipping_mask= DestroyImage(graphic_context[n]->clipping_mask); graphic_context[n]->clipping_mask=DrawClippingMask(image, graphic_context[n],token,clip_path,&image->exception); clip_path=DestroyString(clip_path); if (draw_info->compliance != SVGCompliance) (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask); } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } if (LocaleCompare("compliance",keyword) == 0) { /* MVG compliance associates a clipping mask with an image; SVG compliance associates a clipping mask with a graphics context. */ GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern); else { status&=QueryColorDatabase(token,&graphic_context[n]->fill, &image->exception); if (graphic_context[n]->fill_opacity != OpaqueOpacity) graphic_context[n]->fill.opacity=(Quantum) graphic_context[n]->fill_opacity; } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { double opacity; GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(image,token); graphic_context[n]->fill_opacity=QuantumRange*(1.0-opacity); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) { status=MagickFalse; break; } graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) { status=MagickFalse; break; } graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) { status=MagickFalse; break; } graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) { status=MagickFalse; break; } graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("mask",keyword) == 0) { char *mask_path; /* Take a node from within the MVG document, and duplicate it here. */ GetNextToken(q,&q,extent,token); mask_path=GetNodeByURL(primitive,token); if (mask_path != (char *) NULL) { if (graphic_context[n]->composite_mask != (Image *) NULL) graphic_context[n]->composite_mask= DestroyImage(graphic_context[n]->composite_mask); graphic_context[n]->composite_mask=DrawCompositeMask(image, graphic_context[n],token,mask_path,&image->exception); mask_path=DestroyString(mask_path); if (draw_info->compliance != SVGCompliance) status=SetImageMask(image,graphic_context[n]->composite_mask); } break; } if (LocaleCompare("matte",keyword) == 0) { primitive_type=MattePrimitive; break; } status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->opacity=(Quantum) (QuantumRange-QuantumRange* ((1.0-QuantumScale*graphic_context[n]->opacity)*factor* StringToDouble(token,&next_token))); graphic_context[n]->fill_opacity=QuantumRange-QuantumRange*((1.0- QuantumScale*graphic_context[n]->fill_opacity)*factor* StringToDouble(token,&next_token)); graphic_context[n]->stroke_opacity=QuantumRange-QuantumRange*((1.0- QuantumScale*graphic_context[n]->stroke_opacity)*factor* StringToDouble(token,&next_token)); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) { defsDepth--; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),DrawError, "UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if ((graphic_context[n]->clip_mask != (char *) NULL) && (draw_info->compliance != SVGCompliance)) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageClipMask(image,(Image *) NULL); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("mask",token) == 0) break; if (LocaleCompare("pattern",token) == 0) break; if (LocaleCompare("symbol",token) == 0) { symbolDepth--; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) { char *clip_path, name[MaxTextExtent]; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MaxTextExtent,"%s",token); clip_path=GetNodeByURL(primitive,name); (void) SetImageArtifact(image,name,clip_path); break; } if (LocaleCompare("defs",token) == 0) { defsDepth++; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MaxTextExtent], name[MaxTextExtent], type[MaxTextExtent]; SegmentInfo segment; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MaxTextExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MaxTextExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } if ((size_t) (q-p-4+1) <= 0) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(&image->exception, GetMagickModule(),ResourceLimitError, "MemoryAllocationFailed","`%s'",image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); if (*q == '"') GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("mask",token) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { RectangleInfo bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MaxTextExtent); GetNextToken(q,&q,extent,token); bounds.x=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.y=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.width=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.height=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(image,token); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } if ((size_t) (q-p-4+1) <= 0) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("symbol",token) == 0) { symbolDepth++; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { GradientType type; PixelPacket stop_color; GetNextToken(q,&q,extent,token); status&=QueryColorDatabase(token,&stop_color,&image->exception); type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,&start_color,&stop_color); start_color=stop_color; GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke",keyword) == 0) { GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern); else { status&=QueryColorDatabase(token,&graphic_context[n]->stroke, &image->exception); if (graphic_context[n]->stroke_opacity != OpaqueOpacity) graphic_context[n]->stroke.opacity=(Quantum) graphic_context[n]->stroke_opacity; } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *p; p=q; GetNextToken(p,&p,extent,token); if (*token == ',') GetNextToken(p,&p,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(p,&p,extent,token); if (*token == ',') GetNextToken(p,&p,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+2UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(&image->exception, GetMagickModule(),ResourceLimitError, "MemoryAllocationFailed","`%s'",image->filename); status=MagickFalse; break; } (void) memset(graphic_context[n]->dash_pattern,0,(size_t) (2UL*x+2UL)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(image,token); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) { status=MagickFalse; break; } graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) { status=MagickFalse; break; } graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(image,token); graphic_context[n]->stroke_opacity=QuantumRange*(1.0-opacity); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); status&=QueryColorDatabase(token,&graphic_context[n]->undercolor, &image->exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } case 'u': case 'U': { if (LocaleCompare("use",keyword) == 0) { char *node; /* Get a node from the MVG document, and "use" it here. */ GetNextToken(q,&q,extent,token); node=GetNodeByURL(primitive,token); if (node != (char *) NULL) { DrawInfo *clone_info; clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); (void) CloneString(&clone_info->primitive,node); node=DestroyString(node); status=DrawImage(image,clone_info); clone_info=DestroyDrawInfo(clone_info); } break; } break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) ThrowPointExpectedException(image,token); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= DrawEpsilon) || (fabs(affine.rx) >= DrawEpsilon) || (fabs(affine.ry) >= DrawEpsilon) || (fabs(affine.sy-1.0) >= DrawEpsilon) || (fabs(affine.tx) >= DrawEpsilon) || (fabs(affine.ty) >= DrawEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; primitive_info[0].coordinates=0; primitive_info[0].method=FloodfillMethod; primitive_info[0].closed_subpath=MagickFalse; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; primitive_info[i].closed_subpath=MagickFalse; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; if (number_points != (MagickSizeType) ((size_t) number_points)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points+4096,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (status == MagickFalse) break; primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; primitive_info[j].text=(char *) NULL; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ coordinates=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { coordinates*=5; break; } case RoundRectanglePrimitive: { coordinates=ReckonRoundRectangleCoordinates(primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) { (void) ThrowMagickException(&image->exception,GetMagickModule(), DrawError,"TooManyBezierCoordinates","`%s'",token); status=MagickFalse; break; } coordinates=(BezierQuantum*primitive_info[j].coordinates); break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); coordinates=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } coordinates++; } coordinates*=(6*BezierQuantum)+360.0; break; } case CirclePrimitive: { double alpha, beta, radius; PointInfo offset, degrees; alpha=primitive_info[j+1].point.x-primitive_info[j].point.x; beta=primitive_info[j+1].point.y-primitive_info[j].point.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; coordinates=ReckonEllipseCoordinates(offset,degrees); break; } case ArcPrimitive: { PointInfo center, radii; if ((primitive_info[j+2].point.x < -360.0) || (primitive_info[j+2].point.x > 360.0) || (primitive_info[j+2].point.y < -360.0) || (primitive_info[j+2].point.y > 360.0)) ThrowPointExpectedException(image,token); center.x=0.5*(primitive_info[j+1].point.x+primitive_info[j].point.x); center.y=0.5*(primitive_info[j+1].point.y+primitive_info[j].point.y); radii.x=fabs(center.x-primitive_info[j].point.x); radii.y=fabs(center.y-primitive_info[j].point.y); coordinates=ReckonEllipseCoordinates(radii,primitive_info[j+2].point); break; } case EllipsePrimitive: { if ((primitive_info[j+2].point.x < -360.0) || (primitive_info[j+2].point.x > 360.0) || (primitive_info[j+2].point.y < -360.0) || (primitive_info[j+2].point.y > 360.0)) ThrowPointExpectedException(image,token); coordinates=ReckonEllipseCoordinates(primitive_info[j+1].point, primitive_info[j+2].point); break; } default: break; } if (coordinates > MaxBezierCoordinates) { (void) ThrowMagickException(&image->exception,GetMagickModule(), DrawError,"TooManyBezierCoordinates","`%s'",token); status=MagickFalse; } if (status == MagickFalse) break; if ((MagickSizeType) (i+coordinates) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=coordinates+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points+4096,sizeof(*primitive_info)); if ((primitive_info == (PrimitiveInfo *) NULL) || (number_points != (MagickSizeType) ((size_t) number_points))) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+2].point.x < 0.0) || (primitive_info[j+2].point.y < 0.0)) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0) { status=MagickFalse; break; } if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0) { status=MagickFalse; break; } TraceRoundRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } TraceArc(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x < 0.0) || (primitive_info[j+1].point.y < 0.0)) { status=MagickFalse; break; } TraceEllipse(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: { if (primitive_info[j].coordinates < 1) { status=MagickFalse; break; } break; } case PolygonPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; primitive_info[j].closed_subpath=MagickTrue; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { coordinates=TracePath(image,primitive_info+j,token); if (coordinates == 0) { status=MagickFalse; break; } i=(ssize_t) (j+coordinates); break; } case ColorPrimitive: case MattePrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (draw_info->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask); status&=DrawPrimitive(image,graphic_context[n],primitive_info); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern) { char property[MaxTextExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MaxTextExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MaxTextExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info); image_info=DestroyImageInfo(image_info); (void) QueryColorDatabase("#00000000",&(*pattern)->background_color, &image->exception); (void) SetImageBackgroundColor(*pattern); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill_pattern=NewImageList(); clone_info->stroke_pattern=NewImageList(); (void) FormatLocaleString(property,MaxTextExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=DrawImage(*pattern,clone_info); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { register ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) return((PolygonInfo **) NULL); (void) memset(polygon_info,0,(size_t) GetMagickResourceLimit(ThreadResource)*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(draw_info,primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static double GetOpacityPixel(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_opacity) { double alpha, beta, distance, subpath_opacity; PointInfo delta; register EdgeInfo *p; register const PointInfo *q; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_opacity=0.0; subpath_opacity=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,(size_t) j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta <= 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta >= alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=PerceptibleReciprocal(alpha); beta=delta.x*(y-q->y)-delta.y*(x-q->x); distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_opacity < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_opacity=1.0; else { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_opacity < ((alpha-0.25)*(alpha-0.25))) *stroke_opacity=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_opacity >= 1.0)) continue; if (distance <= 0.0) { subpath_opacity=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < DrawEpsilon) { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_opacity < (alpha*alpha)) subpath_opacity=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_opacity >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) (p->number_points-1); i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_opacity); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { CacheView *image_view; double mid; ExceptionInfo *exception; MagickBooleanType fill, status; PolygonInfo **magick_restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates <= 1) return(MagickTrue); /* Compute bounding box. */ polygon_info=AcquirePolygonThreadSet(draw_info,primitive_info); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); DisableMSCWarning(4127) if (0) DrawBoundingRectangles(image,draw_info,polygon_info[0]); RestoreMSCWarning if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; bounds=polygon_info[0]->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.y1-=(mid+1.0); bounds.x2+=(mid+1.0); bounds.y2+=(mid+1.0); if ((bounds.x1 >= (double) image->columns) || (bounds.y1 >= (double) image->rows) || (bounds.x2 <= 0.0) || (bounds.y2 <= 0.0)) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(MagickTrue); /* virtual polygon */ } bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x1; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y1; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x2; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y2; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for ( ; x <= stop_x; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) (void) GetFillColor(draw_info,x-start_x,y-start_y,q); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); double fill_opacity, stroke_opacity; PixelPacket fill_color, stroke_color; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { /* Fill and/or stroke. */ fill_opacity=GetOpacityPixel(polygon_info[id],mid,fill, draw_info->fill_rule,x,y,&stroke_opacity); if (draw_info->stroke_antialias == MagickFalse) { fill_opacity=fill_opacity > 0.25 ? 1.0 : 0.0; stroke_opacity=stroke_opacity > 0.25 ? 1.0 : 0.0; } (void) GetFillColor(draw_info,x-start_x,y-start_y,&fill_color); fill_opacity=(double) (QuantumRange-fill_opacity*(QuantumRange- fill_color.opacity)); MagickCompositeOver(&fill_color,(MagickRealType) fill_opacity,q, (MagickRealType) q->opacity,q); (void) GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color); stroke_opacity=(double) (QuantumRange-stroke_opacity*(QuantumRange- stroke_color.opacity)); MagickCompositeOver(&stroke_color,(MagickRealType) stroke_opacity,q, (MagickRealType) q->opacity,q); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % */ static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, q, point; register ssize_t i, x; ssize_t coordinates, y; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); switch (primitive_info->primitive) { case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case MattePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "MattePrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= DrawEpsilon) || (fabs(q.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= DrawEpsilon) || (fabs(p.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { CacheView *image_view; ExceptionInfo *exception; MagickStatusType status; register ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } exception=(&image->exception); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelGray(&draw_info->fill) == MagickFalse) || (IsPixelGray(&draw_info->stroke) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace); status=MagickTrue; if (draw_info->compliance == SVGCompliance) { status=SetImageClipMask(image,draw_info->clipping_mask); status&=SetImageMask(image,draw_info->composite_mask); } x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case PointPrimitive: { PixelPacket fill_color; PixelPacket *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,&fill_color); MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q, (MagickRealType) q->opacity,q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelPacket *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelPacket target; status&=GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) == MagickFalse) { q++; continue; } (void) GetFillColor(draw_info,x,y,q); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { MagickPixelPacket target; (void) GetOneVirtualMagickPixel(image,x,y,&target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(MagickRealType) draw_info->border_color.red; target.green=(MagickRealType) draw_info->border_color.green; target.blue=(MagickRealType) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,DefaultChannels,draw_info,&target,x, y,primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue); break; } case ResetMethod: { MagickBooleanType sync; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) GetFillColor(draw_info,x,y,q); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case MattePrimitive: { if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); switch (primitive_info->method) { case PointMethod: default: { PixelPacket pixel; PixelPacket *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelPacket pixel, target; status&=GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) == MagickFalse) { q++; continue; } (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { MagickPixelPacket target; (void) GetOneVirtualMagickPixel(image,x,y,&target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(MagickRealType) draw_info->border_color.red; target.green=(MagickRealType) draw_info->border_color.green; target.blue=(MagickRealType) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,OpacityChannel,draw_info,&target,x, y,primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue); break; } case ResetMethod: { MagickBooleanType sync; PixelPacket pixel; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case TextPrimitive: { char geometry[MaxTextExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info); clone_info=DestroyDrawInfo(clone_info); break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MaxTextExtent]; Image *composite_image; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_image=ReadInlineImage(clone_info,primitive_info->text, &image->exception); else { (void) CopyMagickString(clone_info->filename,primitive_info->text, MaxTextExtent); composite_image=ReadImage(clone_info,&image->exception); } clone_info=DestroyImageInfo(clone_info); if (composite_image == (Image *) NULL) break; (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=(ssize_t) ceil(primitive_info[1].point.x-0.5); y1=(ssize_t) ceil(primitive_info[1].point.y-0.5); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { char geometry[MaxTextExtent]; /* Resize image. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g!", primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL,geometry); } if (composite_image->matte == MagickFalse) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel); if (draw_info->opacity != OpaqueOpacity) (void) SetImageOpacity(composite_image,draw_info->opacity); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry, &image->exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if ((draw_info->compose == OverCompositeOp) || (draw_info->compose == SrcOverCompositeOp)) (void) DrawAffineImage(image,composite_image,&affine); else (void) CompositeImage(image,draw_info->compose,composite_image, geometry.x,geometry.y); composite_image=DestroyImage(composite_image); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= DrawEpsilon) && (fabs(scale*draw_info->stroke_width) >= DrawEpsilon) && (draw_info->stroke.opacity != (Quantum) TransparentOpacity)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.opacity=(Quantum) TransparentOpacity; status&=DrawPolygonPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); (void) DrawDashPolygon(draw_info,primitive_info,image); break; } mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; if ((mid > 1.0) && ((draw_info->stroke.opacity != (Quantum) TransparentOpacity) || (draw_info->stroke_pattern != (Image *) NULL))) { MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; closed_path=primitive_info[0].closed_subpath; i=(ssize_t) primitive_info[0].coordinates; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.opacity=(Quantum) TransparentOpacity; status&=DrawPolygonPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); status&=DrawStrokePolygon(image,draw_info,primitive_info); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info); break; } } image_view=DestroyCacheView(image_view); if (draw_info->compliance == SVGCompliance) { status&=SetImageClipMask(image,(Image *) NULL); status&=SetImageMask(image,(Image *) NULL); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { PrimitiveInfo linecap[5]; register ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*DrawEpsilon; linecap[2].point.x+=2.0*DrawEpsilon; linecap[2].point.y+=2.0*DrawEpsilon; linecap[3].point.y+=2.0*DrawEpsilon; linecap[4].primitive=UndefinedPrimitive; (void) DrawPolygonPrimitive(image,draw_info,linecap); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; register const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,&clone_info->stroke_pattern->exception); clone_info->stroke.opacity=(Quantum) TransparentOpacity; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { if (p->coordinates == 1) continue; stroke_polygon=TraceStrokePolygon(image,draw_info,p); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); break; } status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); if (status == 0) break; q=p+p->coordinates-1; closed_path=p->closed_subpath; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { DrawRoundLinecap(image,draw_info,p); DrawRoundLinecap(image,draw_info,q); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) memset(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) memset(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorDatabase("#000F",&draw_info->fill,exception); (void) QueryColorDatabase("#FFF0",&draw_info->stroke,exception); draw_info->stroke_antialias=clone_info->antialias; draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->fill_opacity=OpaqueOpacity; draw_info->stroke_opacity=OpaqueOpacity; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; draw_info->pointsize=12.0; if (fabs(clone_info->pointsize) >= DrawEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->undercolor.opacity=(Quantum) TransparentOpacity; draw_info->border_color=clone_info->border_color; draw_info->compose=OverCompositeOp; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); draw_info->render=MagickTrue; draw_info->clip_path=MagickFalse; draw_info->debug=IsEventLogging(); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->fill,exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->stroke,exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->undercolor,exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; register ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo arc) { PointInfo center, radius; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radius.x=fabs(center.x-start.x); radius.y=fabs(center.y-start.y); TraceEllipse(primitive_info,center,radius,arc); } static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; PointInfo center, points[3], radii; register double cosine, sine; register PrimitiveInfo *p; register ssize_t i; size_t arc_segments; if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { TracePoint(primitive_info,end); return; } radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon)) { TraceLine(primitive_info,start,end); return; } cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < DrawEpsilon) { TraceLine(primitive_info,start,end); return; } if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+DrawEpsilon)))); p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; TraceBezier(p,4); p+=p->coordinates; } primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceBezier(PrimitiveInfo *primitive_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=(size_t) MagickMin((double) quantum/number_coordinates, (double) BezierQuantum); control_points=quantum*number_coordinates; coefficients=(double *) AcquireQuantumMemory((size_t) number_coordinates,sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory((size_t) control_points, sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { TracePoint(p,points[i]); p+=p->coordinates; } TracePoint(p,end); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); } static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; TraceEllipse(primitive_info,start,offset,degrees); } static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo center, const PointInfo radii,const PointInfo arc) { double delta, step, x, y; PointInfo angle, point; register PrimitiveInfo *p; register ssize_t i; /* Ellipses are just short segmented polys. */ primitive_info->coordinates=0; if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon)) return; delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/(4.0*(MagickPI*PerceptibleReciprocal(delta)/2.0)); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y; TracePoint(p,point); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y; TracePoint(p,point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; x=fabs(primitive_info[0].point.x- primitive_info[primitive_info->coordinates-1].point.x); y=fabs(primitive_info[0].point.y- primitive_info[primitive_info->coordinates-1].point.y); if ((x <= DrawEpsilon) && (y <= DrawEpsilon)) primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { TracePoint(primitive_info,start); if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return; } TracePoint(primitive_info+1,end); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; primitive_info->closed_subpath=MagickFalse; } static size_t TracePath(Image *image,PrimitiveInfo *primitive_info, const char *path) { char *next_token, token[MaxTextExtent]; const char *p; double x, y; int attribute, last_attribute; MagickBooleanType status; PointInfo end = {0.0, 0.0}, points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; status=MagickTrue; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { if (status == MagickFalse) break; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle = 0.0; MagickBooleanType large_arc = MagickFalse, sweep = MagickFalse; PointInfo arc = {0.0, 0.0}; /* Elliptical arc. */ do { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arc.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arc.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); TraceArcPath(q,point,end,arc,angle,large_arc,sweep); q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Cubic Bézier curve. */ do { points[0]=point; for (i=1; i < 4; i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); TracePoint(q,point); q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { /* Line to. */ do { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { /* Move to. */ if (q != primitive_info) { primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; } i=0; do { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; TracePoint(q,point); q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Quadratic Bézier curve. */ do { points[0]=point; for (i=1; i < 3; i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Cubic Bézier curve. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Quadratic Bézier curve. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (status == MagickFalse) break; if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { /* Line to. */ do { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(image,token); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { /* Close path. */ point=start; TracePoint(q,point); q+=q->coordinates; primitive_info->coordinates=(size_t) (q-primitive_info); primitive_info->closed_subpath=MagickTrue; number_coordinates+=primitive_info->coordinates; primitive_info=q; z_count++; break; } default: { ThrowPointExpectedException(image,token); break; } } } if (status == MagickFalse) return(0); primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return(number_coordinates); } static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; if ((fabs(start.x-end.x) < DrawEpsilon) || (fabs(start.y-end.y) < DrawEpsilon)) { primitive_info->coordinates=0; return; } p=primitive_info; TracePoint(p,start); p+=p->coordinates; point.x=start.x; point.y=end.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,end); p+=p->coordinates; point.x=end.x; point.y=start.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,start); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceRoundRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, offset, point; register PrimitiveInfo *p; register ssize_t i; offset.x=fabs(end.x-start.x); offset.y=fabs(end.y-start.y); if ((offset.x < DrawEpsilon) || (offset.y < DrawEpsilon)) { primitive_info->coordinates=0; return; } p=primitive_info; if (arc.x > (0.5*offset.x)) arc.x=0.5*offset.x; if (arc.y > (0.5*offset.y)) arc.y=0.5*offset.y; point.x=start.x+offset.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+offset.x-arc.x; point.y=start.y+offset.y-arc.y; degrees.x=0.0; degrees.y=90.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+offset.y-arc.y; degrees.x=90.0; degrees.y=180.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; TracePoint(p,primitive_info->point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; register double dx, dy; register ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); } static PrimitiveInfo *TraceStrokePolygon(const Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { #define CheckPathExtent(pad) \ if ((q+(pad)) >= (ssize_t) max_strokes) \ { \ if (~max_strokes < (pad)) \ { \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ } \ else \ { \ max_strokes+=(pad); \ path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, \ sizeof(*path_p)); \ path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, \ sizeof(*path_q)); \ } \ if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) \ { \ if (path_p != (PointInfo *) NULL) \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ if (path_q != (PointInfo *) NULL) \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx = {0,0}, dy = {0,0}, inverse_slope = {0,0}, slope = {0,0}, theta = {0,0}; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) return((PrimitiveInfo *) NULL); (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); closed_path=primitive_info[0].closed_subpath; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= DrawEpsilon) || (fabs(dy.p) >= DrawEpsilon)) break; } if (n == (ssize_t) number_vertices) { if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse)) { /* Zero length subpath. */ stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory( sizeof(*stroke_polygon)); stroke_polygon[0]=polygon_primitive[0]; stroke_polygon[0].coordinates=0; polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } n=(ssize_t) number_vertices-1L; } path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); if (path_p == (PointInfo *) NULL) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return((PrimitiveInfo *) NULL); } path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); if (path_q == (PointInfo *) NULL) { path_p=(PointInfo *) RelinquishMagickMemory(path_p); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return((PrimitiveInfo *) NULL); } slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < DrawEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.p=dy.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.p) < DrawEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < DrawEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.q=dy.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.q) < DrawEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < DrawEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } CheckPathExtent(6*BezierQuantum+360); dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
GB_unaryop__lnot_fp64_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_fp64_uint16 // op(A') function: GB_tran__lnot_fp64_uint16 // C type: double // A type: uint16_t // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ double z = (double) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_uint16 ( double *Cx, // Cx and Ax may be aliased uint16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_fp64_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
dataset.h
#ifndef LIGHTGBM_DATASET_H_ #define LIGHTGBM_DATASET_H_ #include <LightGBM/utils/random.h> #include <LightGBM/utils/text_reader.h> #include <LightGBM/utils/openmp_wrapper.h> #include <LightGBM/meta.h> #include <LightGBM/config.h> #include <LightGBM/feature_group.h> #include <vector> #include <utility> #include <functional> #include <string> #include <unordered_set> #include <mutex> namespace LightGBM { /*! \brief forward declaration */ class DatasetLoader; /*! * \brief This class is used to store some meta(non-feature) data for training data, * e.g. labels, weights, initial scores, query level information. * * Some details: * 1. Label, used for training. * 2. Weights, weighs of records, optional * 3. Query Boundaries, necessary for lambdarank. * The documents of i-th query is in [ query_boundarise[i], query_boundarise[i+1] ) * 4. Query Weights, auto calculate by weights and query_boundarise(if both of them are existed) * the weight for i-th query is sum(query_boundarise[i] , .., query_boundarise[i+1]) / (query_boundarise[i + 1] - query_boundarise[i+1]) * 5. Initial score. optional. if existng, the model will boost from this score, otherwise will start from 0. */ class Metadata { public: /*! * \brief Null constructor */ Metadata(); /*! * \brief Initialization will load qurey level informations, since it is need for sampling data * \param data_filename Filename of data * \param init_score_filename Filename of initial score */ void Init(const char* data_filename, const char* initscore_file); /*! * \brief init as subset * \param metadata Filename of data * \param used_indices * \param num_used_indices */ void Init(const Metadata& metadata, const data_size_t* used_indices, data_size_t num_used_indices); /*! * \brief Initial with binary memory * \param memory Pointer to memory */ void LoadFromMemory(const void* memory); /*! \brief Destructor */ ~Metadata(); /*! * \brief Initial work, will allocate space for label, weight(if exists) and query(if exists) * \param num_data Number of training data * \param weight_idx Index of weight column, < 0 means doesn't exists * \param query_idx Index of query id column, < 0 means doesn't exists */ void Init(data_size_t num_data, int weight_idx, int query_idx); /*! * \brief Partition label by used indices * \param used_indices Indice of local used */ void PartitionLabel(const std::vector<data_size_t>& used_indices); /*! * \brief Partition meta data according to local used indices if need * \param num_all_data Number of total training data, including other machines' data on parallel learning * \param used_data_indices Indices of local used training data */ void CheckOrPartition(data_size_t num_all_data, const std::vector<data_size_t>& used_data_indices); void SetLabel(const label_t* label, data_size_t len); void SetWeights(const label_t* weights, data_size_t len); void SetQuery(const data_size_t* query, data_size_t len); /*! * \brief Set initial scores * \param init_score Initial scores, this class will manage memory for init_score. */ void SetInitScore(const double* init_score, data_size_t len); /*! * \brief Save binary data to file * \param file File want to write */ void SaveBinaryToFile(const VirtualFileWriter* writer) const; /*! * \brief Get sizes in byte of this object */ size_t SizesInByte() const; /*! * \brief Get pointer of label * \return Pointer of label */ inline const label_t* label() const { return label_.data(); } /*! * \brief Set label for one record * \param idx Index of this record * \param value Label value of this record */ inline void SetLabelAt(data_size_t idx, label_t value) { label_[idx] = value; } /*! * \brief Set Weight for one record * \param idx Index of this record * \param value Weight value of this record */ inline void SetWeightAt(data_size_t idx, label_t value) { weights_[idx] = value; } /*! * \brief Set Query Id for one record * \param idx Index of this record * \param value Query Id value of this record */ inline void SetQueryAt(data_size_t idx, data_size_t value) { queries_[idx] = static_cast<data_size_t>(value); } /*! * \brief Get weights, if not exists, will return nullptr * \return Pointer of weights */ inline const label_t* weights() const { if (!weights_.empty()) { return weights_.data(); } else { return nullptr; } } /*! * \brief Get data boundaries on queries, if not exists, will return nullptr * we assume data will order by query, * the interval of [query_boundaris[i], query_boundaris[i+1]) * is the data indices for query i. * \return Pointer of data boundaries on queries */ inline const data_size_t* query_boundaries() const { if (!query_boundaries_.empty()) { return query_boundaries_.data(); } else { return nullptr; } } /*! * \brief Get Number of queries * \return Number of queries */ inline data_size_t num_queries() const { return num_queries_; } /*! * \brief Get weights for queries, if not exists, will return nullptr * \return Pointer of weights for queries */ inline const label_t* query_weights() const { if (!query_weights_.empty()) { return query_weights_.data(); } else { return nullptr; } } /*! * \brief Get initial scores, if not exists, will return nullptr * \return Pointer of initial scores */ inline const double* init_score() const { if (!init_score_.empty()) { return init_score_.data(); } else { return nullptr; } } /*! * \brief Get size of initial scores */ inline int64_t num_init_score() const { return num_init_score_; } /*! \brief Disable copy */ Metadata& operator=(const Metadata&) = delete; /*! \brief Disable copy */ Metadata(const Metadata&) = delete; private: /*! \brief Load initial scores from file */ void LoadInitialScore(const char* initscore_file); /*! \brief Load wights from file */ void LoadWeights(); /*! \brief Load query boundaries from file */ void LoadQueryBoundaries(); /*! \brief Load query wights */ void LoadQueryWeights(); /*! \brief Filename of current data */ std::string data_filename_; /*! \brief Number of data */ data_size_t num_data_; /*! \brief Number of weights, used to check correct weight file */ data_size_t num_weights_; /*! \brief Label data */ std::vector<label_t> label_; /*! \brief Weights data */ std::vector<label_t> weights_; /*! \brief Query boundaries */ std::vector<data_size_t> query_boundaries_; /*! \brief Query weights */ std::vector<label_t> query_weights_; /*! \brief Number of querys */ data_size_t num_queries_; /*! \brief Number of Initial score, used to check correct weight file */ int64_t num_init_score_; /*! \brief Initial score */ std::vector<double> init_score_; /*! \brief Queries data */ std::vector<data_size_t> queries_; /*! \brief mutex for threading safe call */ std::mutex mutex_; bool weight_load_from_file_; bool query_load_from_file_; bool init_score_load_from_file_; }; /*! \brief Interface for Parser */ class Parser { public: /*! \brief virtual destructor */ virtual ~Parser() {} /*! * \brief Parse one line with label * \param str One line record, string format, should end with '\0' * \param out_features Output columns, store in (column_idx, values) * \param out_label Label will store to this if exists */ virtual void ParseOneLine(const char* str, std::vector<std::pair<int, double>>* out_features, double* out_label) const = 0; virtual int TotalColumns() const = 0; /*! * \brief Create a object of parser, will auto choose the format depend on file * \param filename One Filename of data * \param num_features Pass num_features of this data file if you know, <=0 means don't know * \param label_idx index of label column * \return Object of parser */ static Parser* CreateParser(const char* filename, bool header, int num_features, int label_idx); }; /*! \brief The main class of data set, * which are used for training or validation */ class Dataset { public: friend DatasetLoader; LIGHTGBM_EXPORT Dataset(); LIGHTGBM_EXPORT Dataset(data_size_t num_data); void Construct( std::vector<std::unique_ptr<BinMapper>>& bin_mappers, int** sample_non_zero_indices, const int* num_per_col, size_t total_sample_cnt, const Config& io_config); /*! \brief Destructor */ LIGHTGBM_EXPORT ~Dataset(); LIGHTGBM_EXPORT bool CheckAlign(const Dataset& other) const { if (num_features_ != other.num_features_) { return false; } if (num_total_features_ != other.num_total_features_) { return false; } if (label_idx_ != other.label_idx_) { return false; } for (int i = 0; i < num_features_; ++i) { if (!FeatureBinMapper(i)->CheckAlign(*(other.FeatureBinMapper(i)))) { return false; } } return true; } inline void PushOneRow(int tid, data_size_t row_idx, const std::vector<double>& feature_values) { if (is_finish_load_) { return; } for (size_t i = 0; i < feature_values.size() && i < static_cast<size_t>(num_total_features_); ++i) { int feature_idx = used_feature_map_[i]; if (feature_idx >= 0) { const int group = feature2group_[feature_idx]; const int sub_feature = feature2subfeature_[feature_idx]; feature_groups_[group]->PushData(tid, sub_feature, row_idx, feature_values[i]); } } } inline void PushOneRow(int tid, data_size_t row_idx, const std::vector<std::pair<int, double>>& feature_values) { if (is_finish_load_) { return; } for (auto& inner_data : feature_values) { if (inner_data.first >= num_total_features_) { continue; } int feature_idx = used_feature_map_[inner_data.first]; if (feature_idx >= 0) { const int group = feature2group_[feature_idx]; const int sub_feature = feature2subfeature_[feature_idx]; feature_groups_[group]->PushData(tid, sub_feature, row_idx, inner_data.second); } } } inline void PushOneData(int tid, data_size_t row_idx, int group, int sub_feature, double value) { feature_groups_[group]->PushData(tid, sub_feature, row_idx, value); } inline int RealFeatureIndex(int fidx) const { return real_feature_idx_[fidx]; } inline int InnerFeatureIndex(int col_idx) const { return used_feature_map_[col_idx]; } inline int Feature2Group(int feature_idx) const { return feature2group_[feature_idx]; } inline int Feture2SubFeature(int feature_idx) const { return feature2subfeature_[feature_idx]; } inline uint64_t GroupBinBoundary(int group_idx) const { return group_bin_boundaries_[group_idx]; } inline uint64_t NumTotalBin() const { return group_bin_boundaries_.back(); } inline std::vector<int> ValidFeatureIndices() const { std::vector<int> ret; for (int i = 0; i < num_total_features_; ++i) { if (used_feature_map_[i] >= 0) { ret.push_back(i); } } return ret; } void ReSize(data_size_t num_data); void CopySubset(const Dataset* fullset, const data_size_t* used_indices, data_size_t num_used_indices, bool need_meta_data); LIGHTGBM_EXPORT void FinishLoad(); LIGHTGBM_EXPORT bool SetFloatField(const char* field_name, const float* field_data, data_size_t num_element); LIGHTGBM_EXPORT bool SetDoubleField(const char* field_name, const double* field_data, data_size_t num_element); LIGHTGBM_EXPORT bool SetIntField(const char* field_name, const int* field_data, data_size_t num_element); LIGHTGBM_EXPORT bool GetFloatField(const char* field_name, data_size_t* out_len, const float** out_ptr); LIGHTGBM_EXPORT bool GetDoubleField(const char* field_name, data_size_t* out_len, const double** out_ptr); LIGHTGBM_EXPORT bool GetIntField(const char* field_name, data_size_t* out_len, const int** out_ptr); /*! * \brief Save current dataset into binary file, will save to "filename.bin" */ LIGHTGBM_EXPORT void SaveBinaryFile(const char* bin_filename); LIGHTGBM_EXPORT void CopyFeatureMapperFrom(const Dataset* dataset); LIGHTGBM_EXPORT void CreateValid(const Dataset* dataset); void ConstructHistograms(const std::vector<int8_t>& is_feature_used, const data_size_t* data_indices, data_size_t num_data, int leaf_idx, std::vector<std::unique_ptr<OrderedBin>>& ordered_bins, const score_t* gradients, const score_t* hessians, score_t* ordered_gradients, score_t* ordered_hessians, bool is_constant_hessian, HistogramBinEntry* histogram_data) const; void FixHistogram(int feature_idx, double sum_gradient, double sum_hessian, data_size_t num_data, HistogramBinEntry* data) const; inline data_size_t Split(int feature, const uint32_t* threshold, int num_threshold, bool default_left, data_size_t* data_indices, data_size_t num_data, data_size_t* lte_indices, data_size_t* gt_indices) const { const int group = feature2group_[feature]; const int sub_feature = feature2subfeature_[feature]; return feature_groups_[group]->Split(sub_feature, threshold, num_threshold, default_left, data_indices, num_data, lte_indices, gt_indices); } inline int SubFeatureBinOffset(int i) const { const int sub_feature = feature2subfeature_[i]; if (sub_feature == 0) { return 1; } else { return 0; } } inline int FeatureNumBin(int i) const { const int group = feature2group_[i]; const int sub_feature = feature2subfeature_[i]; return feature_groups_[group]->bin_mappers_[sub_feature]->num_bin(); } inline int8_t FeatureMonotone(int i) const { if (monotone_types_.empty()) { return 0; } else { return monotone_types_[i]; } } inline double FeaturePenalte(int i) const { if (feature_penalty_.empty()) { return 1; } else { return feature_penalty_[i]; } } bool HasMonotone() const { if (monotone_types_.empty()) { return false; } else { for (size_t i = 0; i < monotone_types_.size(); ++i) { if (monotone_types_[i] != 0) { return true; } } return false; } } inline int FeatureGroupNumBin(int group) const { return feature_groups_[group]->num_total_bin_; } inline const BinMapper* FeatureBinMapper(int i) const { const int group = feature2group_[i]; const int sub_feature = feature2subfeature_[i]; return feature_groups_[group]->bin_mappers_[sub_feature].get(); } inline const Bin* FeatureBin(int i) const { const int group = feature2group_[i]; return feature_groups_[group]->bin_data_.get(); } inline const Bin* FeatureGroupBin(int group) const { return feature_groups_[group]->bin_data_.get(); } inline bool FeatureGroupIsSparse(int group) const { return feature_groups_[group]->is_sparse_; } inline BinIterator* FeatureIterator(int i) const { const int group = feature2group_[i]; const int sub_feature = feature2subfeature_[i]; return feature_groups_[group]->SubFeatureIterator(sub_feature); } inline BinIterator* FeatureGroupIterator(int group) const { return feature_groups_[group]->FeatureGroupIterator(); } inline double RealThreshold(int i, uint32_t threshold) const { const int group = feature2group_[i]; const int sub_feature = feature2subfeature_[i]; return feature_groups_[group]->bin_mappers_[sub_feature]->BinToValue(threshold); } // given a real threshold, find the closest threshold bin inline uint32_t BinThreshold(int i, double threshold_double) const { const int group = feature2group_[i]; const int sub_feature = feature2subfeature_[i]; return feature_groups_[group]->bin_mappers_[sub_feature]->ValueToBin(threshold_double); } inline void CreateOrderedBins(std::vector<std::unique_ptr<OrderedBin>>* ordered_bins) const { ordered_bins->resize(num_groups_); OMP_INIT_EX(); #pragma omp parallel for schedule(guided) for (int i = 0; i < num_groups_; ++i) { OMP_LOOP_EX_BEGIN(); ordered_bins->at(i).reset(feature_groups_[i]->bin_data_->CreateOrderedBin()); OMP_LOOP_EX_END(); } OMP_THROW_EX(); } /*! * \brief Get meta data pointer * \return Pointer of meta data */ inline const Metadata& metadata() const { return metadata_; } /*! \brief Get Number of used features */ inline int num_features() const { return num_features_; } /*! \brief Get Number of feature groups */ inline int num_feature_groups() const { return num_groups_;} /*! \brief Get Number of total features */ inline int num_total_features() const { return num_total_features_; } /*! \brief Get the index of label column */ inline int label_idx() const { return label_idx_; } /*! \brief Get names of current data set */ inline const std::vector<std::string>& feature_names() const { return feature_names_; } inline void set_feature_names(const std::vector<std::string>& feature_names) { if (feature_names.size() != static_cast<size_t>(num_total_features_)) { Log::Fatal("Size of feature_names error, should equal with total number of features"); } feature_names_ = std::vector<std::string>(feature_names); // replace ' ' in feature_names with '_' bool spaceInFeatureName = false; for (auto& feature_name: feature_names_){ if (feature_name.find(' ') != std::string::npos){ spaceInFeatureName = true; std::replace(feature_name.begin(), feature_name.end(), ' ', '_'); } } if (spaceInFeatureName){ Log::Warning("Find whitespaces in feature_names, replace with underlines"); } } inline std::vector<std::string> feature_infos() const { std::vector<std::string> bufs; for (int i = 0; i < num_total_features_; i++) { int fidx = used_feature_map_[i]; if (fidx == -1) { bufs.push_back("none"); } else { const auto bin_mapper = FeatureBinMapper(fidx); bufs.push_back(bin_mapper->bin_info()); } } return bufs; } /*! \brief Get Number of data */ inline data_size_t num_data() const { return num_data_; } /*! \brief Disable copy */ Dataset& operator=(const Dataset&) = delete; /*! \brief Disable copy */ Dataset(const Dataset&) = delete; private: std::string data_filename_; /*! \brief Store used features */ std::vector<std::unique_ptr<FeatureGroup>> feature_groups_; /*! \brief Mapper from real feature index to used index*/ std::vector<int> used_feature_map_; /*! \brief Number of used features*/ int num_features_; /*! \brief Number of total features*/ int num_total_features_; /*! \brief Number of total data*/ data_size_t num_data_; /*! \brief Store some label level data*/ Metadata metadata_; /*! \brief index of label column */ int label_idx_ = 0; /*! \brief Threshold for treating a feature as a sparse feature */ double sparse_threshold_; /*! \brief store feature names */ std::vector<std::string> feature_names_; /*! \brief store feature names */ static const char* binary_file_token; int num_groups_; std::vector<int> real_feature_idx_; std::vector<int> feature2group_; std::vector<int> feature2subfeature_; std::vector<uint64_t> group_bin_boundaries_; std::vector<int> group_feature_start_; std::vector<int> group_feature_cnt_; std::vector<int8_t> monotone_types_; std::vector<double> feature_penalty_; bool is_finish_load_; }; } // namespace LightGBM #endif // LightGBM_DATA_H_
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p, *restrict r; register IndexPacket *restrict threshold_indexes; register PixelPacket *restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if ((channel & SyncChannels) != 0) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BilevelImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlackThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ static inline Quantum ClampPixel(const MagickRealType value) { #if !defined(MAGICKCORE_HDRI_SUPPORT) return((Quantum) value); #else if (value < 0.0f) return(0.0f); if (value >= (MagickRealType) QuantumRange) return((Quantum) QuantumRange); return(value); #endif } MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampPixel(GetPixelRed(q))); SetPixelGreen(q,ClampPixel(GetPixelGreen(q))); SetPixelBlue(q,ClampPixel(GetPixelBlue(q))); SetPixelOpacity(q,ClampPixel(GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampPixel(GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixel(GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixel(GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampPixel(GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampPixel(GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClampImageChannel) #endif proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attribute, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *) NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(map); for (threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { attribute=GetXMLTreeAttribute(threshold, "map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold, "alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } /* The map has been found -- allocate a Threshold Map to return */ map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; /* Assign basic attributeibutes. */ attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels, "divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array. */ content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { char *p; register ssize_t i; /* Parse levels into integer array. */ for (i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,ClampToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OrderedPosterizeImageChannel) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImageChannel method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon) % MagickBooleanType PerceptibleImageChannel(Image *image, % const ChannelType channel,const double epsilon) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon) { MagickBooleanType status; status=PerceptibleImageChannel(image,DefaultChannels,epsilon); return(status); } MagickExport MagickBooleanType PerceptibleImageChannel(Image *image, const ChannelType channel,const double epsilon) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); q++; } return(SyncImage(image)); } /* Perceptible image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x), epsilon)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PerceptibleImageChannel) #endif proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #endif image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { IndexPacket index; MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #endif image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WhiteThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
axpy_ompacc3.c
// Experimental test input for Accelerator directives // simplest scalar*vector operations // Testing extensions for multiple devices // Liao 2/2/2015 //AXPY multiple GPU version, using OpenMP 4.0 standard directives // vector = vector + vector * scalar #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <assert.h> #include <omp.h> #define REAL double #define VEC_LEN 1024000 //use a fixed number for now //#define MAX_GPU_COUNT 4 // maximum GPU numbers in computation /* zero out the entire vector */ void zero(REAL *A, int n) { int i; for (i = 0; i < n; i++) { A[i] = 0.0; } } /* initialize a vector with random floating point numbers */ void init(REAL *A, int n) { int i; for (i = 0; i < n; i++) { A[i] = (REAL)drand48(); } } REAL check(REAL*A, REAL*B, int n) { int i; REAL diffsum =0.0, sum = 0.0; for (i = 0; i < n; i++) { diffsum += fabs(A[i] - B[i]); sum += fabs(B[i]); } return diffsum/sum; } /* CPU version */ void axpy(REAL* x, REAL* y, long n, REAL a) { int i; #pragma omp parallel for shared(x, y, n, a) private(i) for (i = 0; i < n; ++i) { y[i] += a * x[i]; } } int main(int argc, char *argv[]) { int n,i; REAL *y_ref, *y_ompacc, *x; REAL a = 123.456f; n = VEC_LEN; if (argc >= 2) n = atoi(argv[1]); y_ref = (REAL *) malloc(n * sizeof(REAL)); y_ompacc = (REAL *) malloc(n * sizeof(REAL)); x = (REAL *) malloc(n * sizeof(REAL)); srand48(1<<12); init(x, n); init(y_ref, n); memcpy(y_ompacc, y_ref, n*sizeof(REAL)); // int GPU_N = 0; // Transformation point: obtain the number of devices to be used by default int GPU_N = xomp_get_num_devices(); #if 0 cudaGetDeviceCount(&GPU_N); if (GPU_N > MAX_GPU_COUNT) { GPU_N = MAX_GPU_COUNT; } #endif printf("CUDA-capable device count: %i\n", GPU_N); // preparation for multiple GPUs // Transformation point: set first level thread count to be GPU count used omp_set_num_threads(GPU_N); #pragma omp parallel shared (GPU_N,x , y_ompacc, n) private(i) { int tid = omp_get_thread_num(); // cudaSetDevice(tid); xomp_set_default_device (tid); long size, offset; #if 0 int size = n / GPU_N; int offset = size * tid; if(tid < n%GPU_N) { size++; } if(tid >= n%GPU_N) offset += n%GPU_N; else offset += tid; #endif XOMP_static_even_divide (0, n, GPU_N, tid, &offset, &size); printf("thread %d working on GPU devices %d with size %ld copying data from y_ompacc with offset %ld\n",tid, tid, size,offset); int j; #pragma omp target device (tid) map(tofrom: y_ompacc[offset:size]) map(to: x[offset:size],a,size, offset) #pragma omp parallel for shared(size, a) private(j) for (j = offset; j < offset+size; ++j) { y_ompacc[j] += a * x[j]; } } int num_threads; #pragma omp parallel shared (num_threads) { if (omp_get_thread_num() == 0) num_threads = omp_get_num_threads(); } // serial version axpy(x, y_ref, n, a); REAL checksum = check(y_ref, y_ompacc, n); printf("axpy(%d): checksum: %g\n", n, checksum); assert (checksum < 1.0e-10); free(y_ref); free(y_ompacc); free(x); return 0; }
brisched.h
#pragma omp parallel for collapse(2) for (long k = GZ / TILEK; k < (N + GZ) / TILEK; ++k) for (long j = GZ / TILEJ; j < (N + GZ) / TILEJ; ++j) for (long i = GZ / TILEI; i < (N + GZ) / TILEI; ++i)
prop_container.h
// -*- mode:c++; c-basic-offset:4 -*- #ifndef PROP_CONTAINER_H_KL3 #define PROP_CONTAINER_H_KL3 #include <util/gjp.h> #include <util/verbose.h> #include <alg/qpropw.h> #include <omp.h> #include <cassert> #include "my_util.h" class PropAP { public: PropAP(const std::vector<cps::WilsonMatrix> &f, const std::vector<cps::WilsonMatrix> &s) :fst(&f),snd(&s), lcl_vol(cps::GJP.VolNodeSites()) { } const cps::WilsonMatrix &operator[](size_t i)const { if(i < lcl_vol) return (*fst)[i]; else return (*snd)[i - lcl_vol]; } private: const std::vector<cps::WilsonMatrix> *fst; const std::vector<cps::WilsonMatrix> *snd; // If the source is on the local lattice, then the 1st half is // (P+A)/2 and the 2nd half is (P-A)/2. If the source is on the // mirrored lattice, then the 1st half is (P-A)/2 and the 2nd half // is (P+A)/2. size_t lcl_vol; }; // Propagators from all time slices (including the case where the // source is on the mirrored lattice). class AllProp { public: AllProp() :lcl_vol(cps::GJP.VolNodeSites()), t_size_glb(cps::GJP.TnodeSites() * cps::GJP.Tnodes()), p(t_size_glb), m(t_size_glb) { for(unsigned i = 0; i < t_size_glb; ++i) { prop.push_back(PropAP(p[i], m[i])); } for(unsigned i = 0; i < t_size_glb; ++i) { prop.push_back(PropAP(m[i], p[i])); } } const PropAP &operator[](size_t i)const { return prop[i]; } bool empty(size_t t)const { assert(t < 2 * t_size_glb); if(t >= t_size_glb) t -= t_size_glb; return p[t].empty(); } // Add a propagator where the source is located at time slice t. // If periodic == true then it will be treated as a P-boundary // condition propagator, otherwise it will be treated as an // A-boundary condition propagator. void add(cps::QPropW &qp, size_t t, bool periodic) { std::vector<cps::WilsonMatrix> &pt = p[t]; std::vector<cps::WilsonMatrix> &mt = m[t]; if(pt.size() == 0) { pt.assign(lcl_vol, cps::WilsonMatrix(0)); } if(mt.size() == 0) { mt.assign(lcl_vol, cps::WilsonMatrix(0)); } #pragma omp parallel for for(size_t i = 0; i < lcl_vol; ++i) { pt[i] += qp[i]; if(periodic) { mt[i] += qp[i]; } else { mt[i] -= qp[i]; } } } void avg(void) { for(size_t t = 0; t < t_size_glb; ++t) { std::vector<cps::WilsonMatrix> &pt = p[t]; std::vector<cps::WilsonMatrix> &mt = m[t]; assert(pt.size() == mt.size()); if(pt.size() == 0) continue; #pragma omp parallel for for(size_t i = 0; i < lcl_vol; ++i) { pt[i] *= 0.5; mt[i] *= 0.5; } } } private: const size_t lcl_vol; const size_t t_size_glb; std::vector<std::vector<cps::WilsonMatrix> > p; // (P+A)/2 std::vector<std::vector<cps::WilsonMatrix> > m; // (P-A)/2 std::vector<PropAP> prop; }; // This function is not supported and must be checked again when // use. // void apply_mom(const double mom[4]) { // if(mom[3] != 0) { // fprintf(stderr, "Adding momentum in t direction is not supported.\n"); // exit(-1); // } // const int lcl[4] = { // cps::GJP.XnodeSites(), cps::GJP.YnodeSites(), // cps::GJP.ZnodeSites(), cps::GJP.TnodeSites(), // }; // const int shift[4] = { // cps::GJP.XnodeSites() * cps::GJP.XnodeCoor(), // cps::GJP.YnodeSites() * cps::GJP.YnodeCoor(), // cps::GJP.ZnodeSites() * cps::GJP.ZnodeCoor(), // cps::GJP.TnodeSites() * cps::GJP.TnodeCoor(), // }; // const int glb[4] = { // cps::GJP.XnodeSites() * cps::GJP.Xnodes(), // cps::GJP.YnodeSites() * cps::GJP.Ynodes(), // cps::GJP.ZnodeSites() * cps::GJP.Znodes(), // cps::GJP.TnodeSites() * cps::GJP.Tnodes(), // }; // cps::VRB.Result("PropAP", "apply_mom", "mom = %.3e %.3e %.3e %.3e\n", // mom[0], mom[1], mom[2], mom[3]); // const size_t lcl_vol = cps::GJP.VolNodeSites(); // #pragma omp parallel for // for(int i = 0; i < lcl_vol; ++i) { // int glb_x[4]; // compute_coord(glb_x, lcl, shift, i); // const double PI = 3.1415926535897932384626433832795028842; // double alpha = 0.; // for(int mu = 0; mu < 4; ++mu) { // alpha -= mom[mu] * 2.0 * PI * glb_x[mu] / glb[mu]; // } // wm[i] *= cps::Rcomplex(std::cos(alpha), std::sin(alpha)); // wm[i + lcl_vol] *= cps::Rcomplex(std::cos(alpha), std::sin(alpha)); // } // } #endif
django_scrypt_fmt_plug.c
/* scrypt cracker patch for JtR. Hacked together during May of 2013 by Dhiru * Kholia <dhiru at openwall.com>. * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com> and * it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_django_scrypt; #elif FMT_REGISTERS_H john_register_one(&fmt_django_scrypt); #else #include <string.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "base64.h" #include "escrypt/crypto_scrypt.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 // So slow a format, a multiplier is NOT needed #endif #endif #include "memdbg.h" #define FORMAT_LABEL "django-scrypt" #define FORMAT_NAME "" #define FORMAT_TAG "scrypt" #define TAG_LENGTH 6 #ifdef __XOP__ #define ALGORITHM_NAME "Salsa20/8 128/128 XOP" #elif defined(__AVX__) #define ALGORITHM_NAME "Salsa20/8 128/128 AVX" #elif defined(__SSE2__) #define ALGORITHM_NAME "Salsa20/8 128/128 SSE2" #else #define ALGORITHM_NAME "Salsa20/8 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 64 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 4 #define SALT_ALIGN 4 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 /* notastrongpassword => scrypt$NBGmaGIXijJW$14$8$1$64$achPt01SbytSt+F3CcCFgEPr96+/j9iCTdejFdAARZ8mzfejrP64TJ5XBJa3gYwuCKOEGlw2E/lWCWS7LeS6CA== */ static struct fmt_tests scrypt_tests[] = { /* https://pypi.python.org/pypi/django-scrypt/ format hashes */ {"scrypt$NBGmaGIXijJW$14$8$1$64$achPt01SbytSt+F3CcCFgEPr96+/j9iCTdejFdAARZ8mzfejrP64TJ5XBJa3gYwuCKOEGlw2E/lWCWS7LeS6CA==", "notastrongpassword"}, {"scrypt$Cj0PzdtT3qS2$14$8$1$64$qn4CDnM8CcIBNrpQXHo6ti8vSUoSXj7GBFy7k1bp5wPs8jKjh/gHZ+qM9uk6LbcVHm02yBaI5WCbDm/Shq/MXA==", "realmenuseJtR"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { /* int type; */ // not used (another type probably required a new JtR format) int N; int r; int p; unsigned char salt[32]; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int isDigits(char *p) { while (*p && *p != '$') { if (*p <= '0' || *p >= '9') return 0; ++p; } return 1; } static int valid(char *ciphertext, struct fmt_main *self) { char *cp, *cp2; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) return 0; cp = ciphertext + TAG_LENGTH; if (*cp != '$') return 0; ++cp; cp2 = strchr(cp, '$'); if (!cp2) return 0; if (cp2-cp > 32) return 0; cp = &cp2[1]; if (isDigits(cp) == 0) return 0; cp = strchr(cp, '$'); if (!cp) return 0; ++cp; if (isDigits(cp) == 0) return 0; cp = strchr(cp, '$'); if (!cp) return 0; ++cp; if (isDigits(cp) == 0) return 0; cp = strchr(cp, '$'); if (!cp) return 0; ++cp; if (isDigits(cp) == 0) return 0; cp = strchr(cp, '$'); if (!cp) return 0; ++cp; if (strlen(cp) != 88) return 0; return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; /* ensure alignment */ static union { struct custom_salt _cs; ARCH_WORD_32 dummy; } un; static struct custom_salt *cs = &(un._cs); ctcopy += TAG_LENGTH + 1; p = strtokm(ctcopy, "$"); strncpy((char*)cs->salt, p, 32); p = strtokm(NULL, "$"); cs->N = atoi(p); p = strtokm(NULL, "$"); cs->r = atoi(p); p = strtokm(NULL, "$"); cs->p = atoi(p); MEM_FREE(keeptr); return (void *)cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE + 1]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; p = strrchr(ciphertext, '$') + 1; base64_decode(p, strlen(p), (char*)out); return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { if (crypto_scrypt((unsigned char*)saved_key[index], strlen((char*)saved_key[index]), cur_salt->salt, strlen((char*)cur_salt->salt), (1ULL) << cur_salt->N, cur_salt->r, cur_salt->p, (unsigned char*)crypt_out[index], BINARY_SIZE) == -1) { memset(crypt_out[index], 0, sizeof(crypt_out[index])); } } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void scrypt_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static unsigned int tunable_cost_N(void *salt) { static struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->N; } static unsigned int tunable_cost_r(void *salt) { static struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->r; } static unsigned int tunable_cost_p(void *salt) { static struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->p; } struct fmt_main fmt_django_scrypt = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "N", "r", "p" }, scrypt_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { tunable_cost_N, tunable_cost_r, tunable_cost_p }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, scrypt_set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
GB_unop__identity_fp64_int8.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_fp64_int8) // op(A') function: GB (_unop_tran__identity_fp64_int8) // C type: double // A type: int8_t // cast: double cij = (double) aij // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ double z = (double) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = (double) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp64_int8) ( double *Cx, // Cx and Ax may be aliased const int8_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 (int8_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; double z = (double) aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int8_t aij = Ax [p] ; double z = (double) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fp64_int8) ( 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
conv1x1s2_sse.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. #include "option.h" #include "mat.h" namespace ncnn{ static void conv1x1s2_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } } }
pre_processing_dodg.h
#pragma once #include <future> #include "pre_processing.h" bool RankLT(int du, int dv, int u, int v) { // assert(u != v); return du < dv || ((du == dv) && (u < v)); } template<typename T, typename OFF> void ConvertEdgeListToDODGCSR(OFF num_edges, pair<T, T> *&edge_lst, uint32_t num_vertices, uint32_t *&deg_lst, OFF *&off, int32_t *&adj_lst, int max_omp_threads) { ConvertEdgeListToDODGCSR(num_edges, edge_lst, num_vertices, deg_lst, off, adj_lst, max_omp_threads, [](size_t it) { return true; }); } template<typename T, typename F, typename OFF> void ConvertEdgeListToDODGCSR(OFF num_edges, pair<T, T> *&edge_lst, uint32_t num_vertices, uint32_t *&deg_lst, OFF *&off, int32_t *&adj_lst, int max_omp_threads, F f) { Timer convert_timer; deg_lst = (uint32_t *) malloc(sizeof(uint32_t) * (num_vertices + 1)); auto *dodg_deg_lst = (uint32_t *) malloc(sizeof(uint32_t) * (num_vertices + 1)); off = (OFF *) malloc(sizeof(OFF) * (num_vertices + 1)); auto cur_write_off = (OFF *) malloc(sizeof(OFF) * (num_vertices + 1)); vector<row_ptr_t> histogram; auto io_future = std::async(std::launch::async, [=]() { auto tmp_file_fd = open("tmp_el.bin", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); size_t size = num_edges * sizeof(int32_t) * 2; ftruncate(tmp_file_fd, size); auto write_buf = (pair<T, T> *) mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, tmp_file_fd, 0); memcpy(write_buf, edge_lst, size); return write_buf; }); #pragma omp parallel num_threads(max_omp_threads) { MemSetOMP(deg_lst, 0, num_vertices + 1); MemSetOMP(off, 0, num_vertices + 1); #pragma omp single log_info("[%s]: InitTime: %.9lf s", __FUNCTION__, convert_timer.elapsed()); // Histogram. EdgeListHistogram(num_vertices, num_edges, edge_lst, deg_lst, f); MemSetOMP(dodg_deg_lst, 0, num_vertices + 1); #pragma omp for for (size_t i = 0u; i < num_edges; i++) { if (f(i)) { auto src = edge_lst[i].first; auto dst = edge_lst[i].second; if (RankLT(deg_lst[src], deg_lst[dst], src, dst)) __sync_fetch_and_add(&dodg_deg_lst[src], 1); else __sync_fetch_and_add(&dodg_deg_lst[dst], 1); } } #pragma omp single log_info("[%s]: Histogram Time: %.9lf s", __FUNCTION__, convert_timer.elapsed()); // PrefixSum. InclusivePrefixSumOMP(histogram, off + 1, num_vertices, [&dodg_deg_lst](uint32_t it) { return dodg_deg_lst[it]; }); #pragma omp single { log_debug("%zu", off[num_vertices]); assert(off[num_vertices] <= num_edges); } MemCpyOMP(cur_write_off, off, num_vertices + 1); // Write Edge List to File, Using Page Cache. #pragma omp single { log_info("Mem Usage: %s KB", FormatWithCommas(getValue()).c_str()); auto tmp = edge_lst; edge_lst = io_future.get(); log_info("Mem Usage: %s KB", FormatWithCommas(getValue()).c_str()); size_t size = num_edges * sizeof(int32_t) * 2; free(tmp); madvise(edge_lst, size, MADV_SEQUENTIAL); if (adj_lst == nullptr) { log_info("Allocate Inside (adj_lst)..."); adj_lst = (int32_t *) malloc(sizeof(int32_t) * off[num_vertices]); } log_info("[%s]: PrefixSum Time: %.9lf s", __FUNCTION__, convert_timer.elapsed()); } // Scatter. #pragma omp for schedule(dynamic, 32*4096/8) for (size_t i = 0; i < num_edges; i++) { if (f(i)) { auto src = edge_lst[i].first; auto dst = edge_lst[i].second; if (!RankLT(deg_lst[src], deg_lst[dst], src, dst)) { swap(src, dst); } auto old_offset = __sync_fetch_and_add(&(cur_write_off[src]), 1); adj_lst[old_offset] = dst; } } } free(dodg_deg_lst); free(cur_write_off); log_info("[%s]: Total Conversion Time: %.9lf s", __FUNCTION__, convert_timer.elapsed()); } inline void ReorderDegDescendingDODG(graph_t &g, vector<int32_t> &new_vid_dict, vector<int32_t> &old_vid_dict, int32_t *&new_adj, uint32_t *&deg_lst) { Timer timer; auto max_omp_threads = omp_get_max_threads(); auto max_deg = 0; auto *old_vid_dict_buffer = (int32_t *) malloc(sizeof(int32_t) * g.n); uint32_t *write_off = nullptr; uint32_t *bucket_ptrs = nullptr; auto histogram = vector<uint32_t>((max_omp_threads + 1) * CACHE_LINE_ENTRY, 0); #pragma omp parallel num_threads(max_omp_threads) { #pragma omp for reduction(max: max_deg) for (auto i = 0; i < g.n; i++) { max_deg = max<int>(max_deg, deg_lst[i]); } #pragma omp single nowait { old_vid_dict = vector<int32_t>(g.n); } #pragma omp for for (auto i = 0u; i < g.n; i++) { old_vid_dict_buffer[i] = i; } auto ptr = &old_vid_dict[0]; BucketSortSmallBuckets(histogram, old_vid_dict_buffer, ptr, write_off, bucket_ptrs, g.n, max_deg + 1, [deg_lst, old_vid_dict_buffer, max_deg](int i) { auto u = old_vid_dict_buffer[i]; return max_deg - (deg_lst[u]); }); } free(write_off); free(bucket_ptrs); free(old_vid_dict_buffer); log_info("Deg-descending time: %.9lf s", timer.elapsed()); Reorder(g, new_vid_dict, old_vid_dict, new_adj); }
stream.c
// Copyright 2009-2019 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2019, NTESS // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { const int LENGTH = 2000; printf("Allocating arrays of size %d elements.\n", LENGTH); double* a = (double*) malloc(sizeof(double) * LENGTH); double* b = (double*) malloc(sizeof(double) * LENGTH); double* c = (double*) malloc(sizeof(double) * LENGTH); printf("Done allocating arrays.\n"); int i; for(i = 0; i < LENGTH; ++i) { a[i] = i; b[i] = LENGTH - i; c[i] = 0; } printf("Perfoming the fast_c compute loop...\n"); #pragma omp parallel for for(i = 0; i < LENGTH; ++i) { //printf("issuing a write to: %llu (fast_c)\n", ((unsigned long long int) &fast_c[i])); c[i] = 2.0 * a[i] + 1.5 * b[i]; } double sum = 0; for(i = 0; i < LENGTH; ++i) { sum += c[i]; } printf("Sum of arrays is: %f\n", sum); printf("Freeing arrays...\n"); free(a); free(b); free(c); printf("Done.\n"); }
a2+a3.c
#include <stdio.h> #include <omp.h> int main(){ int a2, a3, id; omp_set_dynamic(0); #pragma omp parallel num_threads(3) { id = omp_get_thread_num(); if(id == 0){ while(1){ #pragma omp critical { a2 = 18; printf("a2 = %d", a2); fgetc(stdin); } } } else if(id == 1){ while(1){ #pragma omp critical { a3 = 7; printf("a3 = %d", a3); fgetc(stdin); } } } else{ while(1){ #pragma omp critical { printf("a2+a3 = %d", a2+a3); fgetc(stdin); } } } } return 0; }
GeneralMatrixMatrix.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_GENERAL_MATRIX_MATRIX_H #define EIGEN_GENERAL_MATRIX_MATRIX_H #include "../InternalHeaderCheck.h" namespace Eigen { namespace internal { template<typename LhsScalar_, typename RhsScalar_> class level3_blocking; /* Specialization for a row-major destination matrix => simple transposition of the product */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int ResInnerStride> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor,ResInnerStride> { typedef gebp_traits<RhsScalar,LhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static EIGEN_STRONG_INLINE void run( Index rows, Index cols, Index depth, const LhsScalar* lhs, Index lhsStride, const RhsScalar* rhs, Index rhsStride, ResScalar* res, Index resIncr, Index resStride, ResScalar alpha, level3_blocking<RhsScalar,LhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { // transpose the product such that the result is column major general_matrix_matrix_product<Index, RhsScalar, RhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateRhs, LhsScalar, LhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateLhs, ColMajor,ResInnerStride> ::run(cols,rows,depth,rhs,rhsStride,lhs,lhsStride,res,resIncr,resStride,alpha,blocking,info); } }; /* Specialization for a col-major destination matrix * => Blocking algorithm following Goto's paper */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int ResInnerStride> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor,ResInnerStride> { typedef gebp_traits<LhsScalar,RhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static void run(Index rows, Index cols, Index depth, const LhsScalar* _lhs, Index lhsStride, const RhsScalar* _rhs, Index rhsStride, ResScalar* _res, Index resIncr, Index resStride, ResScalar alpha, level3_blocking<LhsScalar,RhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { typedef const_blas_data_mapper<LhsScalar, Index, LhsStorageOrder> LhsMapper; typedef const_blas_data_mapper<RhsScalar, Index, RhsStorageOrder> RhsMapper; typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor,Unaligned,ResInnerStride> ResMapper; LhsMapper lhs(_lhs, lhsStride); RhsMapper rhs(_rhs, rhsStride); ResMapper res(_res, resStride, resIncr); Index kc = blocking.kc(); // cache block size along the K direction Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction Index nc = (std::min)(cols,blocking.nc()); // cache block size along the N direction gemm_pack_lhs<LhsScalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, typename Traits::LhsPacket4Packing, LhsStorageOrder> pack_lhs; gemm_pack_rhs<RhsScalar, Index, RhsMapper, Traits::nr, RhsStorageOrder> pack_rhs; gebp_kernel<LhsScalar, RhsScalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp; #ifdef EIGEN_HAS_OPENMP if(info) { // this is the parallel version! int tid = omp_get_thread_num(); int threads = omp_get_num_threads(); LhsScalar* blockA = blocking.blockA(); eigen_internal_assert(blockA!=0); std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, 0); // For each horizontal panel of the rhs, and corresponding vertical panel of the lhs... for(Index k=0; k<depth; k+=kc) { const Index actual_kc = (std::min)(k+kc,depth)-k; // => rows of B', and cols of the A' // In order to reduce the chance that a thread has to wait for the other, // let's start by packing B'. pack_rhs(blockB, rhs.getSubMapper(k,0), actual_kc, nc); // Pack A_k to A' in a parallel fashion: // each thread packs the sub block A_k,i to A'_i where i is the thread id. // However, before copying to A'_i, we have to make sure that no other thread is still using it, // i.e., we test that info[tid].users equals 0. // Then, we set info[tid].users to the number of threads to mark that all other threads are going to use it. while(info[tid].users!=0) {} info[tid].users = threads; pack_lhs(blockA+info[tid].lhs_start*actual_kc, lhs.getSubMapper(info[tid].lhs_start,k), actual_kc, info[tid].lhs_length); // Notify the other threads that the part A'_i is ready to go. info[tid].sync = k; // Computes C_i += A' * B' per A'_i for(int shift=0; shift<threads; ++shift) { int i = (tid+shift)%threads; // At this point we have to make sure that A'_i has been updated by the thread i, // we use testAndSetOrdered to mimic a volatile access. // However, no need to wait for the B' part which has been updated by the current thread! if (shift>0) { while(info[i].sync!=k) { } } gebp(res.getSubMapper(info[i].lhs_start, 0), blockA+info[i].lhs_start*actual_kc, blockB, info[i].lhs_length, actual_kc, nc, alpha); } // Then keep going as usual with the remaining B' for(Index j=nc; j<cols; j+=nc) { const Index actual_nc = (std::min)(j+nc,cols)-j; // pack B_k,j to B' pack_rhs(blockB, rhs.getSubMapper(k,j), actual_kc, actual_nc); // C_j += A' * B' gebp(res.getSubMapper(0, j), blockA, blockB, rows, actual_kc, actual_nc, alpha); } // Release all the sub blocks A'_i of A' for the current thread, // i.e., we simply decrement the number of users by 1 for(Index i=0; i<threads; ++i) #if !EIGEN_HAS_CXX11_ATOMIC #pragma omp atomic #endif info[i].users -= 1; } } else #endif // EIGEN_HAS_OPENMP { EIGEN_UNUSED_VARIABLE(info); // this is the sequential version! std::size_t sizeA = kc*mc; std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(LhsScalar, blockA, sizeA, blocking.blockA()); ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, blocking.blockB()); const bool pack_rhs_once = mc!=rows && kc==depth && nc==cols; // For each horizontal panel of the rhs, and corresponding panel of the lhs... for(Index i2=0; i2<rows; i2+=mc) { const Index actual_mc = (std::min)(i2+mc,rows)-i2; for(Index k2=0; k2<depth; k2+=kc) { const Index actual_kc = (std::min)(k2+kc,depth)-k2; // OK, here we have selected one horizontal panel of rhs and one vertical panel of lhs. // => Pack lhs's panel into a sequential chunk of memory (L2/L3 caching) // Note that this panel will be read as many times as the number of blocks in the rhs's // horizontal panel which is, in practice, a very low number. pack_lhs(blockA, lhs.getSubMapper(i2,k2), actual_kc, actual_mc); // For each kc x nc block of the rhs's horizontal panel... for(Index j2=0; j2<cols; j2+=nc) { const Index actual_nc = (std::min)(j2+nc,cols)-j2; // We pack the rhs's block into a sequential chunk of memory (L2 caching) // Note that this block will be read a very high number of times, which is equal to the number of // micro horizontal panel of the large rhs's panel (e.g., rows/12 times). if((!pack_rhs_once) || i2==0) pack_rhs(blockB, rhs.getSubMapper(k2,j2), actual_kc, actual_nc); // Everything is packed, we can now call the panel * block kernel: gebp(res.getSubMapper(i2, j2), blockA, blockB, actual_mc, actual_kc, actual_nc, alpha); } } } } } }; /********************************************************************************* * Specialization of generic_product_impl for "large" GEMM, i.e., * implementation of the high level wrapper to general_matrix_matrix_product **********************************************************************************/ template<typename Scalar, typename Index, typename Gemm, typename Lhs, typename Rhs, typename Dest, typename BlockingType> struct gemm_functor { gemm_functor(const Lhs& lhs, const Rhs& rhs, Dest& dest, const Scalar& actualAlpha, BlockingType& blocking) : m_lhs(lhs), m_rhs(rhs), m_dest(dest), m_actualAlpha(actualAlpha), m_blocking(blocking) {} void initParallelSession(Index num_threads) const { m_blocking.initParallel(m_lhs.rows(), m_rhs.cols(), m_lhs.cols(), num_threads); m_blocking.allocateA(); } void operator() (Index row, Index rows, Index col=0, Index cols=-1, GemmParallelInfo<Index>* info=0) const { if(cols==-1) cols = m_rhs.cols(); Gemm::run(rows, cols, m_lhs.cols(), &m_lhs.coeffRef(row,0), m_lhs.outerStride(), &m_rhs.coeffRef(0,col), m_rhs.outerStride(), (Scalar*)&(m_dest.coeffRef(row,col)), m_dest.innerStride(), m_dest.outerStride(), m_actualAlpha, m_blocking, info); } typedef typename Gemm::Traits Traits; protected: const Lhs& m_lhs; const Rhs& m_rhs; Dest& m_dest; Scalar m_actualAlpha; BlockingType& m_blocking; }; template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor=1, bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class gemm_blocking_space; template<typename LhsScalar_, typename RhsScalar_> class level3_blocking { typedef LhsScalar_ LhsScalar; typedef RhsScalar_ RhsScalar; protected: LhsScalar* m_blockA; RhsScalar* m_blockB; Index m_mc; Index m_nc; Index m_kc; public: level3_blocking() : m_blockA(0), m_blockB(0), m_mc(0), m_nc(0), m_kc(0) {} inline Index mc() const { return m_mc; } inline Index nc() const { return m_nc; } inline Index kc() const { return m_kc; } inline LhsScalar* blockA() { return m_blockA; } inline RhsScalar* blockB() { return m_blockB; } }; template<int StorageOrder, typename LhsScalar_, typename RhsScalar_, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,LhsScalar_,RhsScalar_,MaxRows, MaxCols, MaxDepth, KcFactor, true /* == FiniteAtCompileTime */> : public level3_blocking< typename conditional<StorageOrder==RowMajor,RhsScalar_,LhsScalar_>::type, typename conditional<StorageOrder==RowMajor,LhsScalar_,RhsScalar_>::type> { enum { Transpose = StorageOrder==RowMajor, ActualRows = Transpose ? MaxCols : MaxRows, ActualCols = Transpose ? MaxRows : MaxCols }; typedef typename conditional<Transpose,RhsScalar_,LhsScalar_>::type LhsScalar; typedef typename conditional<Transpose,LhsScalar_,RhsScalar_>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; enum { SizeA = ActualRows * MaxDepth, SizeB = ActualCols * MaxDepth }; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES EIGEN_ALIGN_MAX LhsScalar m_staticA[SizeA]; EIGEN_ALIGN_MAX RhsScalar m_staticB[SizeB]; #else EIGEN_ALIGN_MAX char m_staticA[SizeA * sizeof(LhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; EIGEN_ALIGN_MAX char m_staticB[SizeB * sizeof(RhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; #endif public: gemm_blocking_space(Index /*rows*/, Index /*cols*/, Index /*depth*/, Index /*num_threads*/, bool /*full_rows = false*/) { this->m_mc = ActualRows; this->m_nc = ActualCols; this->m_kc = MaxDepth; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES this->m_blockA = m_staticA; this->m_blockB = m_staticB; #else this->m_blockA = reinterpret_cast<LhsScalar*>((internal::UIntPtr(m_staticA) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); this->m_blockB = reinterpret_cast<RhsScalar*>((internal::UIntPtr(m_staticB) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); #endif } void initParallel(Index, Index, Index, Index) {} inline void allocateA() {} inline void allocateB() {} inline void allocateAll() {} }; template<int StorageOrder, typename LhsScalar_, typename RhsScalar_, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,LhsScalar_,RhsScalar_,MaxRows, MaxCols, MaxDepth, KcFactor, false> : public level3_blocking< typename conditional<StorageOrder==RowMajor,RhsScalar_,LhsScalar_>::type, typename conditional<StorageOrder==RowMajor,LhsScalar_,RhsScalar_>::type> { enum { Transpose = StorageOrder==RowMajor }; typedef typename conditional<Transpose,RhsScalar_,LhsScalar_>::type LhsScalar; typedef typename conditional<Transpose,LhsScalar_,RhsScalar_>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; Index m_sizeA; Index m_sizeB; public: gemm_blocking_space(Index rows, Index cols, Index depth, Index num_threads, bool l3_blocking) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; if(l3_blocking) { computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, this->m_nc, num_threads); } else // no l3 blocking { Index n = this->m_nc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, n, num_threads); } m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void initParallel(Index rows, Index cols, Index depth, Index num_threads) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; eigen_internal_assert(this->m_blockA==0 && this->m_blockB==0); Index m = this->m_mc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, m, this->m_nc, num_threads); m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void allocateA() { if(this->m_blockA==0) this->m_blockA = aligned_new<LhsScalar>(m_sizeA); } void allocateB() { if(this->m_blockB==0) this->m_blockB = aligned_new<RhsScalar>(m_sizeB); } void allocateAll() { allocateA(); allocateB(); } ~gemm_blocking_space() { aligned_delete(this->m_blockA, m_sizeA); aligned_delete(this->m_blockB, m_sizeB); } }; } // end namespace internal namespace internal { template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; typedef typename Lhs::Scalar LhsScalar; typedef typename Rhs::Scalar RhsScalar; typedef internal::blas_traits<Lhs> LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef typename internal::remove_all<ActualLhsType>::type ActualLhsTypeCleaned; typedef internal::blas_traits<Rhs> RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; typedef typename internal::remove_all<ActualRhsType>::type ActualRhsTypeCleaned; enum { MaxDepthAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(Lhs::MaxColsAtCompileTime,Rhs::MaxRowsAtCompileTime) }; typedef generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> lazyproduct; template<typename Dst> static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=404 for a discussion and helper program // to determine the following heuristic. // EIGEN_GEMM_TO_COEFFBASED_THRESHOLD is typically defined to 20 in GeneralProduct.h, // unless it has been specialized by the user or for a given architecture. // Note that the condition rhs.rows()>0 was required because lazy product is (was?) not happy with empty inputs. // I'm not sure it is still required. if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::assign_op<typename Dst::Scalar,Scalar>()); else { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } } template<typename Dst> static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::add_assign_op<typename Dst::Scalar,Scalar>()); else scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } template<typename Dst> static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::sub_assign_op<typename Dst::Scalar,Scalar>()); else scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& a_lhs, const Rhs& a_rhs, const Scalar& alpha) { eigen_assert(dst.rows()==a_lhs.rows() && dst.cols()==a_rhs.cols()); if(a_lhs.cols()==0 || a_lhs.rows()==0 || a_rhs.cols()==0) return; if (dst.cols() == 1) { // Fallback to GEMV if either the lhs or rhs is a runtime vector typename Dest::ColXpr dst_vec(dst.col(0)); return internal::generic_product_impl<Lhs,typename Rhs::ConstColXpr,DenseShape,DenseShape,GemvProduct> ::scaleAndAddTo(dst_vec, a_lhs, a_rhs.col(0), alpha); } else if (dst.rows() == 1) { // Fallback to GEMV if either the lhs or rhs is a runtime vector typename Dest::RowXpr dst_vec(dst.row(0)); return internal::generic_product_impl<typename Lhs::ConstRowXpr,Rhs,DenseShape,DenseShape,GemvProduct> ::scaleAndAddTo(dst_vec, a_lhs.row(0), a_rhs, alpha); } typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(a_lhs); typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(a_rhs); Scalar actualAlpha = combine_scalar_factors(alpha, a_lhs, a_rhs); typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,LhsScalar,RhsScalar, Dest::MaxRowsAtCompileTime,Dest::MaxColsAtCompileTime,MaxDepthAtCompileTime> BlockingType; typedef internal::gemm_functor< Scalar, Index, internal::general_matrix_matrix_product< Index, LhsScalar, (ActualLhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(LhsBlasTraits::NeedToConjugate), RhsScalar, (ActualRhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(RhsBlasTraits::NeedToConjugate), (Dest::Flags&RowMajorBit) ? RowMajor : ColMajor, Dest::InnerStrideAtCompileTime>, ActualLhsTypeCleaned, ActualRhsTypeCleaned, Dest, BlockingType> GemmFunctor; BlockingType blocking(dst.rows(), dst.cols(), lhs.cols(), 1, true); internal::parallelize_gemm<(Dest::MaxRowsAtCompileTime>32 || Dest::MaxRowsAtCompileTime==Dynamic)> (GemmFunctor(lhs, rhs, dst, actualAlpha, blocking), a_lhs.rows(), a_rhs.cols(), a_lhs.cols(), Dest::Flags&RowMajorBit); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_GENERAL_MATRIX_MATRIX_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 "magick/studio.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/string_.h" #include "magick/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 { MagickRealType 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 { MagickRealType tau; ssize_t left, right; MagickRealType mean_stability, stability; struct _IntervalTree *sibling, *child; } IntervalTree; typedef struct _ZeroCrossing { MagickRealType 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 MagickRealType 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 MagickRealType,MagickRealType *), ZeroCrossHistogram(MagickRealType *,const MagickRealType,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 MagickRealType cluster_threshold, % const MagickRealType weighting_exponent, % const MagickBooleanType verbose) % % 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 MagickRealType 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. % */ static MagickBooleanType Classify(Image *image,short **extrema, const MagickRealType cluster_threshold, const MagickRealType weighting_exponent,const MagickBooleanType verbose) { #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; ExceptionInfo *exception; ExtentPacket blue, green, red; MagickOffsetType progress; MagickRealType *free_squares; MagickStatusType status; register ssize_t i; register MagickRealType *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)); exception=(&image->exception); 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 PixelPacket *p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) 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(p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetPixelRed(p)); cluster->green.center+=(MagickRealType) ScaleQuantumToChar(GetPixelGreen(p)); cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetPixelBlue(p)); cluster->count++; break; } p++; } 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=(MagickRealType *) AcquireQuantumMemory(513UL,sizeof(*squares)); if (squares == (MagickRealType *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); squares+=255; for (i=(-255); i <= 255; i++) squares[i]=(MagickRealType) i*(MagickRealType) i; /* Allocate image colormap. */ if (AcquireImageColormap(image,number_clusters) == MagickFalse) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); i=0; for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) (cluster->red.center+0.5)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) (cluster->green.center+0.5)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) (cluster->blue.center+0.5)); i++; } /* Do course grain classes. */ exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Cluster *cluster; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,0); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { if (((ssize_t) ScaleQuantumToChar(q->red) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->red) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->green) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->green) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->blue) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->blue) <= (cluster->blue.right+SafeMargin))) { /* Classify this pixel. */ SetPixelIndex(indexes+x,cluster->id); break; } } if (cluster == (Cluster *) NULL) { MagickRealType 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(q->red)- (ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->green)- (ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->blue)- (ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]; numerator=distance_squared; for (k=0; k < (ssize_t) image->colors; k++) { p=image->colormap+k; distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)- (ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->green)- (ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->blue)- (ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]; 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(indexes+x,j); } } } q++; } 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); /* 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=(MagickRealType *) 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 MagickRealType *histogram, % MagickRealType *derivative) % % A description of each parameter follows. % % o histogram: Specifies an array of MagickRealTypes representing the number % of pixels for each intensity of a particular color component. % % o derivative: This array of MagickRealTypes is initialized by % DerivativeHistogram to the derivative of the histogram using central % differencing. % */ static void DerivativeHistogram(const MagickRealType *histogram, MagickRealType *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, % MagickPixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cluster_threshold: This MagickRealType 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, MagickPixelPacket *pixel,ExceptionInfo *exception) { Cluster *background, *cluster, *object, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickBooleanType proceed; MagickRealType threshold; register const PixelPacket *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); GetMagickPixelPacket(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 PixelPacket *) 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(p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetPixelRed(p)); cluster->green.center+=(MagickRealType) ScaleQuantumToChar(GetPixelGreen(p)); cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetPixelBlue(p)); cluster->count++; break; } p++; } 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=(MagickRealType) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->green.center+object->green.center)/2.0; pixel->green=(MagickRealType) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->blue.center+object->blue.center)/2.0; pixel->blue=(MagickRealType) 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 PixelPacket *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 PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(p))]++; histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]++; histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]++; p++; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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 MagickRealType sum; sum=0.0; count=0; for ( ; child != (IntervalTree *) NULL; child=child->sibling) { sum+=child->stability; count++; } node->mean_stability=sum/(MagickRealType) 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: % % MagickRealType 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 MagickRealType 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; MagickRealType 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=(MagickRealType *) AcquireCriticalMemory(256*sizeof(*derivative)); second_derivative=(MagickRealType *) 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]=(MagickRealType) 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=(MagickRealType *) RelinquishMagickMemory(derivative); second_derivative=(MagickRealType *) 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*=PerceptibleReciprocal((MagickRealType) 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 MagickRealType tau, % MagickRealType *scale_histogram) % % A description of each parameter follows. % % o histogram: Specifies an array of MagickRealTypes representing the number % of pixels for each intensity of a particular color component. % */ static void ScaleSpace(const ssize_t *histogram,const MagickRealType tau, MagickRealType *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=1.0/(tau*sqrt(2.0*MagickPI)); beta=(-1.0/(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]=(MagickRealType) (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) % % 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. % */ MagickExport MagickBooleanType SegmentImage(Image *image, const ColorspaceType colorspace,const MagickBooleanType verbose, const double cluster_threshold,const double smooth_threshold) { 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]); } ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename) } } /* Initialize histogram. */ previous_colorspace=image->colorspace; (void) TransformImageColorspace(image,colorspace); InitializeHistogram(image,histogram,&image->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); (void) TransformImageColorspace(image,previous_colorspace); /* 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(MagickRealType *second_derivative, % const MagickRealType smooth_threshold,short *crossings) % % A description of each parameter follows. % % o second_derivative: Specifies an array of MagickRealTypes 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(MagickRealType *second_derivative, const MagickRealType 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); } } }
GB_unop__expm1_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__expm1_fp32_fp32) // op(A') function: GB (_unop_tran__expm1_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = expm1f (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = expm1f (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = expm1f (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EXPM1 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__expm1_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = expm1f (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = expm1f (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__expm1_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 32; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_binop__isgt_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_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_uint8 // A.*B function (eWiseMult): GB_AemultB__isgt_uint8 // A*D function (colscale): GB_AxD__isgt_uint8 // D*A function (rowscale): GB_DxB__isgt_uint8 // C+=B function (dense accum): GB_Cdense_accumB__isgt_uint8 // C+=b function (dense accum): GB_Cdense_accumb__isgt_uint8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isgt_uint8 // C=scalar+B GB_bind1st__isgt_uint8 // C=scalar+B' GB_bind1st_tran__isgt_uint8 // C=A+scalar GB_bind2nd__isgt_uint8 // C=A'+scalar GB_bind2nd_tran__isgt_uint8 // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x > 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_ISGT || GxB_NO_UINT8 || GxB_NO_ISGT_UINT8) //------------------------------------------------------------------------------ // 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__isgt_uint8 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__isgt_uint8 ( 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__isgt_uint8 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__isgt_uint8 ( 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 uint8_t *GB_RESTRICT Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__isgt_uint8 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *GB_RESTRICT Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #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__isgt_uint8 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__isgt_uint8 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const 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__isgt_uint8 ( 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 uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = Bx [p] ; Cx [p] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__isgt_uint8 ( 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 ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = Ax [p] ; Cx [p] = (aij > 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) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB_bind1st_tran__isgt_uint8 ( 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 \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB_bind2nd_tran__isgt_uint8 ( 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 uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pf3dbenchvars.h
#include "mytypes.h" /* Storage for these variables needs to be allocated ONCE on the host. In the file responsible for allocating storage, define __parm_init__. */ #ifdef __parm_init__ #define EXTERN #else #define EXTERN extern #endif #ifndef _PF3DBENCHVARS_H_ #ifdef OMP45 #pragma omp declare target #endif EXTERN int ngrd; /* number of guard cells */ EXTERN int nxa, nya, nza; /* allocated box dimensions */ EXTERN int omp_maxthreads; EXTERN long ngtot, nplng, nmaxpln, ntheta; /* xy arrays */ EXTERN real *theta; /* rotation angles */ /* 3D arrays */ EXTERN rcomplex *tN_new; /* temp storage for a new light wave */ EXTERN real *thetb; /* angles as a function of z */ EXTERN real *thetb_sav; /* angles as a function of z backup*/ EXTERN char *cbuf; #ifdef OMP45 #pragma omp end declare target #endif #endif #define _PF3DBENCHVARS_H_
ConcurrentLocalIdMap.h
#pragma once #include <cassert> #include <cstdint> #include <numeric> #include <vector> #include <omp.h> // This class maps a set of n IDs in the range 0..m - 1 to the range 0..n - 1, preserving the // relative order. We call the IDs in the larger range global IDs, and the IDs in the smaller // range local IDs. Note that the local IDs are sequential. This class takes the set of mapped // global IDs as a vector of 8-bit integers instead of as a bit vector. A zero value indicates // that a global ID is not mapped to a local ID. template <int k = 64> class ConcurrentLocalIdMap { public: // Constructs a map from the specified set of n global IDs to the range 0..n - 1. explicit ConcurrentLocalIdMap(const std::vector<int8_t>& mappedGlobalIds) : mappedGlobalIds(mappedGlobalIds), numMappedGlobalIds((mappedGlobalIds.size() + k - 1) / k + 1) { std::vector<int> sums; #pragma omp parallel { #pragma omp single sums.assign(omp_get_num_threads() + 1, 0); int sum = 0; #pragma omp for schedule(static) nowait for (int i = 0; i < mappedGlobalIds.size() / k; ++i) { for (int j = 0; j < k; ++j) sum += mappedGlobalIds[i * k + j]; numMappedGlobalIds[i + 1] = sum; } if (omp_get_num_threads() > 1) { sums[omp_get_thread_num() + 1] = sum; #pragma omp barrier #pragma omp single std::partial_sum(sums.begin(), sums.end(), sums.begin()); #pragma omp for schedule(static) nowait for (int i = 0; i < mappedGlobalIds.size() / k; ++i) numMappedGlobalIds[i + 1] += sums[omp_get_thread_num()]; } } const int i = mappedGlobalIds.size() / k; if (i + 1 < numMappedGlobalIds.size()) { numMappedGlobalIds[i + 1] = numMappedGlobalIds[i]; for (int j = i * k; j < mappedGlobalIds.size(); ++j) numMappedGlobalIds[i + 1] += mappedGlobalIds[j]; } } // Returns the size m of the range of global IDs. int numGlobalIds() const { return mappedGlobalIds.size(); } // Returns the size n of the range of local IDs. int numLocalIds() const { assert(!numMappedGlobalIds.empty()); return numMappedGlobalIds.back(); } // Returns true if globalId is mapped to a local ID. bool isGlobalIdMapped(const int globalId) const { assert(globalId >= 0); assert(globalId < numGlobalIds()); return mappedGlobalIds[globalId]; } // Returns the local ID globalId is mapped to. int toLocalId(const int globalId) const { assert(isGlobalIdMapped(globalId)); return numMappedGlobalIdsBefore(globalId); } // Returns the number of mapped global IDs before globalId. int numMappedGlobalIdsBefore(const int globalId) const { assert(globalId >= 0); assert(globalId < numGlobalIds()); int sum = numMappedGlobalIds[globalId / k]; for (int i = globalId / k * k; i < globalId; ++i) sum += mappedGlobalIds[i]; return sum; } private: const std::vector<int8_t>& mappedGlobalIds; // The set of mapped global IDs. std::vector<int32_t> numMappedGlobalIds; // Stores the nmb of mapped IDs before every k-th ID. };
nodal_residualbased_elimination_builder_and_solver_continuity.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi, Alessandro Franci // // #if !defined(KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_CONTINUITY) #define KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_CONTINUITY /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* External includes */ // #define USE_GOOGLE_HASH #ifdef USE_GOOGLE_HASH #include "sparsehash/dense_hash_set" //included in external libraries #else #include <unordered_set> #endif /* Project includes */ #include "utilities/timer.h" #include "includes/define.h" #include "includes/key_hash.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "pfem_fluid_dynamics_application_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class NodalResidualBasedEliminationBuilderAndSolverContinuity * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @author Riccardo Rossi */ template <class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class NodalResidualBasedEliminationBuilderAndSolverContinuity : public BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedEliminationBuilderAndSolverContinuity); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef Node<3> NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef Vector VectorType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ NodalResidualBasedEliminationBuilderAndSolverContinuity( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pNewLinearSystemSolver) { // KRATOS_INFO("NodalResidualBasedEliminationBuilderAndSolverContinuity") << "Using the standard builder and solver " << std::endl; } /** Destructor. */ ~NodalResidualBasedEliminationBuilderAndSolverContinuity() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void BuildNodally( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double pressure = 0; double deltaPressure = 0; double meanMeshSize = 0; double characteristicLength = 0; double density = 0; double nodalVelocityNorm = 0; double tauStab = 0; double dNdXi = 0; double dNdYi = 0; double dNdZi = 0; double dNdXj = 0; double dNdYj = 0; double dNdZj = 0; unsigned int firstRow = 0; unsigned int firstCol = 0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() + 1; if (neighSize > 1) { const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); noalias(LHS_Contribution) = ZeroMatrix(neighSize, neighSize); noalias(RHS_Contribution) = ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } if (deviatoricCoeff > 0.1) { deviatoricCoeff = 0.1; } double volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += -deltaPressure * nodalVolume / volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE) * nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0] = itNode->GetDof(PRESSURE, xDofPos).EquationId(); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { EquationId[i + 1] = neighb_nodes[i].GetDof(PRESSURE, xDofPos).EquationId(); } firstRow = 0; firstCol = 0; meanMeshSize = itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength = 1.0 * meanMeshSize; density = itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if (dimension == 2) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if (dimension == 3) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z) * itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab = 1.0 * (characteristicLength * characteristicLength * timeInterval) / (density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval); itNode->FastGetSolutionStepValue(NODAL_TAU) = tauStab; /* std::cout<<"tauStab= "<<tauStab<<std::endl; */ LHS_Contribution(0, 0) += +nodalVolume * tauStab * density / (volumetricCoeff * timeInterval); RHS_Contribution[0] += -nodalVolume * tauStab * density / (volumetricCoeff * timeInterval) * (deltaPressure - itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) * timeInterval); if (itNode->Is(FREE_SURFACE)) { // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0, 0) += +4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += -4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE, 0); const array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector &SpatialDefRate = itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration = 0.5 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration = 0; double nodalNormalProjDefRate = 0; if (dimension == 2) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + 2 * Normal[0] * SpatialDefRate[2] * Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration = Normal[0] * nodalAcceleration[0] + Normal[1] * nodalAcceleration[1]; } else if (dimension == 3) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + Normal[2] * SpatialDefRate[2] * Normal[2] + 2 * Normal[0] * SpatialDefRate[3] * Normal[1] + 2 * Normal[0] * SpatialDefRate[4] * Normal[2] + 2 * Normal[1] * SpatialDefRate[5] * Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution = 2.0 * density * nodalNormalAcceleration / meanMeshSize; double deviatoricContribution = 8.0 * deviatoricCoeff * nodalNormalProjDefRate / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += 1.0 * tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } array_1d<double, 3> &VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); // double posX= itNode->X(); // double posY= itNode->Y(); // double coeffX =(12.0-24.0*posY)*pow(posX,4); // coeffX += (-24.0+48.0*posY)*pow(posX,3); // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // double coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 1]; if (i != 0) { // i==0 of EquationIs has been already filled with the master node (that is not included in neighb_nodes). The next is stored for i+1 EquationId[i] = neighb_nodes[i - 1].GetDof(PRESSURE, xDofPos).EquationId(); // at i==0 density and volume acceleration are taken from the master node density = neighb_nodes[i - 1].FastGetSolutionStepValue(DENSITY); // VolumeAcceleration = neighb_nodes[i-1].FastGetSolutionStepValue(VOLUME_ACCELERATION); // // posX= neighb_nodes[i-1].X(); // // posY= neighb_nodes[i-1].Y(); // // coeffX =(12.0-24.0*posY)*pow(posX,4); // // coeffX += (-24.0+48.0*posY)*pow(posX,3); // // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // // coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); } if (dimension == 2) { // RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0]*coeffX + dNdYi* VolumeAcceleration[1]*coeffY) * nodalVolume; RHS_Contribution[i] += -tauStab * density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1]) * nodalVolume; } else if (dimension == 3) { dNdZi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 2]; RHS_Contribution[i] += -tauStab * density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1] + dNdZi * VolumeAcceleration[2]) * nodalVolume; } firstRow = 0; for (unsigned int j = 0; j < neighSize; j++) { dNdXj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 1]; // double Vx=itNode->FastGetSolutionStepValue(VELOCITY_X,0); // double Vy=itNode->FastGetSolutionStepValue(VELOCITY_Y,0); if (j != 0) { pressure = neighb_nodes[j - 1].FastGetSolutionStepValue(PRESSURE, 0); // Vx= neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X,0); // Vy= neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y,0); // meanMeshSize=neighb_nodes[j-1].FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); // characteristicLength=2.0*meanMeshSize; // density=neighb_nodes[j-1].FastGetSolutionStepValue(DENSITY); // if(dimension==2){ // nodalVelocityNorm= sqrt(neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)); // }else if(dimension==3){ // nodalVelocityNorm=sqrt(neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Z)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Z)); // } } else { pressure = itNode->FastGetSolutionStepValue(PRESSURE, 0); // meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); // characteristicLength=2.0*meanMeshSize; // density=itNode->FastGetSolutionStepValue(DENSITY); // if(dimension==2){ // nodalVelocityNorm= sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + // itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); // }else if(dimension==3){ // nodalVelocityNorm=sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + // itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + // itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); // } } // tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); if (dimension == 2) { // // ////////////////// Laplacian term for LHS LHS_Contribution(i, j) += +tauStab * (dNdXi * dNdXj + dNdYi * dNdYj) * nodalVolume; // // ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += -tauStab * (dNdXi * dNdXj + dNdYi * dNdYj) * nodalVolume * pressure; // RHS_Contribution[i] += (dNdXj*Vx + dNdYj*Vy)*nodalVolume/3.0; // LHS_Contribution(i,j)+= nodalVolume/volumetricCoeff/(1.0+double(neighSize)); // if(i==j){ // RHS_Contribution[i] += (-deltaPressure/volumetricCoeff )*nodalVolume; // } } else if (dimension == 3) { dNdZj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 2]; ////////////////// Laplacian term for LHS LHS_Contribution(i, j) += +tauStab * (dNdXi * dNdXj + dNdYi * dNdYj + dNdZi * dNdZj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += -tauStab * (dNdXi * dNdXj + dNdYi * dNdYj + dNdZi * dNdZj) * nodalVolume * pressure; } firstRow += dimension; } firstCol += dimension; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyUnlessLaplacian( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure = 0; double meanMeshSize = 0; double characteristicLength = 0; double density = 0; double nodalVelocityNorm = 0; double tauStab = 0; double dNdXi = 0; double dNdYi = 0; double dNdZi = 0; unsigned int firstCol = 0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() + 1; if (neighSize > 1) { const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); noalias(LHS_Contribution) = ZeroMatrix(neighSize, neighSize); noalias(RHS_Contribution) = ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } if (deviatoricCoeff > 0.1) { deviatoricCoeff = 0.1; } double volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += -deltaPressure * nodalVolume / volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE) * nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0] = itNode->GetDof(PRESSURE, xDofPos).EquationId(); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { EquationId[i + 1] = neighb_nodes[i].GetDof(PRESSURE, xDofPos).EquationId(); } firstCol = 0; meanMeshSize = itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength = 1.0 * meanMeshSize; density = itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if (dimension == 2) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if (dimension == 3) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z) * itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab = 1.0 * (characteristicLength * characteristicLength * timeInterval) / (density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval); itNode->FastGetSolutionStepValue(NODAL_TAU) = tauStab; LHS_Contribution(0, 0) += +nodalVolume * tauStab * density / (volumetricCoeff * timeInterval); RHS_Contribution[0] += -nodalVolume * tauStab * density / (volumetricCoeff * timeInterval) * (deltaPressure - itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) * timeInterval); if (itNode->Is(FREE_SURFACE)) { // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0, 0) += +4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += -4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE, 0); array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector &SpatialDefRate = itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration = 0.5 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration = 0; double nodalNormalProjDefRate = 0; if (dimension == 2) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + 2 * Normal[0] * SpatialDefRate[2] * Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration = Normal[0] * nodalAcceleration[0] + Normal[1] * nodalAcceleration[1]; } else if (dimension == 3) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + Normal[2] * SpatialDefRate[2] * Normal[2] + 2 * Normal[0] * SpatialDefRate[3] * Normal[1] + 2 * Normal[0] * SpatialDefRate[4] * Normal[2] + 2 * Normal[1] * SpatialDefRate[5] * Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution = 2.0 * density * nodalNormalAcceleration / meanMeshSize; double deviatoricContribution = 8.0 * deviatoricCoeff * nodalNormalProjDefRate / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += 1.0 * tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } array_1d<double, 3> &VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); // double posX= itNode->X(); // double posY= itNode->Y(); // double coeffX =(12.0-24.0*posY)*pow(posX,4); // coeffX += (-24.0+48.0*posY)*pow(posX,3); // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // double coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 1]; if (i != 0) { // i==0 of EquationIs has been already filled with the master node (that is not included in neighb_nodes). The next is stored for i+1 EquationId[i] = neighb_nodes[i - 1].GetDof(PRESSURE, xDofPos).EquationId(); // at i==0 density and volume acceleration are taken from the master node density = neighb_nodes[i - 1].FastGetSolutionStepValue(DENSITY); // // VolumeAcceleration = neighb_nodes[i-1].FastGetSolutionStepValue(VOLUME_ACCELERATION); // // posX= neighb_nodes[i-1].X(); // // posY= neighb_nodes[i-1].Y(); // // coeffX =(12.0-24.0*posY)*pow(posX,4); // // coeffX += (-24.0+48.0*posY)*pow(posX,3); // // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // // coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); } if (dimension == 2) { // RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0]*coeffX + dNdYi* VolumeAcceleration[1]*coeffY) * nodalVolume; RHS_Contribution[i] += -tauStab * density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1]) * nodalVolume; } else if (dimension == 3) { dNdZi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 2]; RHS_Contribution[i] += -tauStab * density * (dNdXi * VolumeAcceleration[0] + dNdYi * VolumeAcceleration[1] + dNdZi * VolumeAcceleration[2]) * nodalVolume; } firstCol += dimension; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyNoVolumetricStabilizedTerms( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure = 0; double meanMeshSize = 0; double characteristicLength = 0; double density = 0; double nodalVelocityNorm = 0; double tauStab = 0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() + 1; if (neighSize > 1) { const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); noalias(LHS_Contribution) = ZeroMatrix(neighSize, neighSize); noalias(RHS_Contribution) = ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } if (deviatoricCoeff > 0.1) { deviatoricCoeff = 0.1; } double volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += -deltaPressure * nodalVolume / volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE) * nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0] = itNode->GetDof(PRESSURE, xDofPos).EquationId(); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { EquationId[i + 1] = neighb_nodes[i].GetDof(PRESSURE, xDofPos).EquationId(); } meanMeshSize = itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength = 1.0 * meanMeshSize; density = itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if (dimension == 2) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if (dimension == 3) { nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X) * itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y) * itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z) * itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab = 1.0 * (characteristicLength * characteristicLength * timeInterval) / (density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval); itNode->FastGetSolutionStepValue(NODAL_TAU) = tauStab; LHS_Contribution(0, 0) += +nodalVolume * tauStab * density / (volumetricCoeff * timeInterval); RHS_Contribution[0] += -nodalVolume * tauStab * density / (volumetricCoeff * timeInterval) * (deltaPressure - itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) * timeInterval); if (itNode->Is(FREE_SURFACE)) { // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0, 0) += +4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += -4.0 * tauStab * nodalVolume / (meanMeshSize * meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE, 0); array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector &SpatialDefRate = itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration = 0.5 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration = 0; double nodalNormalProjDefRate = 0; if (dimension == 2) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + 2 * Normal[0] * SpatialDefRate[2] * Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration = Normal[0] * nodalAcceleration[0] + Normal[1] * nodalAcceleration[1]; } else if (dimension == 3) { nodalNormalProjDefRate = Normal[0] * SpatialDefRate[0] * Normal[0] + Normal[1] * SpatialDefRate[1] * Normal[1] + Normal[2] * SpatialDefRate[2] * Normal[2] + 2 * Normal[0] * SpatialDefRate[3] * Normal[1] + 2 * Normal[0] * SpatialDefRate[4] * Normal[2] + 2 * Normal[1] * SpatialDefRate[5] * Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution = 2.0 * density * nodalNormalAcceleration / meanMeshSize; double deviatoricContribution = 8.0 * deviatoricCoeff * nodalNormalProjDefRate / (meanMeshSize * meanMeshSize); RHS_Contribution[0] += 1.0 * tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyNotStabilized( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure = 0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() + 1; if (neighSize > 1) { const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); noalias(LHS_Contribution) = ZeroMatrix(neighSize, neighSize); noalias(RHS_Contribution) = ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } if (deviatoricCoeff > 0.1) { deviatoricCoeff = 0.1; } double volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += -deltaPressure * nodalVolume / volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE) * nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0] = itNode->GetDof(PRESSURE, xDofPos).EquationId(); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { EquationId[i + 1] = neighb_nodes[i].GetDof(PRESSURE, xDofPos).EquationId(); } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildAll( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure = 0; /* #pragma omp parallel */ // { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() + 1; if (neighSize > 1) { // if (LHS_Contribution.size1() != neighSize) // LHS_Contribution.resize(neighSize, neighSize, false); //false says not to preserve existing storage!! // if (RHS_Contribution.size() != neighSize) // RHS_Contribution.resize(neighSize, false); //false says not to preserve existing storage!! // LHS_Contribution= ZeroMatrix(neighSize,neighSize); // RHS_Contribution= ZeroVector(neighSize); // if (EquationId.size() != neighSize) // EquationId.resize(neighSize, false); if (LHS_Contribution.size1() != 1) LHS_Contribution.resize(1, 1, false); //false says not to preserve existing storage!! if (RHS_Contribution.size() != 1) RHS_Contribution.resize(1, false); //false says not to preserve existing storage!! noalias(LHS_Contribution) = ZeroMatrix(1, 1); noalias(RHS_Contribution) = ZeroVector(1); if (EquationId.size() != 1) EquationId.resize(1, false); double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); if (nodalVolume > 0) { // in interface nodes not in contact with fluid elements the nodal volume is zero double deviatoricCoeff = itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } if (deviatoricCoeff > 0.1) { deviatoricCoeff = 0.1; } double volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) - itNode->FastGetSolutionStepValue(PRESSURE, 1); LHS_Contribution(0, 0) += nodalVolume / volumetricCoeff; RHS_Contribution[0] += -deltaPressure * nodalVolume / volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE) * nodalVolume; } const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0] = itNode->GetDof(PRESSURE, xDofPos).EquationId(); #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } //} } // } ElementsArrayType &pElements = rModelPart.Elements(); int number_of_threads = ParallelUtilities::GetNumThreads(); #ifdef _OPENMP int A_size = A.size1(); //creating an array of lock variables of the size of the system matrix std::vector<omp_lock_t> lock_array(A.size1()); for (int i = 0; i < A_size; i++) omp_init_lock(&lock_array[i]); #endif DenseVector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if (this->GetEchoLevel() > 0) { KRATOS_WATCH(number_of_threads); KRATOS_WATCH(element_partition); } #pragma omp parallel for firstprivate(number_of_threads) schedule(static, 1) for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemMatrixType elementalLHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType elementalRHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType elementalEquationId; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin = pElements.ptr_begin() + element_partition[k]; typename ElementsArrayType::ptr_iterator it_end = pElements.ptr_begin() + element_partition[k + 1]; unsigned int pos = (rModelPart.Nodes().begin())->GetDofPosition(PRESSURE); // assemble all elements for (typename ElementsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution (*it)->CalculateLocalSystem(elementalLHS_Contribution, elementalRHS_Contribution, CurrentProcessInfo); Geometry<Node<3>> &geom = (*it)->GetGeometry(); if (elementalEquationId.size() != geom.size()) elementalEquationId.resize(geom.size(), false); for (unsigned int i = 0; i < geom.size(); i++) elementalEquationId[i] = geom[i].GetDof(PRESSURE, pos).EquationId(); //assemble the elemental contribution #ifdef _OPENMP this->Assemble(A, b, elementalLHS_Contribution, elementalRHS_Contribution, elementalEquationId, lock_array); #else this->Assemble(A, b, elementalLHS_Contribution, elementalRHS_Contribution, elementalEquationId); #endif } } #ifdef _OPENMP for (int i = 0; i < A_size; i++) omp_destroy_lock(&lock_array[i]); #endif KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b, ModelPart &rModelPart) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if (BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded()) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY Timer::Start("Build"); /* boost::timer c_build_time; */ ///////////////////////////////// ALL NODAL ///////////////////////////////// //BuildNodally(pScheme, rModelPart, A, b); ///////////////////////////////// ALL NODAL ///////////////////////////////// // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// //BuildNodallyUnlessLaplacian(pScheme, rModelPart, A, b); //Build(pScheme, rModelPart, A, b); // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// //////////////// NODAL + ELEMENTAL VOLUMETRIC STABILIZED TERMS//////////////// //BuildNodallyNoVolumetricStabilizedTerms(pScheme, rModelPart, A, b); //Build(pScheme, rModelPart, A, b); // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// /////////////////////// NODAL + ELEMENTAL STABILIZATION ////////////////////// // BuildNodallyNotStabilized(pScheme, rModelPart, A, b); // Build(pScheme, rModelPart, A, b); BuildAll(pScheme, rModelPart, A, b); /////////////////////// NODAL + ELEMENTAL STABILIZATION ////////////////////// //////////////////////// ALL ELEMENTAL (FOR HYBRID) ////////////////////////// //Build(pScheme, rModelPart, A, b); //////////////////////// ALL ELEMENTAL (FOR HYBRID) ////////////////////////// Timer::Stop("Build"); // ApplyPointLoads(pScheme,rModelPart,b); // Does nothing...dirichlet conditions are naturally dealt with in defining the residual ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; /* const double start_solve = OpenMPUtils::GetCurrentTime(); */ Timer::Start("Solve"); /* boost::timer c_solve_time; */ SystemSolveWithPhysics(A, Dx, b, rModelPart); /* std::cout << "CONTINUITY EQ: solve_time : " << c_solve_time.elapsed() << std::endl; */ Timer::Stop("Solve"); /* const double stop_solve = OpenMPUtils::GetCurrentTime(); */ KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } void Build( typename TSchemeType::Pointer pScheme, ModelPart &r_model_part, TSystemMatrixType &A, TSystemVectorType &b) override { KRATOS_TRY if (!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); //getting the elements from the model ElementsArrayType &pElements = r_model_part.Elements(); // //getting the array of the conditions // ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); //resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); //create a partition of the element array int number_of_threads = ParallelUtilities::GetNumThreads(); #ifdef _OPENMP int A_size = A.size1(); //creating an array of lock variables of the size of the system matrix std::vector<omp_lock_t> lock_array(A.size1()); for (int i = 0; i < A_size; i++) omp_init_lock(&lock_array[i]); #endif DenseVector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if (this->GetEchoLevel() > 0) { KRATOS_WATCH(number_of_threads); KRATOS_WATCH(element_partition); } // double start_prod = OpenMPUtils::GetCurrentTime(); #pragma omp parallel for firstprivate(number_of_threads) schedule(static, 1) for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; const ProcessInfo &CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin = pElements.ptr_begin() + element_partition[k]; typename ElementsArrayType::ptr_iterator it_end = pElements.ptr_begin() + element_partition[k + 1]; unsigned int pos = (r_model_part.Nodes().begin())->GetDofPosition(PRESSURE); // assemble all elements for (typename ElementsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution (*it)->CalculateLocalSystem(LHS_Contribution, RHS_Contribution, CurrentProcessInfo); Geometry<Node<3>> &geom = (*it)->GetGeometry(); if (EquationId.size() != geom.size()) EquationId.resize(geom.size(), false); for (unsigned int i = 0; i < geom.size(); i++) EquationId[i] = geom[i].GetDof(PRESSURE, pos).EquationId(); //assemble the elemental contribution #ifdef _OPENMP this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, lock_array); #else this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } // if (this->GetEchoLevel() > 0) // { // double stop_prod = OpenMPUtils::GetCurrentTime(); // std::cout << "parallel building time: " << stop_prod - start_prod << std::endl; // } #ifdef _OPENMP for (int i = 0; i < A_size; i++) omp_destroy_lock(&lock_array[i]); #endif KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart) override { KRATOS_TRY; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType &pElements = rModelPart.Elements(); const int nelements = static_cast<int>(pElements.size()); Element::DofsVectorType ElementalDofList; const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); unsigned int nthreads = ParallelUtilities::GetNumThreads(); // typedef boost::fast_pool_allocator< NodeType::DofType::Pointer > allocator_type; // typedef std::unordered_set < NodeType::DofType::Pointer, // DofPointerHasher, // DofPointerComparor, // allocator_type > set_type; #ifdef USE_GOOGLE_HASH typedef google::dense_hash_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #else typedef std::unordered_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #endif // std::vector<set_type> dofs_aux_list(nthreads); // std::vector<allocator_type> allocators(nthreads); for (int i = 0; i < static_cast<int>(nthreads); i++) { #ifdef USE_GOOGLE_HASH dofs_aux_list[i].set_empty_key(NodeType::DofType::Pointer()); #else // dofs_aux_list[i] = set_type( allocators[i]); dofs_aux_list[i].reserve(nelements); #endif } // #pragma omp parallel for firstprivate(nelements, ElementalDofList) for (int i = 0; i < static_cast<int>(nelements); ++i) { auto it_elem = pElements.begin() + i; const IndexType this_thread_id = OpenMPUtils::ThisThread(); // Gets list of Dof involved on every element pScheme->GetDofList(*it_elem, ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } // ConditionsArrayType& pConditions = rModelPart.Conditions(); // const int nconditions = static_cast<int>(pConditions.size()); // #pragma omp parallel for firstprivate(nconditions, ElementalDofList) // for (int i = 0; i < nconditions; i++) // { // typename ConditionsArrayType::iterator it = pConditions.begin() + i; // const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // // gets list of Dof involved on every element // pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); // dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); // } //here we do a reduction in a tree so to have everything on thread 0 unsigned int old_max = nthreads; unsigned int new_max = ceil(0.5 * static_cast<double>(old_max)); while (new_max >= 1 && new_max != old_max) { // //just for debugging // std::cout << "old_max" << old_max << " new_max:" << new_max << std::endl; // for (int i = 0; i < new_max; i++) // { // if (i + new_max < old_max) // { // std::cout << i << " - " << i + new_max << std::endl; // } // } // std::cout << "********************" << std::endl; #pragma omp parallel for for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { dofs_aux_list[i].insert(dofs_aux_list[i + new_max].begin(), dofs_aux_list[i + new_max].end()); dofs_aux_list[i + new_max].clear(); } } old_max = new_max; new_max = ceil(0.5 * static_cast<double>(old_max)); } DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dofs_aux_list[0].size()); for (auto it = dofs_aux_list[0].begin(); it != dofs_aux_list[0].end(); it++) { Doftemp.push_back((*it)); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; // Throws an execption if there are no Degrees of freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0) << "Finished setting up the dofs" << std::endl; #ifdef _OPENMP if (mlock_array.size() != 0) { for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_destroy_lock(&mlock_array[i]); } mlock_array.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_init_lock(&mlock_array[i]); #endif // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if (BaseType::GetCalculateReactionsFlag()) { for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " << std::endl << "Node : " << dof_iterator->Id() << std::endl << "Dof : " << (*dof_iterator) << std::endl << "Not possible to calculate reactions." << std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart &rModelPart) override { // Set equation id for degrees of freedom // the free degrees of freedom are positioned at the beginning of the system, // while the fixed one are at the end (in opposite order). // // that means that if the EquationId is greater than "mEquationSystemSize" // the pointed degree of freedom is restrained // int free_id = 0; int fix_id = BaseType::mDofSet.size(); for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) if (dof_iterator->IsFixed()) dof_iterator->SetEquationId(--fix_id); else dof_iterator->SetEquationId(free_id++); BaseType::mEquationSystemSize = fix_id; } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType &pA, TSystemVectorPointerType &pDx, TSystemVectorPointerType &pb, ModelPart &rModelPart) override { KRATOS_TRY /* boost::timer c_contruct_matrix; */ if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } if (BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0)); BaseType::mpReactionsVector.swap(pNewReactionsVector); } TSystemMatrixType &A = *pA; TSystemVectorType &Dx = *pDx; TSystemVectorType &b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH("it should not come here!!!!!!!! ... this is SLOW"); KRATOS_ERROR << "The equation system size has changed during the simulation. This is not permited." << std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //if needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag == true) { unsigned int ReactionsVectorSize = BaseType::mDofSet.size(); if (BaseType::mpReactionsVector->size() != ReactionsVectorSize) BaseType::mpReactionsVector->resize(ReactionsVectorSize, false); } /* std::cout << "CONTINUITY EQ: contruct_matrix : " << c_contruct_matrix.elapsed() << std::endl; */ KRATOS_CATCH("") } //************************************************************************** //************************************************************************** /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { this->mDofSet = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); // this->mReactionsVector = TSystemVectorType(); this->mpLinearSystemSolver->Clear(); KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1) << "Clear Function called" << std::endl; } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart &rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ void Assemble( TSystemMatrixType &A, TSystemVectorType &b, const LocalSystemMatrixType &LHS_Contribution, const LocalSystemVectorType &RHS_Contribution, const Element::EquationIdVectorType &EquationId #ifdef _OPENMP , std::vector<omp_lock_t> &lock_array #endif ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&lock_array[i_global]); #endif b[i_global] += RHS_Contribution(i_local); for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) { A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } #ifdef _OPENMP omp_unset_lock(&lock_array[i_global]); #endif } //note that assembly on fixed rows is not performed here } } //************************************************************************** virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType &A, ModelPart &rModelPart) { //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); const std::size_t equation_size = BaseType::mEquationSystemSize; std::vector<std::unordered_set<std::size_t>> indices(equation_size); #pragma omp parallel for firstprivate(equation_size) for (int iii = 0; iii < static_cast<int>(equation_size); iii++) { indices[iii].reserve(40); } Element::EquationIdVectorType ids(3, 0); #pragma omp parallel firstprivate(ids) { // The process info ProcessInfo &r_current_process_info = rModelPart.GetProcessInfo(); // We repeat the same declaration for each thead std::vector<std::unordered_set<std::size_t>> temp_indexes(equation_size); #pragma omp for for (int index = 0; index < static_cast<int>(equation_size); ++index) temp_indexes[index].reserve(30); // Getting the size of the array of elements from the model const int number_of_elements = static_cast<int>(rModelPart.Elements().size()); // Element initial iterator const auto el_begin = rModelPart.ElementsBegin(); // We iterate over the elements #pragma omp for schedule(guided, 512) nowait for (int i_elem = 0; i_elem < number_of_elements; ++i_elem) { auto it_elem = el_begin + i_elem; pScheme->EquationId(*it_elem, ids, r_current_process_info); for (auto &id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto &row_indices = temp_indexes[id_i]; for (auto &id_j : ids) if (id_j < BaseType::mEquationSystemSize) row_indices.insert(id_j); } } } // Getting the size of the array of the conditions const int number_of_conditions = static_cast<int>(rModelPart.Conditions().size()); // Condition initial iterator const auto cond_begin = rModelPart.ConditionsBegin(); // We iterate over the conditions #pragma omp for schedule(guided, 512) nowait for (int i_cond = 0; i_cond < number_of_conditions; ++i_cond) { auto it_cond = cond_begin + i_cond; pScheme->EquationId(*it_cond, ids, r_current_process_info); for (auto &id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto &row_indices = temp_indexes[id_i]; for (auto &id_j : ids) if (id_j < BaseType::mEquationSystemSize) row_indices.insert(id_j); } } } // Merging all the temporal indexes #pragma omp critical { for (int i = 0; i < static_cast<int>(temp_indexes.size()); ++i) { indices[i].insert(temp_indexes[i].begin(), temp_indexes[i].end()); } } } //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) nnz += indices[i].size(); A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); double *Avalues = A.value_data().begin(); std::size_t *Arow_indices = A.index1_data().begin(); std::size_t *Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) Arow_indices[i + 1] = Arow_indices[i] + indices[i].size(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(A.size1()); i++) { const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i + 1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); } A.set_filled(indices.size() + 1, nnz); Timer::Stop("MatrixStructure"); } void AssembleLHS( TSystemMatrixType &A, LocalSystemMatrixType &LHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ #ifdef _OPENMP std::vector<omp_lock_t> mlock_array; #endif ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t> &v, const std::size_t &candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, DenseVector<unsigned int> &partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } void AssembleRHS( TSystemVectorType &b, const LocalSystemVectorType &RHS_Contribution, const Element::EquationIdVectorType &EquationId) { unsigned int local_size = RHS_Contribution.size(); if (BaseType::mCalculateReactionsFlag == false) { for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double &b_value = b[i_global]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } else { TSystemVectorType &ReactionsVector = *BaseType::mpReactionsVector; for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double &b_value = b[i_global]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } else //fixed dof { double &b_value = ReactionsVector[i_global - BaseType::mEquationSystemSize]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } } //************************************************************************** void AssembleLHS_CompleteOnFreeRows( TSystemMatrixType &A, LocalSystemMatrixType &LHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class NodalResidualBasedEliminationBuilderAndSolverContinuity */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER defined */
stresslet_rsrc.c
#include "mex.h" #include "math.h" #define X prhs[0] // Source locations #define F prhs[1] // Source strengths #define IDX prhs[2] // Source indeces #define DIS prhs[3] // Distances #define XI prhs[4] // Ewald Param #define U plhs[0] // Output #ifndef VERBOSE #define VERBOSE 0 #endif #define PI 3.141592653589793 static inline double dot(double x[], double y[]) { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // input target const int M = mxGetM(X); const double xi = (double) mxGetScalar(XI); const double* restrict x = mxGetPr(X); const double* restrict f = mxGetPr(F); const double* restrict qvec = f; const double* restrict nvec = f + 3*M; // output U = mxCreateDoubleMatrix(M, 3, mxREAL); double* restrict u = mxGetPr(U); if(VERBOSE) mexPrintf("[FS Stresslet Real space ] MEX N=%d ",M); double xi2 = xi*xi; double xi3 = xi2*xi; // Loop through the cell #ifdef _OPENMP #pragma omp parallel for #endif for (int m=0; m<M; m++) { const mxArray * _IDX = mxGetCell(IDX, m); const mxArray * _DIS = mxGetCell(DIS, m); const int N= mxGetN(_IDX); // number of the source points in nblist double* idx= (double*) mxGetPr(_IDX);// index pointer of the source points in nblist double* dis= mxGetPr(_DIS); // distance pointer of the source points in nblist double p[3]; p[0] = 0; p[1] = 0; p[2] = 0; // First element is the target itself; see MATLAB doc for rangesearch. for(int n = 1; n<N; n++){ int idxn = (int) idx[n]-1; double qn[] = {qvec[idxn], qvec[idxn+M], qvec[idxn+2*M]}; double nn[] = {nvec[idxn], nvec[idxn+M], nvec[idxn+2*M]}; double rvec[] = {x[m]-x[idxn], x[m+M]-x[idxn+M],x[m+2*M]-x[idxn+2*M]}; double r = dis[n]; double r2= r*r; double c = xi2*r2; double expc = exp(-c); // Hasimoto double C = -2/(r2*r2)*( 3.0/r*erfc(xi*r) + 2.0*xi/sqrt(PI)*(3.0+2.0*c)*expc ); double D = 4/sqrt(PI)*xi3*expc; double rdotn = dot(rvec, nn); double rdotq = dot(rvec, qn); double ndotq = dot(nn, qn); double Kr = C*rdotn*rdotq + D*ndotq; double Kn = D*rdotq; double Kq = D*rdotn; for (int i=0; i<3; i++) { p[i] += Kr*rvec[i] + Kn*nn[i] + Kq*qn[i]; } } u[m ] = p[0]; u[m+ M] = p[1]; u[m+2*M] = p[2]; } }
rand123wrapper.h
#include <stdio.h> #include <stdint.h> #include <math.h> #include <stdbool.h> #include "frand123.h" // leave blank when using MKL #ifndef USE_MKL #if USE_ARS #include <ars.h> /* * Constants used to first map onto interval [0,1) and then onto (0,1) */ static const double factor_double = 1. / ( (double)UINT64_MAX + 1. ); static const double summand_double = 0.5 / ( (double)UINT64_MAX + 1. ); /* * Function ars2x64_u01 calculates two double precision random numbers * uniformly distributed in (0,1). * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 2 double precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void ars2x64_u01( frand123State_t *state, double *res ) { // extract counter and key from state ars4x32_ctr_t *ctr_ars = (ars4x32_ctr_t*)&( state->state[0] ); ars4x32_key_t *key_ars = (ars4x32_key_t*)&( state->state[2] ); // calc uniformly distributed integers ars4x32_ctr_t resArs = ars4x32_R( 6, *ctr_ars, *key_ars ); // convert to uint64_t uint64_t resInts[2]; resInts[0] = *((uint64_t*)&resArs.v[0]); resInts[1] = *((uint64_t*)&resArs.v[2]); // convert to uniformly distributed doubles in (0,1) res[0] = (double)resInts[0] * factor_double + summand_double; res[1] = (double)resInts[1] * factor_double + summand_double; // advance counter if( ctr_ars->v[0] < UINT32_MAX ) ctr_ars->v[0]++; else { ctr_ars->v[0] = 0; if( ctr_ars->v[1] < UINT32_MAX ) ctr_ars->v[1]++; else { ctr_ars->v[1] = 0; if( ctr_ars->v[2] < UINT32_MAX ) ctr_ars->v[2]++; else { ctr_ars->v[2] = 0; ctr_ars->v[3]++; } } } return; } /* * Constants used to first map onto (-0.5,0.5) and then (0,1) * * ******************* * **** IMPORTANT **** * ******************* * The value of enlarger was determined experimentally to ensure mapping onto (0,-1). * It is included from frand123enlarger.h to allow validation * of the choice in testAccuracyFloats */ #include "frand123enlarger.h" static const float factor_float = 1.f / ( (float)UINT32_MAX + 257.f ); static const float summand_float = 0.5f; /* * Function ars4x32_u01 calculates four single precision random numbers * uniformly distributed in [0,1]. * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 4 single precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void ars4x32_u01( frand123State_t *state, float *res ) { // extract counter and key from state ars4x32_ctr_t *ctr_ars = (ars4x32_ctr_t*)&( state->state[0] ); ars4x32_key_t *key_ars = (ars4x32_key_t*)&( state->state[2] ); // move to vector registers ars1xm128i_ctr_t c128; ars1xm128i_key_t k128; c128.v[0].m = _mm_set_epi32( ctr_ars->v[3], ctr_ars->v[2], ctr_ars->v[1], ctr_ars->v[0] ); k128.v[0].m = _mm_set_epi32( key_ars->v[3], key_ars->v[2], key_ars->v[1], key_ars->v[0] ); // calc uniformly distributed integers in SEE vector registers c128 = ars1xm128i_R( 6, c128, k128 ); // convert signed integers to signed floats __m128 asSignedFloats = _mm_cvtepi32_ps( c128.v[0].m ); // normalize to [-0.5,0.5] and add shift to end in [0,1] __m128 normFactor = _mm_load_ps1( &factor_float ); __m128 summand = _mm_load_ps1( &summand_float ); #ifdef USE_FMA __m128 restrictedToUnitInterval = _mm_fmadd_ps( asSignedFloats, normFactor, summand ); #else __m128 restrictedToUnitCircle = _mm_mul_ps( asSignedFloats, normFactor ); __m128 restrictedToUnitInterval = _mm_add_ps( restrictedToUnitCircle, summand ); #endif // store result in memory _mm_storeu_ps( res, restrictedToUnitInterval ); // advance counter if( ctr_ars->v[0] < UINT32_MAX ) ctr_ars->v[0]++; else { ctr_ars->v[0] = 0; if( ctr_ars->v[1] < UINT32_MAX ) ctr_ars->v[1]++; else { ctr_ars->v[1] = 0; if( ctr_ars->v[2] < UINT32_MAX ) ctr_ars->v[2]++; else { ctr_ars->v[2] = 0; ctr_ars->v[3]++; } } } return; } /* * Function ars2x64_int calculates two 64 bit signed integers * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: adress to storage for 2 64 bit signed integers */ R123_STATIC_INLINE R123_FORCE_INLINE() void ars2x64_int( frand123State_t *state, int64_t *res ) { // extract counter and key from state ars4x32_ctr_t *ctr_ars = (ars4x32_ctr_t*)&( state->state[0] ); ars4x32_key_t *key_ars = (ars4x32_key_t*)&( state->state[2] ); // calc uniformly distributed integers ars4x32_ctr_t resArs = ars4x32_R( 6, *ctr_ars, *key_ars ); // store in res and reinterpret as int64_t res[0] = *((int64_t*)&resArs.v[0]); res[1] = *((int64_t*)&resArs.v[2]); // advance counter if( ctr_ars->v[0] < UINT32_MAX ) ctr_ars->v[0]++; else { ctr_ars->v[0] = 0; if( ctr_ars->v[1] < UINT32_MAX ) ctr_ars->v[1]++; else { ctr_ars->v[1] = 0; if( ctr_ars->v[2] < UINT32_MAX ) ctr_ars->v[2]++; else { ctr_ars->v[2] = 0; ctr_ars->v[3]++; } } } return; } /* * Function ars4x32_int calculates four 32 bit signed integers * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: adress to storage for 4 32 bit signed integers */ R123_STATIC_INLINE R123_FORCE_INLINE() void ars4x32_int( frand123State_t *state, int32_t *res ) { // extract counter and key from state ars4x32_ctr_t *ctr_ars = (ars4x32_ctr_t*)&( state->state[0] ); ars4x32_key_t *key_ars = (ars4x32_key_t*)&( state->state[2] ); // calc uniformly distributed integers ars4x32_ctr_t resArs = ars4x32_R( 6, *ctr_ars, *key_ars ); // store in res and reinterpret as int64_t res[0] = *((int32_t*)&resArs.v[0]); res[1] = *((int32_t*)&resArs.v[1]); res[2] = *((int32_t*)&resArs.v[2]); res[3] = *((int32_t*)&resArs.v[3]); // advance counter if( ctr_ars->v[0] < UINT32_MAX ) ctr_ars->v[0]++; else { ctr_ars->v[0] = 0; if( ctr_ars->v[1] < UINT32_MAX ) ctr_ars->v[1]++; else { ctr_ars->v[1] = 0; if( ctr_ars->v[2] < UINT32_MAX ) ctr_ars->v[2]++; else { ctr_ars->v[2] = 0; ctr_ars->v[3]++; } } } return; } #else // USE_ARS #include <threefry.h> /* * Union conv_union_t simplifies access to bits generated using threefry2x64 */ typedef union { threefry2x64_ctr_t ctr; uint64_t ints[2]; } conv_union_t; /* * Constants used to first map onto interval [0,1) and then onto (0,1) */ static const double factor_double = 1. / ( (double)UINT64_MAX + 1. ); static const double summand_double = 0.5 / ( (double)UINT64_MAX + 1. ); /* * Function threefry2x64_u01 returns 2 double precision reals * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 2 double precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void threefry2x64_u01( frand123State_t *state, double *res ) { // extract counter and key from state threefry2x64_ctr_t *ctr_threefry = (threefry2x64_ctr_t*)&( state->state[0] ); threefry2x64_key_t *key_threefry = (threefry2x64_key_t*)&( state->state[2] ); // calc uniformly distributed integers conv_union_t resInt; resInt.ctr = threefry2x64_R( 13, *ctr_threefry, *key_threefry ); // convert to uniformly distributed doubles in (0,1) res[0] = (double)resInt.ints[0] * factor_double + summand_double; res[1] = (double)resInt.ints[1] * factor_double + summand_double; // advance counter if( ctr_threefry->v[0] < UINT64_MAX ) ctr_threefry->v[0]++; else { ctr_threefry->v[0] = 0; ctr_threefry->v[1]++; } return; } /* * Constants used to first map onto interval [0,1) and then onto (0,1) */ static const float factor_float = 1. / ( (float)UINT32_MAX + 400.f ); static const float summand_float = 0.5 / ( (float)UINT32_MAX + 400.f ); /* * Function threefry4x32_u01 returns 4 single precision reals * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 4 single precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void threefry4x32_u01( frand123State_t *state, float *res ) { // extract counter and key from state threefry4x32_ctr_t *ctr_threefry = (threefry4x32_ctr_t*)&( state->state[0] ); threefry4x32_key_t *key_threefry = (threefry4x32_key_t*)&( state->state[2] ); // calc uniformly distributed integers threefry4x32_ctr_t resInt = threefry4x32_R( 12, *ctr_threefry, *key_threefry ); // convert to uniformly distributed floats in (0,1) res[0] = (float)resInt.v[0] * factor_float + summand_float; res[1] = (float)resInt.v[1] * factor_float + summand_float; res[2] = (float)resInt.v[2] * factor_float + summand_float; res[3] = (float)resInt.v[3] * factor_float + summand_float; // advance counter if( ctr_threefry->v[0] < UINT32_MAX ) ctr_threefry->v[0]++; else { ctr_threefry->v[0] = 0; if( ctr_threefry->v[1] < UINT32_MAX ) ctr_threefry->v[1]++; else { ctr_threefry->v[1] = 0; if( ctr_threefry->v[2] < UINT32_MAX ) ctr_threefry->v[2]++; else { ctr_threefry->v[2] = 0; ctr_threefry->v[3]++; } } } return; } /* * Function threefry2x64_int returns 2 64 bit signed integers * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 2 64 bit signed integers */ R123_STATIC_INLINE R123_FORCE_INLINE() void threefry2x64_int( frand123State_t *state, int64_t *res ) { // extract counter and key from state threefry2x64_ctr_t *ctr_threefry = (threefry2x64_ctr_t*)&( state->state[0] ); threefry2x64_key_t *key_threefry = (threefry2x64_key_t*)&( state->state[2] ); // calc uniformly distributed integers threefry2x64_ctr_t resThreefry = threefry2x64_R( 13, *ctr_threefry, *key_threefry ); // reinterprete as signed 64 bit integer res[0] = *((int64_t*)&resThreefry.v[0]); res[1] = *((int64_t*)&resThreefry.v[1]); // advance counter if( ctr_threefry->v[0] < UINT64_MAX ) ctr_threefry->v[0]++; else { ctr_threefry->v[0] = 0; ctr_threefry->v[1]++; } return; } /* * Function threefry4x32 returns 4 32 bit signed integers * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * res: address to storage for 4 32 bit signed integers */ R123_STATIC_INLINE R123_FORCE_INLINE() void threefry4x32_int( frand123State_t *state, int32_t *res ) { // extract counter and key from state threefry4x32_ctr_t *ctr_threefry = (threefry4x32_ctr_t*)&( state->state[0] ); threefry4x32_key_t *key_threefry = (threefry4x32_key_t*)&( state->state[2] ); // calc uniformly distributed integers threefry4x32_ctr_t resInt = threefry4x32_R( 12, *ctr_threefry, *key_threefry ); // reinterprete as 32 bit signed integer res[0] = *((int32_t*)&resInt.v[0]); res[1] = *((int32_t*)&resInt.v[1]); res[2] = *((int32_t*)&resInt.v[2]); res[3] = *((int32_t*)&resInt.v[3]); // advance counter if( ctr_threefry->v[0] < UINT32_MAX ) ctr_threefry->v[0]++; else { ctr_threefry->v[0] = 0; if( ctr_threefry->v[1] < UINT32_MAX ) ctr_threefry->v[1]++; else { ctr_threefry->v[1] = 0; if( ctr_threefry->v[2] < UINT32_MAX ) ctr_threefry->v[2]++; else { ctr_threefry->v[2] = 0; ctr_threefry->v[3]++; } } } } #endif #ifdef USE_POLAR /* * Function polar2x64 calculates two double precision random numbers * normally distributed with expectation mu and variance sigma using the * polar rejection method by Box and Muller * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * mu: expectation * sigma: variance * res: address to storage for 2 double precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void polar2x64( frand123State_t *state, const double mu, const double sigma, double *res ) { double u[ 2 ]; double x[ 2 ]; double r2; double f; // generate coordinates until within unit circle // at least first try successful: probability ~79% // at least second try successful: ~95% // at least third try successful: ~99% do { #if USE_ARS ars2x64_u01( &( state->state ), u ); #else threefry2x64_u01( &( state->state ), u ); #endif x[ 0 ] = 2. * u[ 0 ] - 1.; x[ 1 ] = 2. * u[ 1 ] - 1.; r2 = x[ 0 ] * x[ 0 ] + x[ 1 ] * x[ 1 ]; } while( ( r2 >= 1. ) || ( r2 == 0. ) ); // compute random numbers f = sqrt( -2. * log( r2 ) / r2 ); res[ 0 ] = mu + sigma * f * x[ 0 ]; res[ 1 ] = mu + sigma * f * x[ 1 ]; return; } #else /* * Function wichura2x64kernel represents the kernel of the AS 241 algorithm extracted for testing */ R123_STATIC_INLINE R123_FORCE_INLINE() void wichura2x64kernel( const double *p, const double mu, const double sigma, double *res ) { // constants for the polynomials const double A[ 8 ] = { 3.3871328727963666080e0, 1.3314166789178437745e2, 1.9715909503065514427e3, 1.3731693765509461125e4, 4.5921953931549871457e4, 6.7265770927008700853e4, 3.3430575583588128105e4, 2.5090809287301226727e3 }; const double B[ 8 ] = { 1.0E0, 4.2313330701600911252e1, 6.8718700749205790830e2, 5.3941960214247511077e3, 2.1213794301586595867e4, 3.9307895800092710610e4, 2.8729085735721942674e4, 5.2264952788528545610e3 }; const double C[ 8 ] = { 1.42343711074968357734e0, 4.63033784615654529590e0, 5.76949722146069140550e0, 3.64784832476320460504e0, 1.27045825245236838258e0, 2.41780725177450611770e-1, 2.27238449892691845833e-2, 7.74545014278341407640e-4 }; const double D[ 8 ] = { 1.0E0, 2.05319162663775882187e0, 1.67638483018380384940e0, 6.89767334985100004550e-1, 1.48103976427480074590e-1, 1.51986665636164571966e-2, 5.47593808499534494600e-4, 1.05075007164441684324e-9 }; const double E[ 8 ] = { 6.65790464350110377720e0, 5.46378491116411436990e0, 1.78482653991729133580e0, 2.96560571828504891230e-1, 2.65321895265761230930e-2, 1.24266094738807843860e-3, 2.71155556874348757815e-5, 2.01033439929228813265e-7 }; const double F[ 8 ] = { 1.0E0, 5.99832206555887937690e-1, 1.36929880922735805310e-1, 1.48753612908506148525e-2, 7.86869131145613259100e-4, 1.84631831751005468180e-5, 1.42151175831644588870e-7, 2.04426310338993978564e-15 }; // algorithmic constants const double split1 = 0.425; const double split2 = 5.; const double const1 = 0.180625; const double const2 = 1.6; // variables double q[ 2 ], r, prodA[ 2 ], prodB[ 2]; int i, j; bool cond[ 2 ]; // compute both q at once q[ 0 ] = p[ 0 ] - 0.5; q[ 1 ] = p[ 1 ] - 0.5; // compute abs eval cond[ 0 ] = ( fabs( q[ 0 ] ) <= split1 ); cond[ 1 ] = ( fabs( q[ 1 ] ) <= split1 ); // run vectorized version of the main route // in the following cases // both values of |q| <= split1: probability ~72% // one |q| <= split1, one |q| > split1: probability ~26% if( cond[ 0 ] || cond[ 1 ] ) { #pragma omp simd private( r ) for( i = 0; i <= 1; i++ ) { r = const1 - q[ i ] * q[ i ]; prodA[ i ] = A[7]; prodB[ i ] = B[7]; for( j = 6; j >= 0; j-- ) { prodA[ i ] = prodA[ i ] * r + A[ j ]; prodB[ i ] = prodB[ i ] * r + B[ j ]; } // transform to required mean and variance res[ i ] = mu + sigma * q[ i ] * prodA[ i ] / prodB[ i ]; } } // return in 72.25% of calls if( cond[ 0 ] && cond[ 1 ] ) { return; } // handle first non-standard case // probability for need to handle single case: ~13% // probability for need to handle both cases: ~2% for( i = 0; i <= 1; i++ ) { if( ! cond[ i ] ) { if( q[ i ] < 0 ) { r = p[ i ]; } else { r = 1. - p[ i ]; } r = sqrt( -log( r ) ); // not too far within the tail if( r <= split2 ) { r = r - const2; double prodC = C[ 7 ]; double prodD = D[ 7 ]; for( j = 6; j >= 0; j-- ) { prodC = prodC * r + C[ j ]; prodD = prodD * r + D[ j ]; } res[ i ] = prodC / prodD; } // far within the tail else { r = r - split2; double prodE = E[ 7 ]; double prodF = F[ 7 ]; for( j = 6; j >= 0; j-- ) { prodE = prodE * r + E[ j ]; prodF = prodF * r + F[ j ]; } res[ i ] = prodE / prodF; } if( q[ i ] < 0. ) { res[ i ] = -res[ i ]; } // transform to required mean and variance res[ i ] = mu + sigma * res[ i ]; } } } /* * Function wichura2x64 calculates two double precision random numbers * normally distributed with expectation mu and variance sigma using the * inverse transform sampling introduced by Wichura 1988 in algorithm AS241 (PPND16) * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * mu: expectation * sigma: variance * res: address to storage for 2 double precision reals */ R123_STATIC_INLINE R123_FORCE_INLINE() void wichura2x64( frand123State_t *state, const double mu, const double sigma, double *res ) { // get uniform random numbers double p[ 2 ]; #ifdef USE_ARS ars2x64_u01( state, p ); #else threefry2x64_u01( state, p ); #endif // rest is computed within the kernel wichura2x64kernel( p, mu, sigma, res ); return; } #endif /* * Function polar4x32 calculates four single precision random numbers * normally distributed with expectation mu and variance sigma using the * polar rejection method by Box and Muller * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * mu: expectation * sigma: variance * res: address to storage for 4 single precision reals */ void polar4x32( frand123State_t *state, const float mu, const float sigma, float *res ) { float u[ 4 ]; float x[ 4 ]; float r2[ 2 ]; float f[ 2 ]; // generate coordinates until within unit circle // at least first try successful: probability ~62% // at least second try successful: probability ~85% // at least third try successful: probability ~94% // this implementation should require ~0.8 calls of ars4x32_u01 or // threefry4x32_u01 to generate a single random number but fewer // conditionals than one that requires only ~0.7 calls per random number do { #if USE_ARS ars4x32_u01( state, u ); #else threefry4x32_u01( state, u ); #endif x[ 0 ] = 2.f * u[ 0 ] - 1.f; x[ 1 ] = 2.f * u[ 1 ] - 1.f; x[ 2 ] = 2.f * u[ 2 ] - 1.f; x[ 3 ] = 2.f * u[ 3 ] - 1.f; r2[ 0 ] = x[ 0 ] * x[ 0 ] + x[ 1 ] * x[ 1 ]; r2[ 1 ] = x[ 2 ] * x[ 2 ] + x[ 3 ] * x[ 3 ]; } while( ( r2[ 0 ] >= 1.f ) || ( r2[ 0 ] == 0.f ) || ( r2[ 1 ] >= 1.f ) || ( r2[ 1 ] == 0.f ) ); // compute random numbers f[ 0 ] = sqrt( -2.f * log( r2[ 0 ] ) / r2[ 0 ] ); f[ 1 ] = sqrt( -2.f * log( r2[ 1 ] ) / r2[ 1 ] ); res[ 0 ] = mu + sigma * f[ 0 ] * x[ 0 ]; res[ 1 ] = mu + sigma * f[ 0 ] * x[ 1 ]; res[ 2 ] = mu + sigma * f[ 1 ] * x[ 2 ]; res[ 3 ] = mu + sigma * f[ 1 ] * x[ 3 ]; return; } /* * Function polar4x32_two calculates two single precision random numbers * normally distributed with expectation mu and variance sigma using the * polar rejection method by Box and Muller * * Note: restriction to 2 random numbers allows for fewer calls to RNG due * the specifics of the rejection method * * Arguments: state: four elements holding * counter: first 128 bit * key: second 128 bit * mu: expectation * sigma: variance * res: address to storage for 2 single precision reals */ void polar4x32_two( frand123State_t *state, const float mu, const float sigma, float *res ) { float u[ 4 ]; float x[ 4 ]; float r2[ 2 ]; float f; bool in[ 2 ]; // generate coordinates until within unit circle // at least first try successful: probability ~95% // at least second try successful: probability ~100% // this implementation requires ~ 0.52 calls of the // RNG per random number do { #if USE_ARS ars4x32_u01( state, u ); #else threefry4x32_u01( state, u ); #endif // compute distance from center x[ 0 ] = 2.f * u[ 0 ] - 1.f; x[ 1 ] = 2.f * u[ 1 ] - 1.f; x[ 2 ] = 2.f * u[ 2 ] - 1.f; x[ 3 ] = 2.f * u[ 3 ] - 1.f; r2[ 0 ] = x[ 0 ] * x[ 0 ] + x[ 1 ] * x[ 1 ]; r2[ 1 ] = x[ 2 ] * x[ 2 ] + x[ 3 ] * x[ 3 ]; // check which lies within the unit circle in[ 0 ] = ( r2[ 0 ] > 0.f ) && ( r2[ 0 ] < 1.f ); in[ 1 ] = ( r2[ 1 ] > 0.f ) && ( r2[ 1 ] < 1.f ); } while( ! ( in[ 0 ] || in[ 1 ] ) ); // compute two random numbers if( in[ 0 ] ) { f = sqrt( -2.f * log( r2[ 0 ] ) / r2[ 0 ] ); res[ 0 ] = mu + sigma * f * x[ 0 ]; res[ 1 ] = mu + sigma * f * x[ 1 ]; } else { f = sqrt( -2.f * log( r2[ 1 ] ) / r2[ 1 ] ); res[ 0 ] = mu + sigma * f * x[ 2 ]; res[ 1 ] = mu + sigma * f * x[ 3 ]; } return; } #endif // USE_MKL
two_step_v_p_strategy.h
// // Project Name: KratosPFEMFluidDynamicsApplication $ // Last modified by: $Author: AFranci $ // Date: $Date: January 2016 $ // Revision: $Revision: 0.0 $ // // #ifndef KRATOS_TWO_STEP_V_P_STRATEGY_H #define KRATOS_TWO_STEP_V_P_STRATEGY_H #include "includes/define.h" #include "includes/model_part.h" #include "includes/deprecated_variables.h" #include "includes/cfd_variables.h" #include "utilities/openmp_utils.h" #include "processes/process.h" #include "solving_strategies/schemes/scheme.h" #include "solving_strategies/strategies/solving_strategy.h" #include "custom_utilities/mesher_utilities.hpp" #include "custom_utilities/boundary_normals_calculation_utilities.hpp" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h" /* #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme_slip.h" */ #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h" #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver_componentwise.h" #include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h" #include "custom_utilities/solver_settings.h" #include "custom_strategies/strategies/gauss_seidel_linear_strategy.h" #include "pfem_fluid_dynamics_application_variables.h" #include <stdio.h> #include <math.h> namespace Kratos { ///@addtogroup PFEMFluidDynamicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ template <class TSparseSpace, class TDenseSpace, class TLinearSolver> class TwoStepVPStrategy : public SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(TwoStepVPStrategy); /// Counted pointer of TwoStepVPStrategy //typedef boost::shared_ptr< TwoStepVPStrategy<TSparseSpace, TDenseSpace, TLinearSolver> > Pointer; typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TDataType TDataType; //typedef typename BaseType::DofSetType DofSetType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>::Pointer StrategyPointerType; typedef TwoStepVPSolverSettings<TSparseSpace, TDenseSpace, TLinearSolver> SolverSettingsType; ///@} ///@name Life Cycle ///@{ TwoStepVPStrategy(ModelPart &rModelPart, SolverSettingsType &rSolverConfig) : BaseType(rModelPart) { InitializeStrategy(rSolverConfig); } TwoStepVPStrategy(ModelPart &rModelPart, /*SolverConfiguration<TSparseSpace, TDenseSpace, TLinearSolver>& rSolverConfig,*/ typename TLinearSolver::Pointer pVelocityLinearSolver, typename TLinearSolver::Pointer pPressureLinearSolver, bool ReformDofSet = true, double VelTol = 0.0001, double PresTol = 0.0001, int MaxPressureIterations = 1, // Only for predictor-corrector unsigned int TimeOrder = 2, unsigned int DomainSize = 2) : BaseType(rModelPart), // Move Mesh flag, pass as input? mVelocityTolerance(VelTol), mPressureTolerance(PresTol), mMaxPressureIter(MaxPressureIterations), mDomainSize(DomainSize), mTimeOrder(TimeOrder), mReformDofSet(ReformDofSet) { KRATOS_TRY; BaseType::SetEchoLevel(1); // Check that input parameters are reasonable and sufficient. this->Check(); bool CalculateNormDxFlag = true; bool ReformDofAtEachIteration = false; // DofSet modifiaction is managed by the fractional step strategy, auxiliary strategies should not modify the DofSet directly. // Additional Typedefs typedef typename BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>::Pointer BuilderSolverTypePointer; typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; //initializing fractional velocity solution step typedef Scheme<TSparseSpace, TDenseSpace> SchemeType; typename SchemeType::Pointer pScheme; typename SchemeType::Pointer Temp = typename SchemeType::Pointer(new ResidualBasedIncrementalUpdateStaticScheme<TSparseSpace, TDenseSpace>()); pScheme.swap(Temp); //CONSTRUCTION OF VELOCITY BuilderSolverTypePointer vel_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pVelocityLinearSolver)); /* BuilderSolverTypePointer vel_build = BuilderSolverTypePointer(new ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver > (pVelocityLinearSolver)); */ this->mpMomentumStrategy = typename BaseType::Pointer(new GaussSeidelLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pVelocityLinearSolver, vel_build, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mpMomentumStrategy->SetEchoLevel(BaseType::GetEchoLevel()); vel_build->SetCalculateReactionsFlag(false); /* BuilderSolverTypePointer pressure_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolverComponentwise<TSparseSpace, TDenseSpace, TLinearSolver, Variable<double> >(pPressureLinearSolver, PRESSURE)); */ BuilderSolverTypePointer pressure_build = BuilderSolverTypePointer(new ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pPressureLinearSolver)); this->mpPressureStrategy = typename BaseType::Pointer(new GaussSeidelLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pPressureLinearSolver, pressure_build, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mpPressureStrategy->SetEchoLevel(BaseType::GetEchoLevel()); pressure_build->SetCalculateReactionsFlag(false); KRATOS_CATCH(""); } /// Destructor. virtual ~TwoStepVPStrategy() {} int Check() override { KRATOS_TRY; // Check elements and conditions in the model part int ierr = BaseType::Check(); if (ierr != 0) return ierr; if (DELTA_TIME.Key() == 0) KRATOS_THROW_ERROR(std::runtime_error, "DELTA_TIME Key is 0. Check that the application was correctly registered.", ""); if (BDF_COEFFICIENTS.Key() == 0) KRATOS_THROW_ERROR(std::runtime_error, "BDF_COEFFICIENTS Key is 0. Check that the application was correctly registered.", ""); ModelPart &rModelPart = BaseType::GetModelPart(); if (mTimeOrder == 2 && rModelPart.GetBufferSize() < 3) KRATOS_THROW_ERROR(std::invalid_argument, "Buffer size too small for fractional step strategy (BDF2), needed 3, got ", rModelPart.GetBufferSize()); if (mTimeOrder == 1 && rModelPart.GetBufferSize() < 2) KRATOS_THROW_ERROR(std::invalid_argument, "Buffer size too small for fractional step strategy (Backward Euler), needed 2, got ", rModelPart.GetBufferSize()); // const ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); // for (ModelPart::ElementIterator itEl = rModelPart.ElementsBegin(); itEl != rModelPart.ElementsEnd(); ++itEl) // { // ierr = itEl->Check(rCurrentProcessInfo); // if (ierr != 0) // break; // } const auto &r_current_process_info = rModelPart.GetProcessInfo(); for (const auto &r_element : rModelPart.Elements()) { ierr = r_element.Check(r_current_process_info); if (ierr != 0) { break; } } /* for ( ModelPart::ConditionIterator itCond = rModelPart.ConditionsBegin(); itCond != rModelPart.ConditionsEnd(); ++itCond) */ /* { */ /* ierr = itCond->Check(rCurrentProcessInfo); */ /* if (ierr != 0) break; */ /* } */ return ierr; KRATOS_CATCH(""); } bool SolveSolutionStep() override { ModelPart &rModelPart = BaseType::GetModelPart(); this->SetTimeCoefficients(rModelPart.GetProcessInfo()); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); double currentTime = rCurrentProcessInfo[TIME]; double timeInterval = rCurrentProcessInfo[DELTA_TIME]; bool timeIntervalChanged = rCurrentProcessInfo[TIME_INTERVAL_CHANGED]; unsigned int stepsWithChangedDt = rCurrentProcessInfo[STEPS_WITH_CHANGED_DT]; bool converged = false; unsigned int maxNonLinearIterations = mMaxPressureIter; KRATOS_INFO("\n Solution with two_step_vp_strategy at t=") << currentTime << "s" << std::endl; if ((timeIntervalChanged == true && currentTime > 10 * timeInterval) || stepsWithChangedDt > 0) { maxNonLinearIterations *= 2; } if (currentTime < 10 * timeInterval) { if (BaseType::GetEchoLevel() > 1) std::cout << "within the first 10 time steps, I consider the given iteration number x3" << std::endl; maxNonLinearIterations *= 3; } if (currentTime < 20 * timeInterval && currentTime >= 10 * timeInterval) { if (BaseType::GetEchoLevel() > 1) std::cout << "within the second 10 time steps, I consider the given iteration number x2" << std::endl; maxNonLinearIterations *= 2; } bool momentumConverged = true; bool continuityConverged = false; bool fixedTimeStep = false; double pressureNorm = 0; double velocityNorm = 0; this->SetBlockedFlag(); for (unsigned int it = 0; it < maxNonLinearIterations; ++it) { momentumConverged = this->SolveMomentumIteration(it, maxNonLinearIterations, fixedTimeStep, velocityNorm); this->UpdateTopology(rModelPart, BaseType::GetEchoLevel()); if (fixedTimeStep == false) { continuityConverged = this->SolveContinuityIteration(it, maxNonLinearIterations, pressureNorm); } if (it == maxNonLinearIterations - 1 || ((continuityConverged && momentumConverged) && it > 2)) { this->UpdateStressStrain(); } if ((continuityConverged && momentumConverged) && it > 2) { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, false); rCurrentProcessInfo.SetValue(BAD_PRESSURE_CONVERGENCE, false); converged = true; KRATOS_INFO("TwoStepVPStrategy") << "V-P strategy converged in " << it + 1 << " iterations." << std::endl; break; } if (fixedTimeStep == true) { break; } } if (!continuityConverged && !momentumConverged && BaseType::GetEchoLevel() > 0 && rModelPart.GetCommunicator().MyPID() == 0) std::cout << "Convergence tolerance not reached." << std::endl; if (mReformDofSet) this->Clear(); return converged; } void FinalizeSolutionStep() override { } void InitializeSolutionStep() override { } void UpdateTopology(ModelPart &rModelPart, unsigned int echoLevel) { KRATOS_TRY; this->CalculateDisplacementsAndPorosity(); BaseType::MoveMesh(); /* BoundaryNormalsCalculationUtilities BoundaryComputation; */ /* BoundaryComputation.CalculateWeightedBoundaryNormals(rModelPart, echoLevel); */ KRATOS_CATCH(""); } void SetBlockedFlag() { KRATOS_TRY; ModelPart &rModelPart = BaseType::GetModelPart(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); #pragma omp parallel { ModelPart::ElementIterator ElemBegin; ModelPart::ElementIterator ElemEnd; OpenMPUtils::PartitionedIterators(rModelPart.Elements(), ElemBegin, ElemEnd); for (ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { unsigned int numNodes = itElem->GetGeometry().size(); std::vector<array_1d<double, 3>> nodesCoordinates; nodesCoordinates.resize(numNodes); (itElem)->Set(BLOCKED, false); (itElem)->Set(ISOLATED, false); unsigned int freeSurfaceNodes = 0; unsigned int freeSurfaceRigidNodes = 0; unsigned int rigidNodes = 0; unsigned int isolatedNodes = 0; for (unsigned int i = 0; i < numNodes; i++) { if (itElem->GetGeometry()[i].Is(FREE_SURFACE)) { freeSurfaceNodes++; if (itElem->GetGeometry()[i].Is(RIGID)) { freeSurfaceRigidNodes++; } } else if (itElem->GetGeometry()[i].Is(RIGID)) { rigidNodes++; } nodesCoordinates[i] = itElem->GetGeometry()[i].Coordinates(); ElementWeakPtrVectorType &neighb_elems = itElem->GetGeometry()[i].GetValue(NEIGHBOUR_ELEMENTS); if (neighb_elems.size() == 1) { isolatedNodes++; } } // if (dimension == 3 && (freeSurfaceNodes == numNodes || (freeSurfaceNodes + rigidNodes) == numNodes)) if (dimension == 3) { double a1 = 0; //slope x for plane on the first triangular face of the tetrahedra (nodes A,B,C) double b1 = 0; //slope y for plane on the first triangular face of the tetrahedra (nodes A,B,C) double c1 = 0; //slope z for plane on the first triangular face of the tetrahedra (nodes A,B,C) a1 = (nodesCoordinates[1][1] - nodesCoordinates[0][1]) * (nodesCoordinates[2][2] - nodesCoordinates[0][2]) - (nodesCoordinates[2][1] - nodesCoordinates[0][1]) * (nodesCoordinates[1][2] - nodesCoordinates[0][2]); b1 = (nodesCoordinates[1][2] - nodesCoordinates[0][2]) * (nodesCoordinates[2][0] - nodesCoordinates[0][0]) - (nodesCoordinates[2][2] - nodesCoordinates[0][2]) * (nodesCoordinates[1][0] - nodesCoordinates[0][0]); c1 = (nodesCoordinates[1][0] - nodesCoordinates[0][0]) * (nodesCoordinates[2][1] - nodesCoordinates[0][1]) - (nodesCoordinates[2][0] - nodesCoordinates[0][0]) * (nodesCoordinates[1][1] - nodesCoordinates[0][1]); double a2 = 0; //slope x for plane on the second triangular face of the tetrahedra (nodes A,B,D) double b2 = 0; //slope y for plane on the second triangular face of the tetrahedra (nodes A,B,D) double c2 = 0; //slope z for plane on the second triangular face of the tetrahedra (nodes A,B,D) a2 = (nodesCoordinates[1][1] - nodesCoordinates[0][1]) * (nodesCoordinates[3][2] - nodesCoordinates[0][2]) - (nodesCoordinates[3][1] - nodesCoordinates[0][1]) * (nodesCoordinates[1][2] - nodesCoordinates[0][2]); b2 = (nodesCoordinates[1][2] - nodesCoordinates[0][2]) * (nodesCoordinates[3][0] - nodesCoordinates[0][0]) - (nodesCoordinates[3][2] - nodesCoordinates[0][2]) * (nodesCoordinates[1][0] - nodesCoordinates[0][0]); c2 = (nodesCoordinates[1][0] - nodesCoordinates[0][0]) * (nodesCoordinates[3][1] - nodesCoordinates[0][1]) - (nodesCoordinates[3][0] - nodesCoordinates[0][0]) * (nodesCoordinates[1][1] - nodesCoordinates[0][1]); double a3 = 0; //slope x for plane on the third triangular face of the tetrahedra (nodes B,C,D) double b3 = 0; //slope y for plane on the third triangular face of the tetrahedra (nodes B,C,D) double c3 = 0; //slope z for plane on the third triangular face of the tetrahedra (nodes B,C,D) a3 = (nodesCoordinates[1][1] - nodesCoordinates[2][1]) * (nodesCoordinates[3][2] - nodesCoordinates[2][2]) - (nodesCoordinates[3][1] - nodesCoordinates[2][1]) * (nodesCoordinates[1][2] - nodesCoordinates[2][2]); b3 = (nodesCoordinates[1][2] - nodesCoordinates[2][2]) * (nodesCoordinates[3][0] - nodesCoordinates[2][0]) - (nodesCoordinates[3][2] - nodesCoordinates[2][2]) * (nodesCoordinates[1][0] - nodesCoordinates[2][0]); c3 = (nodesCoordinates[1][0] - nodesCoordinates[2][0]) * (nodesCoordinates[3][1] - nodesCoordinates[2][1]) - (nodesCoordinates[3][0] - nodesCoordinates[2][0]) * (nodesCoordinates[1][1] - nodesCoordinates[2][1]); double a4 = 0; //slope x for plane on the fourth triangular face of the tetrahedra (nodes A,C,D) double b4 = 0; //slope y for plane on the fourth triangular face of the tetrahedra (nodes A,C,D) double c4 = 0; //slope z for plane on the fourth triangular face of the tetrahedra (nodes A,C,D) a4 = (nodesCoordinates[0][1] - nodesCoordinates[2][1]) * (nodesCoordinates[3][2] - nodesCoordinates[2][2]) - (nodesCoordinates[3][1] - nodesCoordinates[2][1]) * (nodesCoordinates[0][2] - nodesCoordinates[2][2]); b4 = (nodesCoordinates[0][2] - nodesCoordinates[2][2]) * (nodesCoordinates[3][0] - nodesCoordinates[2][0]) - (nodesCoordinates[3][2] - nodesCoordinates[2][2]) * (nodesCoordinates[0][0] - nodesCoordinates[2][0]); c4 = (nodesCoordinates[0][0] - nodesCoordinates[2][0]) * (nodesCoordinates[3][1] - nodesCoordinates[2][1]) - (nodesCoordinates[3][0] - nodesCoordinates[2][0]) * (nodesCoordinates[0][1] - nodesCoordinates[2][1]); double cosAngle12 = (a1 * a2 + b1 * b2 + c1 * c2) / (sqrt(pow(a1, 2) + pow(b1, 2) + pow(c1, 2)) * sqrt(pow(a2, 2) + pow(b2, 2) + pow(c2, 2))); double cosAngle13 = (a1 * a3 + b1 * b3 + c1 * c3) / (sqrt(pow(a1, 2) + pow(b1, 2) + pow(c1, 2)) * sqrt(pow(a3, 2) + pow(b3, 2) + pow(c3, 2))); double cosAngle14 = (a1 * a4 + b1 * b4 + c1 * c4) / (sqrt(pow(a1, 2) + pow(b1, 2) + pow(c1, 2)) * sqrt(pow(a4, 2) + pow(b4, 2) + pow(c4, 2))); double cosAngle23 = (a3 * a2 + b3 * b2 + c3 * c2) / (sqrt(pow(a3, 2) + pow(b3, 2) + pow(c3, 2)) * sqrt(pow(a2, 2) + pow(b2, 2) + pow(c2, 2))); double cosAngle24 = (a4 * a2 + b4 * b2 + c4 * c2) / (sqrt(pow(a4, 2) + pow(b4, 2) + pow(c4, 2)) * sqrt(pow(a2, 2) + pow(b2, 2) + pow(c2, 2))); double cosAngle34 = (a4 * a3 + b4 * b3 + c4 * c3) / (sqrt(pow(a4, 2) + pow(b4, 2) + pow(c4, 2)) * sqrt(pow(a3, 2) + pow(b3, 2) + pow(c3, 2))); if ((fabs(cosAngle12) > 0.99 || fabs(cosAngle13) > 0.99 || fabs(cosAngle14) > 0.99 || fabs(cosAngle23) > 0.99 || fabs(cosAngle24) > 0.99 || fabs(cosAngle34) > 0.99) && (freeSurfaceNodes == numNodes) && isolatedNodes > 1) { (itElem)->Set(BLOCKED, true); // std::cout << "in the strategy BLOCKED ELEMENT: " << (itElem)->Id() << std::endl; } else if ((fabs(cosAngle12) > 0.995 || fabs(cosAngle13) > 0.995 || fabs(cosAngle14) > 0.995 || fabs(cosAngle23) > 0.995 || fabs(cosAngle24) > 0.995 || fabs(cosAngle34) > 0.995) && (freeSurfaceNodes == numNodes) && isolatedNodes == 1) { (itElem)->Set(BLOCKED, true); // std::cout << "in the strategy BLOCKED ELEMENT: " << (itElem)->Id() << std::endl; } else if ((fabs(cosAngle12) > 0.999 || fabs(cosAngle13) > 0.999 || fabs(cosAngle14) > 0.999 || fabs(cosAngle23) > 0.999 || fabs(cosAngle24) > 0.999 || fabs(cosAngle34) > 0.999) && (freeSurfaceNodes == numNodes)) { (itElem)->Set(BLOCKED, true); // std::cout << "in the strategy BLOCKED ELEMENT: " << (itElem)->Id() << std::endl; } // else if (fabs(cosAngle12) > 0.999 || fabs(cosAngle13) > 0.999 || fabs(cosAngle14) > 0.999 || fabs(cosAngle23) > 0.999 || fabs(cosAngle24) > 0.999 || fabs(cosAngle34) > 0.999) // { // (itElem)->Set(BLOCKED, true); // // std::cout << "in the strategy BLOCKED ELEMENT: " << (itElem)->Id() << std::endl; // } } if (freeSurfaceNodes == numNodes && rigidNodes == 0 && isolatedNodes >= (numNodes - 1)) { (itElem)->Set(ISOLATED, true); (itElem)->Set(BLOCKED, false); } } } KRATOS_CATCH(""); } void UnactiveSliverElements() { KRATOS_TRY; ModelPart &rModelPart = BaseType::GetModelPart(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); MesherUtilities MesherUtils; double ModelPartVolume = MesherUtils.ComputeModelPartVolume(rModelPart); double CriticalVolume = 0.001 * ModelPartVolume / double(rModelPart.Elements().size()); double ElementalVolume = 0; #pragma omp parallel { ModelPart::ElementIterator ElemBegin; ModelPart::ElementIterator ElemEnd; OpenMPUtils::PartitionedIterators(rModelPart.Elements(), ElemBegin, ElemEnd); for (ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { unsigned int numNodes = itElem->GetGeometry().size(); if (numNodes == (dimension + 1)) { if (dimension == 2) { ElementalVolume = (itElem)->GetGeometry().Area(); } else if (dimension == 3) { ElementalVolume = (itElem)->GetGeometry().Volume(); } if (ElementalVolume < CriticalVolume) { // std::cout << "sliver element: it has Volume: " << ElementalVolume << " vs CriticalVolume(meanVol/1000): " << CriticalVolume<< std::endl; (itElem)->Set(ACTIVE, false); } else { (itElem)->Set(ACTIVE, true); } } } } KRATOS_CATCH(""); } void CalculatePressureVelocity() { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = rCurrentProcessInfo[DELTA_TIME]; unsigned int timeStep = rCurrentProcessInfo[STEP]; for (ModelPart::NodeIterator i = rModelPart.NodesBegin(); i != rModelPart.NodesEnd(); ++i) { if (timeStep == 1) { (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) = 0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 1) = 0; } else { double &CurrentPressure = (i)->FastGetSolutionStepValue(PRESSURE, 0); double &PreviousPressure = (i)->FastGetSolutionStepValue(PRESSURE, 1); double &CurrentPressureVelocity = (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0); CurrentPressureVelocity = (CurrentPressure - PreviousPressure) / timeInterval; } } } void CalculatePressureAcceleration() { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = rCurrentProcessInfo[DELTA_TIME]; unsigned int timeStep = rCurrentProcessInfo[STEP]; for (ModelPart::NodeIterator i = rModelPart.NodesBegin(); i != rModelPart.NodesEnd(); ++i) { if (timeStep == 1) { (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0) = 0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 1) = 0; } else { double &CurrentPressureVelocity = (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0); double &PreviousPressureVelocity = (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 1); double &CurrentPressureAcceleration = (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0); CurrentPressureAcceleration = (CurrentPressureVelocity - PreviousPressureVelocity) / timeInterval; } } } virtual void CalculateTemporalVariables() { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); Vector &BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; for (ModelPart::NodeIterator i = rModelPart.NodesBegin(); i != rModelPart.NodesEnd(); ++i) { array_1d<double, 3> &CurrentVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 0); array_1d<double, 3> &PreviousVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 1); array_1d<double, 3> &CurrentAcceleration = (i)->FastGetSolutionStepValue(ACCELERATION, 0); array_1d<double, 3> &PreviousAcceleration = (i)->FastGetSolutionStepValue(ACCELERATION, 1); /* if((i)->IsNot(ISOLATED) || (i)->Is(SOLID)){ */ if ((i)->IsNot(ISOLATED) && ((i)->IsNot(RIGID) || (i)->Is(SOLID))) { UpdateAccelerations(CurrentAcceleration, CurrentVelocity, PreviousAcceleration, PreviousVelocity, BDFcoeffs); } else if ((i)->Is(RIGID)) { array_1d<double, 3> Zeros(3, 0.0); (i)->FastGetSolutionStepValue(ACCELERATION, 0) = Zeros; (i)->FastGetSolutionStepValue(ACCELERATION, 1) = Zeros; } else { (i)->FastGetSolutionStepValue(PRESSURE, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE, 1) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 1) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 1) = 0.0; if ((i)->SolutionStepsDataHas(VOLUME_ACCELERATION)) { array_1d<double, 3> &VolumeAcceleration = (i)->FastGetSolutionStepValue(VOLUME_ACCELERATION); (i)->FastGetSolutionStepValue(ACCELERATION, 0) = VolumeAcceleration; (i)->FastGetSolutionStepValue(VELOCITY, 0) += VolumeAcceleration * rCurrentProcessInfo[DELTA_TIME]; } } const double timeInterval = rCurrentProcessInfo[DELTA_TIME]; unsigned int timeStep = rCurrentProcessInfo[STEP]; if (timeStep == 1) { (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) = 0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 1) = 0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0) = 0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 1) = 0; } else { double &CurrentPressure = (i)->FastGetSolutionStepValue(PRESSURE, 0); double &PreviousPressure = (i)->FastGetSolutionStepValue(PRESSURE, 1); double &CurrentPressureVelocity = (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0); double &CurrentPressureAcceleration = (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0); CurrentPressureAcceleration = CurrentPressureVelocity / timeInterval; CurrentPressureVelocity = (CurrentPressure - PreviousPressure) / timeInterval; CurrentPressureAcceleration += -CurrentPressureVelocity / timeInterval; } } } void CalculateAccelerations() { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); Vector &BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; for (ModelPart::NodeIterator i = rModelPart.NodesBegin(); i != rModelPart.NodesEnd(); ++i) { array_1d<double, 3> &CurrentVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 0); array_1d<double, 3> &PreviousVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 1); array_1d<double, 3> &CurrentAcceleration = (i)->FastGetSolutionStepValue(ACCELERATION, 0); array_1d<double, 3> &PreviousAcceleration = (i)->FastGetSolutionStepValue(ACCELERATION, 1); /* if((i)->IsNot(ISOLATED) || (i)->Is(SOLID)){ */ if ((i)->IsNot(ISOLATED) && ((i)->IsNot(RIGID) || (i)->Is(SOLID))) { UpdateAccelerations(CurrentAcceleration, CurrentVelocity, PreviousAcceleration, PreviousVelocity, BDFcoeffs); } else if ((i)->Is(RIGID)) { array_1d<double, 3> Zeros(3, 0.0); (i)->FastGetSolutionStepValue(ACCELERATION, 0) = Zeros; (i)->FastGetSolutionStepValue(ACCELERATION, 1) = Zeros; } else { (i)->FastGetSolutionStepValue(PRESSURE, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE, 1) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_VELOCITY, 1) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 0) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE_ACCELERATION, 1) = 0.0; if ((i)->SolutionStepsDataHas(VOLUME_ACCELERATION)) { array_1d<double, 3> &VolumeAcceleration = (i)->FastGetSolutionStepValue(VOLUME_ACCELERATION); (i)->FastGetSolutionStepValue(ACCELERATION, 0) = VolumeAcceleration; (i)->FastGetSolutionStepValue(VELOCITY, 0) += VolumeAcceleration * rCurrentProcessInfo[DELTA_TIME]; } } } } inline void UpdateAccelerations(array_1d<double, 3> &CurrentAcceleration, const array_1d<double, 3> &CurrentVelocity, array_1d<double, 3> &PreviousAcceleration, const array_1d<double, 3> &PreviousVelocity, Vector &BDFcoeffs) { noalias(CurrentAcceleration) = -BDFcoeffs[1] * (CurrentVelocity - PreviousVelocity) - PreviousAcceleration; } virtual void CalculateDisplacementsAndPorosity() { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); const double TimeStep = rCurrentProcessInfo[DELTA_TIME]; for (ModelPart::NodeIterator i = rModelPart.NodesBegin(); i != rModelPart.NodesEnd(); ++i) { array_1d<double, 3> &CurrentVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 0); array_1d<double, 3> &PreviousVelocity = (i)->FastGetSolutionStepValue(VELOCITY, 1); array_1d<double, 3> &CurrentDisplacement = (i)->FastGetSolutionStepValue(DISPLACEMENT, 0); array_1d<double, 3> &PreviousDisplacement = (i)->FastGetSolutionStepValue(DISPLACEMENT, 1); /* if( i->IsFixed(DISPLACEMENT_X) == false ) */ CurrentDisplacement[0] = 0.5 * TimeStep * (CurrentVelocity[0] + PreviousVelocity[0]) + PreviousDisplacement[0]; /* if( i->IsFixed(DISPLACEMENT_Y) == false ) */ CurrentDisplacement[1] = 0.5 * TimeStep * (CurrentVelocity[1] + PreviousVelocity[1]) + PreviousDisplacement[1]; /* if( i->IsFixed(DISPLACEMENT_Z) == false ) */ CurrentDisplacement[2] = 0.5 * TimeStep * (CurrentVelocity[2] + PreviousVelocity[2]) + PreviousDisplacement[2]; // currentFluidFractionRate = (currentFluidFraction - previousFluidFraction)/TimeStep; } } void UpdateStressStrain() { ModelPart &rModelPart = BaseType::GetModelPart(); const ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); #pragma omp parallel { ModelPart::ElementIterator ElemBegin; ModelPart::ElementIterator ElemEnd; OpenMPUtils::PartitionedIterators(rModelPart.Elements(), ElemBegin, ElemEnd); for (ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { /* itElem-> InitializeElementStrainStressState(); */ itElem->InitializeSolutionStep(rCurrentProcessInfo); } } /* this->CalculateAccelerations(); */ /* this->CalculatePressureVelocity(); */ /* this->CalculatePressureAcceleration(); */ this->CalculateTemporalVariables(); } void Clear() override { mpMomentumStrategy->Clear(); mpPressureStrategy->Clear(); } ///@} ///@name Access ///@{ void SetEchoLevel(int Level) override { BaseType::SetEchoLevel(Level); int StrategyLevel = Level > 0 ? Level - 1 : 0; mpMomentumStrategy->SetEchoLevel(StrategyLevel); mpPressureStrategy->SetEchoLevel(StrategyLevel); } ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { std::stringstream buffer; buffer << "TwoStepVPStrategy"; return buffer.str(); } /// Print information about this object. void PrintInfo(std::ostream &rOStream) const override { rOStream << "TwoStepVPStrategy"; } /// Print object's data. void PrintData(std::ostream &rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected Life Cycle ///@{ ///@} ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /// Calculate the coefficients for time iteration. /** * @param rCurrentProcessInfo ProcessInfo instance from the fluid ModelPart. Must contain DELTA_TIME and BDF_COEFFICIENTS variables. */ void SetTimeCoefficients(ProcessInfo &rCurrentProcessInfo) { KRATOS_TRY; if (mTimeOrder == 2) { //calculate the BDF coefficients double Dt = rCurrentProcessInfo[DELTA_TIME]; double OldDt = rCurrentProcessInfo.GetPreviousTimeStepInfo(1)[DELTA_TIME]; double Rho = OldDt / Dt; double TimeCoeff = 1.0 / (Dt * Rho * Rho + Dt * Rho); Vector &BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; BDFcoeffs.resize(3, false); BDFcoeffs[0] = TimeCoeff * (Rho * Rho + 2.0 * Rho); //coefficient for step n+1 (3/2Dt if Dt is constant) BDFcoeffs[1] = -TimeCoeff * (Rho * Rho + 2.0 * Rho + 1.0); //coefficient for step n (-4/2Dt if Dt is constant) BDFcoeffs[2] = TimeCoeff; //coefficient for step n-1 (1/2Dt if Dt is constant) } else if (mTimeOrder == 1) { double Dt = rCurrentProcessInfo[DELTA_TIME]; double TimeCoeff = 1.0 / Dt; Vector &BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; BDFcoeffs.resize(2, false); BDFcoeffs[0] = TimeCoeff; //coefficient for step n+1 (1/Dt) BDFcoeffs[1] = -TimeCoeff; //coefficient for step n (-1/Dt) } KRATOS_CATCH(""); } bool SolveMomentumIteration(unsigned int it, unsigned int maxIt, bool &fixedTimeStep, double &velocityNorm) { ModelPart &rModelPart = BaseType::GetModelPart(); int Rank = rModelPart.GetCommunicator().MyPID(); bool ConvergedMomentum = false; double NormDv = 0; fixedTimeStep = false; // build momentum system and solve for fractional step velocity increment rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP, 1); if (it == 0) { mpMomentumStrategy->InitializeSolutionStep(); } NormDv = mpMomentumStrategy->Solve(); if (BaseType::GetEchoLevel() > 1 && Rank == 0) std::cout << "-------------- s o l v e d ! ------------------" << std::endl; if (it == 0) { velocityNorm = this->ComputeVelocityNorm(); } double DvErrorNorm = NormDv / velocityNorm; unsigned int iterationForCheck = 2; // Check convergence if (it == maxIt - 1) { KRATOS_INFO("Iteration") << it << " Final Velocity error: " << DvErrorNorm << std::endl; ConvergedMomentum = this->FixTimeStepMomentum(DvErrorNorm, fixedTimeStep); } else if (it > iterationForCheck) { KRATOS_INFO("Iteration") << it << " Velocity error: " << DvErrorNorm << std::endl; ConvergedMomentum = this->CheckMomentumConvergence(DvErrorNorm, fixedTimeStep); } else { KRATOS_INFO("Iteration") << it << " Velocity error: " << DvErrorNorm << std::endl; } if (!ConvergedMomentum && BaseType::GetEchoLevel() > 0 && Rank == 0) std::cout << "Momentum equations did not reach the convergence tolerance." << std::endl; return ConvergedMomentum; } bool SolveContinuityIteration(unsigned int it, unsigned int maxIt, double &NormP) { ModelPart &rModelPart = BaseType::GetModelPart(); int Rank = rModelPart.GetCommunicator().MyPID(); bool ConvergedContinuity = false; bool fixedTimeStep = false; double NormDp = 0; // 2. Pressure solution rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP, 5); if (it == 0) { mpPressureStrategy->InitializeSolutionStep(); } NormDp = mpPressureStrategy->Solve(); if (BaseType::GetEchoLevel() > 0 && Rank == 0) std::cout << "The norm of pressure is: " << NormDp << std::endl; if (it == 0) { NormP = this->ComputePressureNorm(); } double DpErrorNorm = NormDp / (NormP); // Check convergence if (it == (maxIt - 1)) { KRATOS_INFO("Iteration") << it << " Final Pressure error: " << DpErrorNorm << std::endl; ConvergedContinuity = this->FixTimeStepContinuity(DpErrorNorm, fixedTimeStep); } else { KRATOS_INFO("Iteration") << it << " Pressure error: " << DpErrorNorm << std::endl; ConvergedContinuity = this->CheckContinuityConvergence(DpErrorNorm, fixedTimeStep); } if (!ConvergedContinuity && BaseType::GetEchoLevel() > 0 && Rank == 0) std::cout << "Continuity equation did not reach the convergence tolerance." << std::endl; return ConvergedContinuity; } void ComputeErrorL2Norm() { ModelPart &rModelPart = BaseType::GetModelPart(); const ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); const double currentTime = rCurrentProcessInfo[TIME]; const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); long double sumErrorL2Velocity = 0; long double sumErrorL2VelocityX = 0; long double sumErrorL2VelocityY = 0; long double sumErrorL2Pressure = 0; long double sumErrorL2TauXX = 0; long double sumErrorL2TauYY = 0; long double sumErrorL2TauXY = 0; #pragma omp parallel { ModelPart::ElementIterator ElemBegin; ModelPart::ElementIterator ElemEnd; OpenMPUtils::PartitionedIterators(rModelPart.Elements(), ElemBegin, ElemEnd); for (ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { Element::GeometryType &geometry = itElem->GetGeometry(); long double nodalArea = 0; if (dimension == 2) { nodalArea = geometry.Area() / 3.0; } else if (dimension == 3) { nodalArea = geometry.Volume() * 0.25; } long double bariPosX = 0; long double bariPosY = 0; long double eleErrorL2Velocity = 0; long double eleErrorL2VelocityX = 0; long double eleErrorL2VelocityY = 0; long double eleErrorL2Pressure = 0; //ShapeFunctionDerivativesArrayType DN_DX; Matrix NContainer; NContainer = geometry.ShapeFunctionsValues(GeometryData::GI_GAUSS_1); const Vector &N = row(NContainer, 0); const unsigned int NumNodes = geometry.size(); double elementalPressure = N[0] * geometry(0)->FastGetSolutionStepValue(PRESSURE); double elementalVelocityX = N[0] * geometry(0)->FastGetSolutionStepValue(VELOCITY_X); double elementalVelocityY = N[0] * geometry(0)->FastGetSolutionStepValue(VELOCITY_Y); ; for (unsigned int i = 1; i < NumNodes; i++) { elementalPressure += N[i] * geometry(i)->FastGetSolutionStepValue(PRESSURE); elementalVelocityX += N[i] * geometry(i)->FastGetSolutionStepValue(VELOCITY_X); elementalVelocityY += N[i] * geometry(i)->FastGetSolutionStepValue(VELOCITY_Y); } for (unsigned int i = 0; i < geometry.size(); i++) { const long double nodalPosX = geometry(i)->X(); const long double nodalPosY = geometry(i)->Y(); bariPosX += nodalPosX / 3.0; bariPosY += nodalPosY / 3.0; } const long double posX = bariPosX; const long double posY = bariPosY; long double expectedVelocityX = pow(posX, 2) * (1.0 - posX) * (1.0 - posX) * (2.0 * posY - 6.0 * pow(posY, 2) + 4.0 * pow(posY, 3)); long double expectedVelocityY = -pow(posY, 2) * (1.0 - posY) * (1.0 - posY) * (2.0 * posX - 6.0 * pow(posX, 2) + 4.0 * pow(posX, 3)); long double expectedPressure = -posX * (1.0 - posX); eleErrorL2VelocityX = elementalVelocityX - expectedVelocityX; eleErrorL2VelocityY = elementalVelocityY - expectedVelocityY; eleErrorL2Pressure = elementalPressure - expectedPressure; sumErrorL2VelocityX += pow(eleErrorL2VelocityX, 2) * geometry.Area(); sumErrorL2VelocityY += pow(eleErrorL2VelocityY, 2) * geometry.Area(); sumErrorL2Pressure += pow(eleErrorL2Pressure, 2) * geometry.Area(); const long double tauXX = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_XX); const long double tauYY = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_YY); const long double tauXY = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_XY); long double expectedTauXX = 2.0 * (-4.0 * (1.0 - bariPosX) * bariPosX * (-1.0 + 2.0 * bariPosX) * bariPosY * (1.0 - 3.0 * bariPosY + 2.0 * pow(bariPosY, 2))); long double expectedTauYY = 2.0 * (4.0 * bariPosX * (1.0 - 3.0 * bariPosX + 2.0 * pow(bariPosX, 2)) * (1.0 - bariPosY) * bariPosY * (-1.0 + 2.0 * bariPosY)); long double expectedTauXY = (2.0 * (1.0 - 6.0 * bariPosY + 6.0 * pow(bariPosY, 2)) * (1.0 - bariPosX) * (1.0 - bariPosX) * pow(bariPosX, 2) - 2.0 * (1.0 - 6.0 * bariPosX + 6.0 * pow(bariPosX, 2)) * (1.0 - bariPosY) * (1 - bariPosY) * pow(bariPosY, 2)); long double nodalErrorTauXX = tauXX - expectedTauXX; long double nodalErrorTauYY = tauYY - expectedTauYY; long double nodalErrorTauXY = tauXY - expectedTauXY; sumErrorL2TauXX += pow(nodalErrorTauXX, 2) * geometry.Area(); sumErrorL2TauYY += pow(nodalErrorTauYY, 2) * geometry.Area(); sumErrorL2TauXY += pow(nodalErrorTauXY, 2) * geometry.Area(); } } long double errorL2Velocity = sqrt(sumErrorL2Velocity); long double errorL2VelocityX = sqrt(sumErrorL2VelocityX); long double errorL2VelocityY = sqrt(sumErrorL2VelocityY); long double errorL2Pressure = sqrt(sumErrorL2Pressure); long double errorL2TauXX = sqrt(sumErrorL2TauXX); long double errorL2TauYY = sqrt(sumErrorL2TauYY); long double errorL2TauXY = sqrt(sumErrorL2TauXY); std::ofstream myfileVelocity; myfileVelocity.open("errorL2VelocityFile.txt", std::ios::app); myfileVelocity << currentTime << "\t" << errorL2Velocity << "\n"; myfileVelocity.close(); std::ofstream myfileVelocityX; myfileVelocityX.open("errorL2VelocityXFile.txt", std::ios::app); myfileVelocityX << currentTime << "\t" << errorL2VelocityX << "\n"; myfileVelocityX.close(); std::ofstream myfileVelocityY; myfileVelocityY.open("errorL2VelocityYFile.txt", std::ios::app); myfileVelocityY << currentTime << "\t" << errorL2VelocityY << "\n"; myfileVelocityY.close(); std::ofstream myfilePressure; myfilePressure.open("errorL2PressureFile.txt", std::ios::app); myfilePressure << currentTime << "\t" << errorL2Pressure << "\n"; myfilePressure.close(); std::ofstream myfileTauXX; myfileTauXX.open("errorL2TauXXFile.txt", std::ios::app); myfileTauXX << currentTime << "\t" << errorL2TauXX << "\n"; myfileTauXX.close(); std::ofstream myfileTauYY; myfileTauYY.open("errorL2TauYYFile.txt", std::ios::app); myfileTauYY << currentTime << "\t" << errorL2TauYY << "\n"; myfileTauYY.close(); std::ofstream myfileTauXY; myfileTauXY.open("errorL2TauXYFile.txt", std::ios::app); myfileTauXY << currentTime << "\t" << errorL2TauXY << "\n"; myfileTauXY.close(); } void ComputeErrorL2NormCasePoiseuille() { ModelPart &rModelPart = BaseType::GetModelPart(); const ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); const double currentTime = rCurrentProcessInfo[TIME]; const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); double sumErrorL2VelocityTheta = 0; double sumErrorL2TauTheta = 0; double r_in = 0.2; double R_out = 0.5; double kappa = r_in / R_out; double omega = 0.5; double viscosity = 100.0; #pragma omp parallel { ModelPart::ElementIterator ElemBegin; ModelPart::ElementIterator ElemEnd; OpenMPUtils::PartitionedIterators(rModelPart.Elements(), ElemBegin, ElemEnd); for (ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { Element::GeometryType &geometry = itElem->GetGeometry(); long double nodalArea = 0; if (dimension == 2) { nodalArea = geometry.Area() / 3.0; } else if (dimension == 3) { nodalArea = geometry.Volume() * 0.25; } long double bariPosX = 0; long double bariPosY = 0; long double eleErrorL2Velocity = 0; long double eleErrorL2VelocityX = 0; long double eleErrorL2VelocityY = 0; long double eleErrorL2Pressure = 0; //ShapeFunctionDerivativesArrayType DN_DX; Matrix NContainer; NContainer = geometry.ShapeFunctionsValues(GeometryData::GI_GAUSS_1); //this->CalculateGeometryData(DN_DX,NContainer,GaussWeights); const Vector &N = row(NContainer, 0); // itElem->EvaluateInPoint(elementalPressure,PRESSURE,N); const unsigned int NumNodes = geometry.size(); double elementalPressure = N[0] * geometry(0)->FastGetSolutionStepValue(PRESSURE); double elementalVelocityX = N[0] * geometry(0)->FastGetSolutionStepValue(VELOCITY_X); double elementalVelocityY = N[0] * geometry(0)->FastGetSolutionStepValue(VELOCITY_Y); ; for (unsigned int i = 1; i < NumNodes; i++) { elementalPressure += N[i] * geometry(i)->FastGetSolutionStepValue(PRESSURE); elementalVelocityX += N[i] * geometry(i)->FastGetSolutionStepValue(VELOCITY_X); elementalVelocityY += N[i] * geometry(i)->FastGetSolutionStepValue(VELOCITY_Y); } for (unsigned int i = 0; i < geometry.size(); i++) { // index = i*dimension; const long double nodalPosX = geometry(i)->X(); const long double nodalPosY = geometry(i)->Y(); bariPosX += nodalPosX / 3.0; bariPosY += nodalPosY / 3.0; } const long double posX = bariPosX; const long double posY = bariPosY; const double rPos = sqrt(pow(posX, 2) + pow(posY, 2)); const double cosalfa = posX / rPos; const double sinalfa = posY / rPos; const double sin2alfa = 2.0 * cosalfa * sinalfa; const double cos2alfa = 1.0 - 2.0 * pow(sinalfa, 2); double expectedVelocityTheta = pow(kappa, 2) * omega * R_out / (1.0 - pow(kappa, 2)) * (R_out / rPos - rPos / R_out); double computedVelocityTheta = sqrt(pow(elementalVelocityX, 2) + pow(elementalVelocityY, 2)); double nodalErrorVelocityTheta = computedVelocityTheta - expectedVelocityTheta; const long double tauXX = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_XX); const long double tauYY = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_YY); const long double tauXY = 0; // itElem->GetValue(ELEMENTAL_DEVIATORIC_STRESS_XY); double expectedTauTheta = (2.0 * viscosity * pow(kappa, 2) * omega * pow(R_out, 2)) / (1.0 - pow(kappa, 2)) / pow(rPos, 2); double computedTauTheta = (tauXX - tauYY) * sin2alfa / 2.0 - tauXY * cos2alfa; double nodalErrorTauTheta = computedTauTheta - expectedTauTheta; sumErrorL2VelocityTheta += pow(nodalErrorVelocityTheta, 2) * geometry.Area(); sumErrorL2TauTheta += pow(nodalErrorTauTheta, 2) * geometry.Area(); } } double errorL2VelocityTheta = sqrt(sumErrorL2VelocityTheta); double errorL2TauTheta = sqrt(sumErrorL2TauTheta); std::ofstream myfileVelocity; myfileVelocity.open("errorL2Poiseuille.txt", std::ios::app); myfileVelocity << currentTime << "\t" << errorL2VelocityTheta << "\t" << errorL2TauTheta << "\n"; myfileVelocity.close(); } double ComputeVelocityNorm() { ModelPart &rModelPart = BaseType::GetModelPart(); double NormV = 0.00; #pragma omp parallel reduction(+ \ : NormV) { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { const array_1d<double, 3> &Vel = itNode->FastGetSolutionStepValue(VELOCITY); double NormVelNode = 0; for (unsigned int d = 0; d < 3; ++d) { NormVelNode += Vel[d] * Vel[d]; NormV += Vel[d] * Vel[d]; } } } BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormV); NormV = sqrt(NormV); if (NormV == 0.0) NormV = 1.00; return NormV; } bool CheckVelocityConvergence(const double NormDv, double &errorNormDv) { ModelPart &rModelPart = BaseType::GetModelPart(); double NormV = 0.00; errorNormDv = 0; #pragma omp parallel reduction(+ \ : NormV) { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { const array_1d<double, 3> &Vel = itNode->FastGetSolutionStepValue(VELOCITY); double NormVelNode = 0; for (unsigned int d = 0; d < 3; ++d) { NormVelNode += Vel[d] * Vel[d]; NormV += Vel[d] * Vel[d]; } } } BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormV); NormV = sqrt(NormV); if (NormV == 0.0) NormV = 1.00; errorNormDv = NormDv / NormV; if (BaseType::GetEchoLevel() > 0 && rModelPart.GetCommunicator().MyPID() == 0) { std::cout << "The norm of velocity increment is: " << NormDv << std::endl; std::cout << "The norm of velocity is: " << NormV << std::endl; std::cout << "Velocity error: " << errorNormDv << "mVelocityTolerance: " << mVelocityTolerance << std::endl; } /* else{ */ /* std::cout<<"Velocity error: "<< errorNormDv <<" velTol: " << mVelocityTolerance<< std::endl; */ /* } */ if (errorNormDv < mVelocityTolerance) { return true; } else { return false; } } bool CheckPressureConvergence(const double NormDp, double &errorNormDp, double &NormP) { ModelPart &rModelPart = BaseType::GetModelPart(); NormP = 0.00; errorNormDp = 0; #pragma omp parallel reduction(+ \ : NormP) { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { const double Pr = itNode->FastGetSolutionStepValue(PRESSURE); NormP += Pr * Pr; } } BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormP); NormP = sqrt(NormP); if (NormP == 0.0) NormP = 1.00; errorNormDp = NormDp / (NormP); if (BaseType::GetEchoLevel() > 0 && rModelPart.GetCommunicator().MyPID() == 0) { std::cout << " The norm of pressure increment is: " << NormDp << std::endl; std::cout << " The norm of pressure is: " << NormP << std::endl; std::cout << " Pressure error: " << errorNormDp << std::endl; } /* else{ */ /* std::cout<<" Pressure error: "<<errorNormDp <<" presTol: "<<mPressureTolerance << std::endl; */ /* } */ if (errorNormDp < mPressureTolerance) { return true; } else return false; } double ComputePressureNorm() { ModelPart &rModelPart = BaseType::GetModelPart(); double NormP = 0.00; #pragma omp parallel reduction(+ \ : NormP) { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { const double Pr = itNode->FastGetSolutionStepValue(PRESSURE); NormP += Pr * Pr; } } BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormP); NormP = sqrt(NormP); if (NormP == 0.0) NormP = 1.00; return NormP; } bool FixTimeStepMomentum(const double DvErrorNorm, bool &fixedTimeStep) { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); double currentTime = rCurrentProcessInfo[TIME]; double timeInterval = rCurrentProcessInfo[DELTA_TIME]; double minTolerance = 0.005; bool converged = false; if (currentTime < 10 * timeInterval) { minTolerance = 10; } if ((DvErrorNorm > minTolerance || (DvErrorNorm < 0 && DvErrorNorm > 0) || (DvErrorNorm != DvErrorNorm)) && DvErrorNorm != 0 && (DvErrorNorm != 1 || currentTime > timeInterval)) { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, true); std::cout << "NOT GOOD CONVERGENCE!!! I'll reduce the next time interval" << DvErrorNorm << std::endl; minTolerance = 0.05; if (DvErrorNorm > minTolerance) { std::cout << "BAD CONVERGENCE!!! I GO AHEAD WITH THE PREVIOUS VELOCITY AND PRESSURE FIELDS" << DvErrorNorm << std::endl; fixedTimeStep = true; #pragma omp parallel { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { itNode->FastGetSolutionStepValue(VELOCITY, 0) = itNode->FastGetSolutionStepValue(VELOCITY, 1); itNode->FastGetSolutionStepValue(PRESSURE, 0) = itNode->FastGetSolutionStepValue(PRESSURE, 1); itNode->FastGetSolutionStepValue(ACCELERATION, 0) = itNode->FastGetSolutionStepValue(ACCELERATION, 1); } } } } else { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, false); if (DvErrorNorm < mVelocityTolerance) { converged = true; } } return converged; } bool CheckMomentumConvergence(const double DvErrorNorm, bool &fixedTimeStep) { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); double currentTime = rCurrentProcessInfo[TIME]; double timeInterval = rCurrentProcessInfo[DELTA_TIME]; double minTolerance = 0.99999; bool converged = false; if ((DvErrorNorm > minTolerance || (DvErrorNorm < 0 && DvErrorNorm > 0) || (DvErrorNorm != DvErrorNorm)) && DvErrorNorm != 0 && (DvErrorNorm != 1 || currentTime > timeInterval)) { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, true); std::cout << " BAD CONVERGENCE DETECTED DURING THE ITERATIVE LOOP!!! error: " << DvErrorNorm << " higher than 0.9999" << std::endl; std::cout << " I GO AHEAD WITH THE PREVIOUS VELOCITY AND PRESSURE FIELDS" << std::endl; fixedTimeStep = true; #pragma omp parallel { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { itNode->FastGetSolutionStepValue(VELOCITY, 0) = itNode->FastGetSolutionStepValue(VELOCITY, 1); itNode->FastGetSolutionStepValue(PRESSURE, 0) = itNode->FastGetSolutionStepValue(PRESSURE, 1); itNode->FastGetSolutionStepValue(ACCELERATION, 0) = itNode->FastGetSolutionStepValue(ACCELERATION, 1); } } } else { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, false); if (DvErrorNorm < mVelocityTolerance) { converged = true; } } return converged; } bool FixTimeStepContinuity(const double DvErrorNorm, bool &fixedTimeStep) { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); double currentTime = rCurrentProcessInfo[TIME]; double timeInterval = rCurrentProcessInfo[DELTA_TIME]; double minTolerance = 0.01; bool converged = false; if (currentTime < 10 * timeInterval) { minTolerance = 10; } if ((DvErrorNorm > minTolerance || (DvErrorNorm < 0 && DvErrorNorm > 0) || (DvErrorNorm != DvErrorNorm)) && DvErrorNorm != 0 && (DvErrorNorm != 1 || currentTime > timeInterval)) { fixedTimeStep = true; // rCurrentProcessInfo.SetValue(BAD_PRESSURE_CONVERGENCE, true); if (DvErrorNorm > 0.9999) { rCurrentProcessInfo.SetValue(BAD_VELOCITY_CONVERGENCE, true); std::cout << " BAD PRESSURE CONVERGENCE DETECTED DURING THE ITERATIVE LOOP!!! error: " << DvErrorNorm << " higher than 0.1" << std::endl; std::cout << " I GO AHEAD WITH THE PREVIOUS VELOCITY AND PRESSURE FIELDS" << std::endl; fixedTimeStep = true; #pragma omp parallel { ModelPart::NodeIterator NodeBegin; ModelPart::NodeIterator NodeEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodeBegin, NodeEnd); for (ModelPart::NodeIterator itNode = NodeBegin; itNode != NodeEnd; ++itNode) { itNode->FastGetSolutionStepValue(VELOCITY, 0) = itNode->FastGetSolutionStepValue(VELOCITY, 1); itNode->FastGetSolutionStepValue(PRESSURE, 0) = itNode->FastGetSolutionStepValue(PRESSURE, 1); itNode->FastGetSolutionStepValue(ACCELERATION, 0) = itNode->FastGetSolutionStepValue(ACCELERATION, 1); } } } } else if (DvErrorNorm < mPressureTolerance) { converged = true; fixedTimeStep = false; } rCurrentProcessInfo.SetValue(BAD_PRESSURE_CONVERGENCE, false); return converged; } bool CheckContinuityConvergence(const double DvErrorNorm, bool &fixedTimeStep) { ModelPart &rModelPart = BaseType::GetModelPart(); ProcessInfo &rCurrentProcessInfo = rModelPart.GetProcessInfo(); bool converged = false; if (DvErrorNorm < mPressureTolerance) { converged = true; fixedTimeStep = false; } rCurrentProcessInfo.SetValue(BAD_PRESSURE_CONVERGENCE, false); return converged; } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ double mVelocityTolerance; double mPressureTolerance; unsigned int mMaxPressureIter; unsigned int mDomainSize; unsigned int mTimeOrder; bool mReformDofSet; // Fractional step index. /* 1 : Momentum step (calculate fractional step velocity) * 2-3 : Unused (reserved for componentwise calculation of frac step velocity) * 4 : Pressure step * 5 : Computation of projections * 6 : End of step velocity */ // unsigned int mStepId; /// Scheme for the solution of the momentum equation StrategyPointerType mpMomentumStrategy; /// Scheme for the solution of the mass equation StrategyPointerType mpPressureStrategy; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ virtual void InitializeStrategy(SolverSettingsType &rSolverConfig) { KRATOS_TRY; mTimeOrder = rSolverConfig.GetTimeOrder(); // Check that input parameters are reasonable and sufficient. this->Check(); //ModelPart& rModelPart = this->GetModelPart(); mDomainSize = rSolverConfig.GetDomainSize(); mReformDofSet = rSolverConfig.GetReformDofSet(); BaseType::SetEchoLevel(rSolverConfig.GetEchoLevel()); // Initialize strategies for each step bool HaveVelStrategy = rSolverConfig.FindStrategy(SolverSettingsType::Velocity, mpMomentumStrategy); if (HaveVelStrategy) { rSolverConfig.FindTolerance(SolverSettingsType::Velocity, mVelocityTolerance); /* rSolverConfig.FindMaxIter(SolverSettingsType::Velocity,mMaxVelocityIter); */ } else { KRATOS_THROW_ERROR(std::runtime_error, "TwoStepVPStrategy error: No Velocity strategy defined in FractionalStepSettings", ""); } bool HavePressStrategy = rSolverConfig.FindStrategy(SolverSettingsType::Pressure, mpPressureStrategy); if (HavePressStrategy) { rSolverConfig.FindTolerance(SolverSettingsType::Pressure, mPressureTolerance); rSolverConfig.FindMaxIter(SolverSettingsType::Pressure, mMaxPressureIter); } else { KRATOS_THROW_ERROR(std::runtime_error, "TwoStepVPStrategy error: No Pressure strategy defined in FractionalStepSettings", ""); } // Check input parameters this->Check(); KRATOS_CATCH(""); } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. TwoStepVPStrategy &operator=(TwoStepVPStrategy const &rOther) {} /// Copy constructor. TwoStepVPStrategy(TwoStepVPStrategy const &rOther) {} ///@} }; /// Class TwoStepVPStrategy ///@} ///@name Type Definitions ///@{ ///@} ///@} // addtogroup } // namespace Kratos. #endif // KRATOS_TWO_STEP_V_P_STRATEGY_H
GB_binop__plus_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__plus_int16) // A.*B function (eWiseMult): GB (_AemultB_08__plus_int16) // A.*B function (eWiseMult): GB (_AemultB_02__plus_int16) // A.*B function (eWiseMult): GB (_AemultB_04__plus_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_int16) // A*D function (colscale): GB (_AxD__plus_int16) // D*A function (rowscale): GB (_DxB__plus_int16) // C+=B function (dense accum): GB (_Cdense_accumB__plus_int16) // C+=b function (dense accum): GB (_Cdense_accumb__plus_int16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_int16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_int16) // C=scalar+B GB (_bind1st__plus_int16) // C=scalar+B' GB (_bind1st_tran__plus_int16) // C=A+scalar GB (_bind2nd__plus_int16) // C=A'+scalar GB (_bind2nd_tran__plus_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij + bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x + y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_PLUS || GxB_NO_INT16 || GxB_NO_PLUS_INT16) //------------------------------------------------------------------------------ // 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__plus_int16) ( 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__plus_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__plus_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__plus_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__plus_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__plus_int16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__plus_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__plus_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__plus_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__plus_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__plus_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__plus_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x + bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__plus_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij + y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x + aij) ; \ } GrB_Info GB (_bind1st_tran__plus_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij + y) ; \ } GrB_Info GB (_bind2nd_tran__plus_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mpncflint.c
/* $Header$ */ /* mpncflint -- netCDF file interpolator */ /* Purpose: Linearly interpolate a third netCDF file from two input files */ /* Copyright (C) 1995--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. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* Usage: ncflint -O -D 2 in.nc in.nc ~/foo.nc ncflint -O -i lcl_time_hr,9.0 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncflint -O -w 0.66666,0.33333 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncflint -O -w 0.66666 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncdiff -O foo.nc /data/zender/arese/clm/951030_0900_arese_clm.nc foo2.nc;ncks -H foo2.nc | m */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <math.h> /* sin cos cos sin 3.14159 */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* abs, getopt, malloc, strtol */ #include <string.h> /* strcmp() */ #include <sys/stat.h> /* stat() */ #include <time.h> /* machine time */ #include <unistd.h> /* POSIX stuff */ #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ /* 3rd party vendors */ #ifdef ENABLE_MPI #include <mpi.h> /* MPI definitions */ #include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ #include <netcdf.h> /* netCDF definitions and C library */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ int main(int argc,char **argv) { char **fl_lst_abb=NULL; /* Option a */ char **fl_lst_in; char **gaa_arg=NULL; /* [sng] Global attribute arguments */ char **ntp_lst_in; char **var_lst_in=NULL_CEWI; char *aux_arg[NC_MAX_DIMS]; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *fl_in_1=NULL; /* fl_in_1 is nco_realloc'd when not NULL */ char *fl_in_2=NULL; /* fl_in_2 is nco_realloc'd when not NULL */ char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL; /* MPI CEWI */ char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *lmt_arg[NC_MAX_DIMS]; char *ntp_nm=NULL; /* Option i */ char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567ACcD:d:Fhi:L:l:Oo:p:rRSt:v:xw:-:"; cnk_dmn_sct **cnk_dmn=NULL_CEWI; dmn_sct **dim; dmn_sct **dmn_out; double ntp_val_out=double_CEWI; /* Option i */ double wgt_val_1=0.5; /* Option w */ double wgt_val_2=0.5; /* Option w */ extern char *optarg; extern int optind; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped shared in parallel clause */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ int *in_id_1_arr; int *in_id_2_arr; int abb_arg_nbr=0; int aux_nbr=0; /* [nbr] Number of auxiliary coordinate hyperslabs specified */ int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_idx; int fl_nbr=0; int fl_in_fmt_1; /* [enm] Input file format */ int fl_in_fmt_2; /* [enm] Input file format */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int has_mss_val=False; int idx; int jdx; int in_id_1; int in_id_2; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int nbr_dmn_fl; int nbr_dmn_xtr; int nbr_ntp; int nbr_var_fix; /* nbr_var_fix gets incremented */ int nbr_var_fl; int nbr_var_prc; /* nbr_var_prc gets incremented */ int xtr_nbr=0; /* xtr_nbr won't otherwise be set for -c with no -v */ int opt; int out_id; int rcd=NC_NOERR; /* [rcd] Return code */ int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; lmt_sct **aux=NULL_CEWI; /* Auxiliary coordinate limits */ lmt_sct **lmt; lmt_all_sct **lmt_all_lst; /* List of *lmt_all structures */ cnv_sct *cnv; /* [sct] Convention structure */ nco_bool CMD_LN_NTP_VAR=False; /* Option i */ nco_bool CMD_LN_NTP_WGT=True; /* Option w */ nco_bool DO_CONFORM=False; /* Did nco_var_cnf_dmn() find truly conforming variables? */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option c */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool FILE_1_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FILE_2_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool MSA_USR_RDR=False; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order*/ nco_bool MUST_CONFORM=False; /* Must nco_var_cnf_dmn() find truly conforming variables? */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ nm_id_sct *dmn_lst; nm_id_sct *xtr_lst=NULL; /* xtr_lst may be alloc()'d from NULL with -c option */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ val_unn val_gnr_unn; /* Generic container for arrival point or weight */ var_sct *wgt_1=NULL_CEWI; var_sct *wgt_2=NULL_CEWI; var_sct *wgt_out_1=NULL; var_sct *wgt_out_2=NULL; var_sct **var; var_sct **var_fix; var_sct **var_fix_out; var_sct **var_out; var_sct **var_prc_1; var_sct **var_prc_2; var_sct **var_prc_out; #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Status mpi_stt; /* [enm] Status check to decode msg_tag_typ */ nco_bool TKN_WRT_FREE=True; /* [flg] Write-access to output file is available */ int fl_nm_lng; /* [nbr] Output file name length */ int msg_bfr[msg_bfr_lng]; /* [bfr] Buffer containing var, idx, tkn_wrt_rsp */ int msg_tag_typ; /* [enm] MPI message tag type */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ int tkn_wrt_rsp; /* [enm] Response to request for write token */ int var_wrt_nbr=0; /* [nbr] Variables written to output file until now */ int rnk_wrk; /* [idx] Worker rank */ int wrk_id_bfr[wrk_id_bfr_lng]; /* [bfr] Buffer for rnk_wrk */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"clean",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"mmr_cln",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"dirty",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"mmr_drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, /* Long options with argument, no short option counterpart */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"append",no_argument,0,'A'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"interpolate",required_argument,0,'i'}, {"ntp",required_argument,0,'i'}, {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"local",required_argument,0,'l'}, {"lcl",required_argument,0,'l'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"output",required_argument,0,'o'}, {"fl_out",required_argument,0,'o'}, {"path",required_argument,0,'p'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"suspend", no_argument,0,'S'}, {"thr_nbr",required_argument,0,'t'}, {"variable",required_argument,0,'v'}, {"weight",required_argument,0,'w'}, {"wgt_var",no_argument,0,'w'}, {"auxiliary",required_argument,0,'X'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"help",no_argument,0,'?'}, {"hlp",no_argument,0,'?'}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef ENABLE_MPI /* MPI Initialization */ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&prc_nbr); MPI_Comm_rank(MPI_COMM_WORLD,&prc_rnk); #endif /* !ENABLE_MPI */ /* Start clock and save command line */ cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* endif gaa */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=False; break; case 'c': EXTRACT_ALL_COORDINATES=True; break; case 'D': /* The debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'i': /* Name of variable to guide interpolation. Default is none */ ntp_lst_in=nco_lst_prs_2D(optarg,",",&nbr_ntp); if(nbr_ntp > 2){ (void)fprintf(stdout,"%s: ERROR too many arguments to -i\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end if */ ntp_nm=ntp_lst_in[0]; ntp_val_out=strtod(ntp_lst_in[1],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtod",sng_cnv_rcd); CMD_LN_NTP_VAR=True; CMD_LN_NTP_WGT=False; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(fp_stdout,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr=var_lst_in_nbr; break; case 'w': /* Weight(s) for interpolation. Default is wgt_val_1=wgt_val_2=0.5 */ ntp_lst_in=nco_lst_prs_2D(optarg,",",&nbr_ntp); if(nbr_ntp > 2){ (void)fprintf(stdout,"%s: ERROR too many arguments to -w\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); }else if(nbr_ntp == 2){ wgt_val_1=strtod(ntp_lst_in[0],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[0],"strtod",sng_cnv_rcd); wgt_val_2=strtod(ntp_lst_in[1],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[1],"strtod",sng_cnv_rcd); }else if(nbr_ntp == 1){ wgt_val_1=strtod(ntp_lst_in[0],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[0],"strtod",sng_cnv_rcd); wgt_val_2=1.0-wgt_val_1; } /* end else */ CMD_LN_NTP_WGT=True; break; case 'X': /* Copy auxiliary coordinate argument for later processing */ aux_arg[aux_nbr]=(char *)strdup(optarg); aux_nbr++; MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ break; case 'x': /* Exclude rather than extract variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case '?': /* Print proper usage */ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ if(CMD_LN_NTP_VAR && CMD_LN_NTP_WGT){ (void)fprintf(stdout,"%s: ERROR interpolating variable (-i) and fixed weight(s) (-w) both set\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); }else if(!CMD_LN_NTP_VAR && !CMD_LN_NTP_WGT){ (void)fprintf(stdout,"%s: ERROR interpolating variable (-i) or fixed weight(s) (-w) must be set\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end else */ /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Make uniform list of user-specified chunksizes */ if(cnk_nbr > 0) cnk_dmn=nco_cnk_prs(cnk_nbr,cnk_arg); /* Make uniform list of user-specified dimension limits */ lmt=nco_lmt_prs(lmt_nbr,lmt_arg); /* Initialize thread information */ thr_nbr=nco_openmp_ini(thr_nbr); in_id_1_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); in_id_2_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); /* Parse filenames */ fl_idx=0; /* Input file _1 */ fl_in_1=nco_fl_nm_prs(fl_in_1,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\nInput file %d is %s; ",fl_idx,fl_in_1); /* Make sure file is on local system and is readable or die trying */ fl_in_1=nco_fl_mk_lcl(fl_in_1,fl_pth_lcl,&FILE_1_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"local file %s:\n",fl_in_1); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_1,md_open,&bfr_sz_hnt,in_id_1_arr+thr_idx); in_id_1=in_id_1_arr[0]; fl_idx=1; /* Input file _2 */ fl_in_2=nco_fl_nm_prs(fl_in_2,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\nInput file %d is %s; ",fl_idx,fl_in_2); /* Make sure file is on local system and is readable or die trying */ fl_in_2=nco_fl_mk_lcl(fl_in_2,fl_pth_lcl,&FILE_2_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"local file %s:\n",fl_in_2); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_2,md_open,&bfr_sz_hnt,in_id_2_arr+thr_idx); in_id_2=in_id_2_arr[0]; /* Parse auxiliary coordinates */ if(aux_nbr > 0){ int aux_idx_nbr; aux=nco_aux_evl(in_id_1,aux_nbr,aux_arg,&aux_idx_nbr); if(aux_idx_nbr > 0){ lmt=(lmt_sct **)nco_realloc(lmt,(lmt_nbr+aux_idx_nbr)*sizeof(lmt_sct *)); int lmt_nbr_new=lmt_nbr+aux_idx_nbr; int aux_idx=0; for(int lmt_idx=lmt_nbr;lmt_idx<lmt_nbr_new;lmt_idx++) lmt[lmt_idx]=aux[aux_idx++]; lmt_nbr=lmt_nbr_new; } /* endif aux */ } /* endif aux_nbr */ /* Get number of variables and dimensions in file */ (void)nco_inq(in_id_1,&nbr_dmn_fl,&nbr_var_fl,(int *)NULL,(int *)NULL); (void)nco_inq_format(in_id_1,&fl_in_fmt_1); (void)nco_inq_format(in_id_2,&fl_in_fmt_2); /* Form initial extraction list which may include extended regular expressions */ xtr_lst=nco_var_lst_mk(in_id_1,nbr_var_fl,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr); /* Change included variables to excluded variables */ if(EXCLUDE_INPUT_LIST) xtr_lst=nco_var_lst_xcl(in_id_1,nbr_var_fl,xtr_lst,&xtr_nbr); /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id_1); /* Add all coordinate variables to extraction list */ if(EXTRACT_ALL_COORDINATES) xtr_lst=nco_var_lst_crd_add(in_id_1,nbr_dmn_fl,nbr_var_fl,xtr_lst,&xtr_nbr,cnv); /* Extract coordinates associated with extracted variables */ if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst=nco_var_lst_crd_ass_add(in_id_1,xtr_lst,&xtr_nbr,cnv); /* Sort extraction list by variable ID for fastest I/O */ if(xtr_nbr > 1) xtr_lst=nco_lst_srt_nm_id(xtr_lst,xtr_nbr,False); /* We now have final list of variables to extract. Phew. */ /* Find coordinate/dimension values associated with user-specified limits NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ for(idx=0;idx<lmt_nbr;idx++) (void)nco_lmt_evl(in_id_1,lmt[idx],0L,FORTRAN_IDX_CNV); /* Place all dimensions in lmt_all_lst */ lmt_all_lst=(lmt_all_sct **)nco_malloc(nbr_dmn_fl*sizeof(lmt_all_sct *)); /* Initialize lmt_all_sct's */ (void)nco_msa_lmt_all_ntl(in_id_1,MSA_USR_RDR,lmt_all_lst,nbr_dmn_fl,lmt,lmt_nbr); /* Find dimensions associated with variables to be extracted */ dmn_lst=nco_dmn_lst_ass_var(in_id_1,xtr_lst,xtr_nbr,&nbr_dmn_xtr); /* Fill-in dimension structure for all extracted dimensions */ dim=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++) dim[idx]=nco_dmn_fll(in_id_1,dmn_lst[idx].id,dmn_lst[idx].nm); /* Dimension list no longer needed */ dmn_lst=nco_nm_id_lst_free(dmn_lst,nbr_dmn_xtr); /* Duplicate input dimension structures for output dimension structures */ dmn_out=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++){ dmn_out[idx]=nco_dmn_dpl(dim[idx]); (void)nco_dmn_xrf(dim[idx],dmn_out[idx]); } /* end loop over idx */ /* Merge hyperslab limit information into dimension structures */ if(nbr_dmn_fl > 0) (void)nco_dmn_lmt_all_mrg(dmn_out,nbr_dmn_xtr,lmt_all_lst,nbr_dmn_fl); /* Fill-in variable structure list for all extracted variables */ var=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); var_out=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); for(idx=0;idx<xtr_nbr;idx++){ var[idx]=nco_var_fll(in_id_1,xtr_lst[idx].id,xtr_lst[idx].nm,dim,nbr_dmn_xtr); var_out[idx]=nco_var_dpl(var[idx]); (void)nco_xrf_var(var[idx],var_out[idx]); (void)nco_xrf_dmn(var_out[idx]); } /* end loop over idx */ /* Extraction list no longer needed */ xtr_lst=nco_nm_id_lst_free(xtr_lst,xtr_nbr); /* Divide variable lists into lists of fixed variables and variables to be processed */ (void)nco_var_lst_dvd(var,var_out,xtr_nbr,cnv,True,nco_pck_plc_nil,nco_pck_map_nil,(dmn_sct **)NULL,0,&var_fix,&var_fix_out,&nbr_var_fix,&var_prc_1,&var_prc_out,&nbr_var_prc); /* Assign zero to start and unity to stride vectors in output variables */ (void)nco_var_srd_srt_set(var_out,xtr_nbr); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt_1; /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Copy global attributes */ (void)nco_att_cpy(in_id_1,out_id,NC_GLOBAL,NC_GLOBAL,(nco_bool)True); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in_1,in_id_1,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); #ifdef ENABLE_MPI /* Initialize MPI task information */ if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); #endif /* !ENABLE_MPI */ /* Define dimensions in output file */ (void)nco_dmn_dfn(fl_out,out_id,dmn_out,nbr_dmn_xtr); /* Define variables in output file, copy their attributes */ (void)nco_var_dfn(in_id_1,fl_out,out_id,var_out,xtr_nbr,(dmn_sct **)NULL,(int)0,nco_pck_plc_nil,nco_pck_map_nil,dfl_lvl); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ /* Manager obtains output filename and broadcasts to workers */ if(prc_rnk == rnk_mgr) fl_nm_lng=(int)strlen(fl_out_tmp); MPI_Bcast(&fl_nm_lng,1,MPI_INT,0,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) fl_out_tmp=(char *)nco_malloc((fl_nm_lng+1)*sizeof(char)); MPI_Bcast(fl_out_tmp,fl_nm_lng+1,MPI_CHAR,0,MPI_COMM_WORLD); if(prc_rnk == rnk_mgr){ /* MPI manager code */ TKN_WRT_FREE=False; #endif /* !ENABLE_MPI */ /* Copy variable data for non-processed variables */ (void)nco_msa_var_val_cpy(in_id_1,out_id,var_fix,nbr_var_fix,lmt_all_lst,nbr_dmn_fl); #ifdef ENABLE_MPI /* Close output file so workers can open it */ nco_close(out_id); TKN_WRT_FREE=True; } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* Perform various error-checks on input file */ if(False) (void)nco_fl_cmp_err_chk(); /* ncflint-specific stuff: */ /* Find the weighting variable in input file */ if(CMD_LN_NTP_VAR){ int ntp_id_1; int ntp_id_2; var_sct *ntp_1; var_sct *ntp_2; var_sct *ntp_var_out; /* Turn arrival point into pseudo-variable */ val_gnr_unn.d=ntp_val_out; /* Generic container for arrival point or weight */ ntp_var_out=scl_mk_var(val_gnr_unn,NC_DOUBLE); rcd=nco_inq_varid(in_id_1,ntp_nm,&ntp_id_1); rcd=nco_inq_varid(in_id_2,ntp_nm,&ntp_id_2); ntp_1=nco_var_fll(in_id_1,ntp_id_1,ntp_nm,dim,nbr_dmn_xtr); ntp_2=nco_var_fll(in_id_2,ntp_id_2,ntp_nm,dim,nbr_dmn_xtr); /* Currently, only support scalar variables */ if(ntp_1->sz > 1 || ntp_2->sz > 1){ (void)fprintf(stdout,"%s: ERROR interpolation variable %s must be scalar\n",nco_prg_nm_get(),ntp_nm); nco_exit(EXIT_FAILURE); } /* end if */ /* Retrieve interpolation variable */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id_1,ntp_1); (void)nco_var_get(in_id_2,ntp_2); /* Weights must be NC_DOUBLE */ ntp_1=nco_var_cnf_typ((nc_type)NC_DOUBLE,ntp_1); ntp_2=nco_var_cnf_typ((nc_type)NC_DOUBLE,ntp_2); /* Check for degenerate case */ if(ntp_1->val.dp[0] == ntp_2->val.dp[0]){ (void)fprintf(stdout,"%s: ERROR Interpolation variable %s is identical (%g) in input files, therefore unable to interpolate.\n",nco_prg_nm_get(),ntp_nm,ntp_1->val.dp[0]); nco_exit(EXIT_FAILURE); } /* end if */ /* Turn weights into pseudo-variables */ wgt_1=nco_var_dpl(ntp_2); wgt_2=nco_var_dpl(ntp_var_out); /* Subtract to find interpolation distances */ (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_var_out->val,wgt_1->val); (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_1->val,wgt_2->val); (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_1->val,ntp_2->val); /* Normalize to obtain final interpolation weights */ (void)nco_var_dvd(wgt_1->type,wgt_1->sz,wgt_1->has_mss_val,wgt_1->mss_val,ntp_2->val,wgt_1->val); (void)nco_var_dvd(wgt_2->type,wgt_2->sz,wgt_2->has_mss_val,wgt_2->mss_val,ntp_2->val,wgt_2->val); if(ntp_1) ntp_1=nco_var_free(ntp_1); if(ntp_2) ntp_2=nco_var_free(ntp_2); if(ntp_var_out) ntp_var_out=nco_var_free(ntp_var_out); } /* end if CMD_LN_NTP_VAR */ if(CMD_LN_NTP_WGT){ val_gnr_unn.d=wgt_val_1; /* Generic container for arrival point or weight */ wgt_1=scl_mk_var(val_gnr_unn,NC_DOUBLE); val_gnr_unn.d=wgt_val_2; /* Generic container for arrival point or weight */ wgt_2=scl_mk_var(val_gnr_unn,NC_DOUBLE); } /* end if CMD_LN_NTP_WGT */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,"wgt_1 = %g, wgt_2 = %g\n",wgt_1->val.dp[0],wgt_2->val.dp[0]); /* Create structure list for second file */ var_prc_2=(var_sct **)nco_malloc(nbr_var_prc*sizeof(var_sct *)); /* Loop over each interpolated variable */ #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc){ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ TKN_WRT_FREE=True; if(idx > nbr_var_prc-1){ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ }else{ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); /* msg_tag_typ != msg_tag_wrk_rqs */ }else if(msg_tag_typ == msg_tag_tkn_wrt_rqs){ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* end while var_wrt_nbr < nbr_var_prc */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ wrk_id_bfr[0]=prc_rnk; while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,0,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass) break; else{ var_prc_out[idx]->id=msg_bfr[2]; /* Process this variable same as UP code */ #else /* !ENABLE_MPI */ #ifdef _OPENMP /* OpenMP notes: shared(): msk and wgt are not altered within loop private(): wgt_avg does not need initialization */ #pragma omp parallel for default(none) firstprivate(wgt_1,wgt_2,wgt_out_1,wgt_out_2) private(DO_CONFORM,idx,in_id_1,in_id_2,has_mss_val) shared(MUST_CONFORM,nco_dbg_lvl,dim,fl_in_1,fl_in_2,fl_out,in_id_1_arr,in_id_2_arr,nbr_dmn_xtr,nbr_var_prc,out_id,nco_prg_nm,var_prc_1,var_prc_2,var_prc_out,lmt_all_lst,nbr_dmn_fl) #endif /* !_OPENMP */ /* UP and SMP codes main loop over variables */ for(idx=0;idx<nbr_var_prc;idx++){ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(fp_stderr,"%s, ",var_prc_1[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); in_id_1=in_id_1_arr[omp_get_thread_num()]; in_id_2=in_id_2_arr[omp_get_thread_num()]; var_prc_2[idx]=nco_var_dpl(var_prc_1[idx]); (void)nco_var_mtd_refresh(in_id_2,var_prc_2[idx]); /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_msa_var_get(in_id_1,var_prc_1[idx],lmt_all_lst,nbr_dmn_fl); (void)nco_msa_var_get(in_id_2,var_prc_2[idx],lmt_all_lst,nbr_dmn_fl); wgt_out_1=nco_var_cnf_dmn(var_prc_1[idx],wgt_1,wgt_out_1,MUST_CONFORM,&DO_CONFORM); wgt_out_2=nco_var_cnf_dmn(var_prc_2[idx],wgt_2,wgt_out_2,MUST_CONFORM,&DO_CONFORM); var_prc_1[idx]=nco_var_cnf_typ((nc_type)NC_DOUBLE,var_prc_1[idx]); var_prc_2[idx]=nco_var_cnf_typ((nc_type)NC_DOUBLE,var_prc_2[idx]); /* Allocate and, if necesssary, initialize space for processed variable */ var_prc_out[idx]->sz=var_prc_1[idx]->sz; /* NB: must not try to free() same tally buffer twice */ /* var_prc_out[idx]->tally=var_prc_1[idx]->tally=(long *)nco_malloc(var_prc_out[idx]->sz*sizeof(long int));*/ var_prc_out[idx]->tally=(long *)nco_malloc(var_prc_out[idx]->sz*sizeof(long int)); (void)nco_zero_long(var_prc_out[idx]->sz,var_prc_out[idx]->tally); /* Weight variable by taking product of weight with variable */ (void)nco_var_mlt(var_prc_1[idx]->type,var_prc_1[idx]->sz,var_prc_1[idx]->has_mss_val,var_prc_1[idx]->mss_val,wgt_out_1->val,var_prc_1[idx]->val); (void)nco_var_mlt(var_prc_2[idx]->type,var_prc_2[idx]->sz,var_prc_2[idx]->has_mss_val,var_prc_2[idx]->mss_val,wgt_out_2->val,var_prc_2[idx]->val); /* Change missing_value of var_prc_2, if any, to missing_value of var_prc_1, if any */ has_mss_val=nco_mss_val_cnf(var_prc_1[idx],var_prc_2[idx]); /* NB: fxm: use tally to determine when to "unweight" answer? TODO */ (void)nco_var_add_tll_ncflint(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,var_prc_1[idx]->mss_val,var_prc_out[idx]->tally,var_prc_1[idx]->val,var_prc_2[idx]->val); /* Re-cast output variable to original type */ var_prc_2[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc_2[idx]); #ifdef ENABLE_MPI /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ if(RAM_OPEN) md_open=NC_WRITE|NC_SHARE|NC_DISKLESS; else md_open=NC_WRITE|NC_SHARE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp critical #endif /* _OPENMP */ #endif /* !ENABLE_MPI */ /* Common code for UP, SMP, and MPI */ { /* begin OpenMP critical */ /* Copy interpolations to output file */ if(var_prc_out[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_2[idx]->val.vp,var_prc_2[idx]->type); }else{ /* end if variable is scalar */ (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_2[idx]->val.vp,var_prc_2[idx]->type); } /* end else */ } /* end OpenMP critical */ /* Free dynamically allocated buffers */ if(var_prc_1[idx]) var_prc_1[idx]=nco_var_free(var_prc_1[idx]); if(var_prc_2[idx]) var_prc_2[idx]=nco_var_free(var_prc_2[idx]); if(var_prc_out[idx]) var_prc_out[idx]=nco_var_free(var_prc_out[idx]); #ifdef ENABLE_MPI /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ } /* end else !idx_all_wrk_ass */ } /* end while loop requesting work/token */ } /* endif Worker */ #else /* !ENABLE_MPI */ } /* end (OpenMP parallel for) loop over idx */ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\n"); /* Close input netCDF files */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_1_arr[thr_idx]); for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_2_arr[thr_idx]); #ifdef ENABLE_MPI /* Manager moves output file (closed by workers) from temporary to permanent location */ if(prc_rnk == rnk_mgr) (void)nco_fl_mv(fl_out_tmp,fl_out); #else /* !ENABLE_MPI */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); #endif /* end !ENABLE_MPI */ /* Remove local copy of file */ if(FILE_1_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_1); if(FILE_2_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_2); /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncflint-specific memory */ if(fl_in_1) fl_in_1=(char *)nco_free(fl_in_1); if(fl_in_2) fl_in_2=(char *)nco_free(fl_in_2); if(in_id_arr_1) in_id_arr_1=(int *)nco_free(in_id_arr_1); if(in_id_arr_2) in_id_arr_2=(int *)nco_free(in_id_arr_2); var_prc_1=(var_sct **)nco_free(var_prc_1); var_prc_2=(var_sct **)nco_free(var_prc_2); if(wgt_1) wgt_1=(var_sct *)nco_var_free(wgt_1); if(wgt_2) wgt_2=(var_sct *)nco_var_free(wgt_2); if(wgt_out_1) wgt_out_1=(var_sct *)nco_var_free(wgt_out_1); if(wgt_out_2) wgt_out_2=(var_sct *)nco_var_free(wgt_out_2); /* NB: free lmt[] is now referenced within lmt_all_lst[idx] */ for(idx=0;idx<nbr_dmn_fl;idx++) for(jdx=0;jdx<lmt_all_lst[idx]->lmt_dmn_nbr;jdx++) lmt_all_lst[idx]->lmt_dmn[jdx]=nco_lmt_free(lmt_all_lst[idx]->lmt_dmn[jdx]); if(nbr_dmn_fl > 0) lmt_all_lst=nco_lmt_all_lst_free(lmt_all_lst,nbr_dmn_fl); lmt=(lmt_sct**)nco_free(lmt); /* NCO-generic clean-up */ /* Free individual strings/arrays */ if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]); if(aux_nbr > 0) aux=(lmt_sct **)nco_free(aux); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0) cnk_dmn=nco_cnk_lst_free(cnk_dmn,cnk_nbr); /* Free dimension lists */ if(nbr_dmn_xtr > 0) dim=nco_dmn_lst_free(dim,nbr_dmn_xtr); if(nbr_dmn_xtr > 0) dmn_out=nco_dmn_lst_free(dmn_out,nbr_dmn_xtr); /* Free variable lists */ /* ncflint free()s _prc variables at end of main loop */ var=(var_sct **)nco_free(var); var_out=(var_sct **)nco_free(var_out); var_prc_out=(var_sct **)nco_free(var_prc_out); if(nbr_var_fix > 0) var_fix=nco_var_lst_free(var_fix,nbr_var_fix); if(nbr_var_fix > 0) var_fix_out=nco_var_lst_free(var_fix_out,nbr_var_fix); } /* !flg_mmr_cln */ #ifdef ENABLE_MPI MPI_Finalize(); #endif /* !ENABLE_MPI */ if(rcd != NC_NOERR) nco_err_exit(rcd,"main"); nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
TestQuantArray0.h
#ifndef __TESTQUANTARRAY0__ #define __TESTQUANTARRAY0__ #include "../Headers/Common.h" #include "../Headers/Timer.h" #include "../Headers/Range.h" #include "../Headers/Ref.h" #include "../Headers/Thread.h" #include "../Headers/NDArrayQuantCPU.h" #include "../Headers/NDArrayApproxCPU.h" #include "../Headers/OpsQuant.h" #include "../Tests/Utils.h" int testMNIST(const string lutfile = "../Utils/LUT_HEAM.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/MNIST/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*1*16, 5*5*16*32, 5*5*32*64, 1024*256, 256*10}; vector<size_t> sizesBiases = {16, 32, 64, 256, 10}; vector<vector<size_t>> shapesWeights = {{5*5*1, 16}, {5*5*16, 32}, {5*5*32, 64}, {1024, 256}, {256, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 1})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImages(); vector<unsigned> labels = getLabels(); float count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784); for(size_t kdx = 0; kdx < 784; kdx++) { float tmp = images[idx+jdx][kdx]; Q_image[kdx] = (Z_input + tmp / S_input > 0) ? round(Z_input + tmp / S_input) : 0; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << endl; } } cout << "Accuray: " << (count / TestSize) << endl; return 0; } int testFashionMNIST(const string &lutfile = "../Utils/LUT_HEAM.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/FashionMNIST/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*1*32, 5*5*32*64, 5*5*64*128, 2048*512, 512*10}; vector<size_t> sizesBiases = {32, 64, 128, 512, 10}; vector<vector<size_t>> shapesWeights = {{5*5*1, 32}, {5*5*32, 64}, {5*5*64, 128}, {2048, 512}, {512, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 1})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImagesFashion(); vector<unsigned> labels = getLabelsFashion(); float count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784); for(size_t kdx = 0; kdx < 784; kdx++) { float tmp = images[idx+jdx][kdx]; Q_image[kdx] = (Z_input + tmp / S_input > 0) ? round(Z_input + tmp / S_input) : 0; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << endl; } } cout << "Accuray: " << (count / TestSize) << endl; return 0; } int testCIFAR10(const string &lutfile = "../Utils/LUT_HEAM.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/CIFAR10/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*3*32, 5*5*32*64, 5*5*64*128, 2048*512, 512*10}; vector<size_t> sizesBiases = {32, 64, 128, 512, 10}; vector<vector<size_t>> shapesWeights = {{5*5*3, 32}, {5*5*32, 64}, {5*5*64, 128}, {2048, 512}, {512, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 3})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } Ref<Var> weightsConv1 = new Var(map_weights["Conv1"]); Ref<vector<int>> biasesConv1 = new vector<int>(map_Q_biases["Conv1"]); cout << "Weight Conv1: " << endl; weightsConv1->value().print(); weightsConv1->value().eval().print(); NDArrayFloatCPU<float> _weightsConv1 = weightsConv1->value().eval(); cout << "Bias Conv1: " << endl; print(*biasesConv1); NDArrayFloatCPU<float> _biasesConv1(sizesBiases[0]); for(size_t idx = 0; idx < _biasesConv1.size(); idx++) { _biasesConv1[idx] = map_S_biases["Conv1"] * (*biasesConv1)[idx]; } Ref<Var> weightsConv2 = new Var(map_weights["Conv2"]); Ref<vector<int>> biasesConv2 = new vector<int>(map_Q_biases["Conv2"]); cout << "Weight Conv2: " << endl; weightsConv2->value().print(); weightsConv2->value().eval().print(); NDArrayFloatCPU<float> _weightsConv2 = weightsConv2->value().eval(); cout << "Bias Conv2: " << endl; print(*biasesConv2); NDArrayFloatCPU<float> _biasesConv2(sizesBiases[1]); for(size_t idx = 0; idx < _biasesConv2.size(); idx++) { _biasesConv2[idx] = map_S_biases["Conv2"] * (*biasesConv2)[idx]; } Ref<Var> weightsConv3 = new Var(map_weights["Conv3"]); Ref<vector<int>> biasesConv3 = new vector<int>(map_Q_biases["Conv3"]); cout << "Weight Conv3: " << endl; weightsConv3->value().print(); weightsConv3->value().eval().print(); NDArrayFloatCPU<float> _weightsConv3 = weightsConv3->value().eval(); cout << "Bias Conv3: " << endl; print(*biasesConv3); NDArrayFloatCPU<float> _biasesConv3(sizesBiases[2]); for(size_t idx = 0; idx < _biasesConv3.size(); idx++) { _biasesConv3[idx] = map_S_biases["Conv3"] * (*biasesConv3)[idx]; } Ref<Var> weightsFC1 = new Var(map_weights["FC1"]); Ref<vector<int>> biasesFC1 = new vector<int>(map_Q_biases["FC1"]); cout << "Weight FC1: " << endl; weightsFC1->value().print(); weightsFC1->value().eval().print(); NDArrayFloatCPU<float> _weightsFC1 = weightsFC1->value().eval(); cout << "Bias FC1: " << endl; print(*biasesFC1); NDArrayFloatCPU<float> _biasesFC1(sizesBiases[3]); for(size_t idx = 0; idx < _biasesFC1.size(); idx++) { _biasesFC1[idx] = map_S_biases["FC1"] * (*biasesFC1)[idx]; } Ref<Var> weightsFC2 = new Var(map_weights["FC_Logits"]); Ref<vector<int>> biasesFC2 = new vector<int>(map_Q_biases["FC_Logits"]); cout << "Weight FC2: " << endl; weightsFC2->value().print(); weightsFC2->value().eval().print(); NDArrayFloatCPU<float> _weightsFC2 = weightsFC2->value().eval(); cout << "Bias FC2: " << endl; print(*biasesFC2); NDArrayFloatCPU<float> _biasesFC2(sizesBiases[4]); for(size_t idx = 0; idx < _biasesFC2.size(); idx++) { _biasesFC2[idx] = map_S_biases["FC_Logits"] * (*biasesFC2)[idx]; } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImagesCIFAR10(); vector<unsigned> labels = getLabelsCIFAR10(); float count = 0, _count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784*3); for(size_t kdx = 0; kdx < 784*3; kdx++) { Q_image[kdx] = images[idx+jdx][kdx]; } image_pool[jdx]->set(Q_image); } int _labels[NUMTHREADS] = {0, }; #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); NDArrayFloatCPU<float> _image({28, 28, 3}, images[idx+jdx]); _image = _image * (1.0 / 255.0); NDArrayFloatCPU<float> _conv1 = (_image.im2col({5, 5}, {1, 1}, true) * _weightsConv1).reshape({28, 28, 32}).addChWise(_biasesConv1).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv1.shape()[0] << ", " << _conv1.shape()[1] << ", " << _conv1.shape()[2] << std::endl; NDArrayFloatCPU<float> _conv2 = (_conv1.im2col({5, 5}, {1, 1}, true) * _weightsConv2).reshape({14, 14, 64}).addChWise(_biasesConv2).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv2.shape()[0] << ", " << _conv2.shape()[1] << ", " << _conv2.shape()[2] << std::endl; NDArrayFloatCPU<float> _conv3 = (_conv2.im2col({5, 5}, {1, 1}, true) * _weightsConv3).reshape({7, 7, 128}).addChWise(_biasesConv3).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv3.shape()[0] << ", " << _conv3.shape()[1] << ", " << _conv3.shape()[2] << std::endl; NDArrayFloatCPU<float> _fc1 = (_conv3.reshape({1, 2048}) * _weightsFC1 +_biasesFC1.reshape({1, 512})).ReLU(); NDArrayFloatCPU<float> _fc2 = _fc1 * _weightsFC2 +_biasesFC2.reshape({1, 10}); _labels[jdx] = _fc2.posmax(); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); size_t _label = _labels[jdx]; if(label == labels[idx+jdx]) { count++; } if(_label == labels[idx+jdx]) { _count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " / " << _label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << " / " << ((_label == labels[idx+jdx]) ? "Right" : "Wrong") << "; Accuracy: " << (count / (idx+jdx+1)) << " / " << (_count / (idx+jdx+1)) << endl; } } cout << "Accuray: " << (count / TestSize) << endl; cout << "_Accuray: " << (_count / TestSize) << endl; return 0; } int testCIFAR10AlexNet(const string &lutfile = "../Utils/LUT_HEAM.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/CIFAR10/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1a", "Conv1b", "Conv2a", "Conv2b", "Conv3a", "Conv3b", "Conv4a", "Conv4b", "FC1", "FC2", "FC_Logits"}; vector<size_t> sizesWeights = {3*3*3*96, 3*3*96*96, 3*3*96*256, 3*3*256*256, 3*3*256*384, 3*3*384*384, 3*3*384*256, 3*3*256*256, 4096*4096, 4096*4096, 4096*10}; vector<size_t> sizesBiases = {96, 96, 256, 256, 384, 384, 256, 256, 4096, 4096, 10}; vector<vector<size_t>> shapesWeights = {{3*3*3, 96}, {3*3*96, 96}, {3*3*96, 256}, {3*3*256, 256}, {3*3*256, 384}, {3*3*384, 384}, {3*3*384, 256}, {3*3*256, 256}, {4096, 4096}, {4096, 4096}, {4096, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 3})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } assert((namesLayers.size() == sizesWeights.size()) && (namesLayers.size() == sizesBiases.size()) && (namesLayers.size() == shapesWeights.size())); cout << "Building Conv1a: S = " << map_S_weights["Conv1a"] << "; Z = " << map_Z_weights["Conv1a"] << "; S_act = " << map_S_activations["Conv1a"] << "; Z_act = " << map_Z_activations["Conv1a"] << endl; vector<Ref<Var>> weightsConv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1a_pool.push_back(new Var(map_weights["Conv1a"])); } vector<Ref<vector<int>>> biasesConv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1a_pool.push_back(new vector<int>(map_Q_biases["Conv1a"])); } vector<Ref<Var>> conv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1a"], map_Z_activations["Conv1a"], input_pool[idx], weightsConv1a_pool[idx], biasesConv1a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv1b: S = " << map_S_weights["Conv1b"] << "; Z = " << map_Z_weights["Conv1b"] << "; S_act = " << map_S_activations["Conv1b"] << "; Z_act = " << map_Z_activations["Conv1b"] << endl; vector<Ref<Var>> weightsConv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1b_pool.push_back(new Var(map_weights["Conv1b"])); } vector<Ref<vector<int>>> biasesConv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1b_pool.push_back(new vector<int>(map_Q_biases["Conv1b"])); } vector<Ref<Var>> conv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1b"], map_Z_activations["Conv1b"], conv1a_pool[idx], weightsConv1b_pool[idx], biasesConv1b_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv2a: S = " << map_S_weights["Conv2a"] << "; Z = " << map_Z_weights["Conv2a"] << "; S_act = " << map_S_activations["Conv2a"] << "; Z_act = " << map_Z_activations["Conv2a"] << endl; vector<Ref<Var>> weightsConv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2a_pool.push_back(new Var(map_weights["Conv2a"])); } vector<Ref<vector<int>>> biasesConv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2a_pool.push_back(new vector<int>(map_Q_biases["Conv2a"])); } vector<Ref<Var>> conv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2a"], map_Z_activations["Conv2a"], conv1b_pool[idx], weightsConv2a_pool[idx], biasesConv2a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv2b: S = " << map_S_weights["Conv2b"] << "; Z = " << map_Z_weights["Conv2b"] << "; S_act = " << map_S_activations["Conv2b"] << "; Z_act = " << map_Z_activations["Conv2b"] << endl; vector<Ref<Var>> weightsConv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2b_pool.push_back(new Var(map_weights["Conv2b"])); } vector<Ref<vector<int>>> biasesConv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2b_pool.push_back(new vector<int>(map_Q_biases["Conv2b"])); } vector<Ref<Var>> preconv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2b"], map_Z_activations["Conv2b"], conv2a_pool[idx], weightsConv2b_pool[idx], biasesConv2b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2b_pool.push_back(MaxPool<NDArray>(preconv2b_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3a: S = " << map_S_weights["Conv3a"] << "; Z = " << map_Z_weights["Conv3a"] << "; S_act = " << map_S_activations["Conv3a"] << "; Z_act = " << map_Z_activations["Conv3a"] << endl; vector<Ref<Var>> weightsConv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3a_pool.push_back(new Var(map_weights["Conv3a"])); } vector<Ref<vector<int>>> biasesConv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3a_pool.push_back(new vector<int>(map_Q_biases["Conv3a"])); } vector<Ref<Var>> conv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3a"], map_Z_activations["Conv3a"], conv2b_pool[idx], weightsConv3a_pool[idx], biasesConv3a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv3b: S = " << map_S_weights["Conv3b"] << "; Z = " << map_Z_weights["Conv3b"] << "; S_act = " << map_S_activations["Conv3b"] << "; Z_act = " << map_Z_activations["Conv3b"] << endl; vector<Ref<Var>> weightsConv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3b_pool.push_back(new Var(map_weights["Conv3b"])); } vector<Ref<vector<int>>> biasesConv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3b_pool.push_back(new vector<int>(map_Q_biases["Conv3b"])); } vector<Ref<Var>> preconv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3b"], map_Z_activations["Conv3b"], conv3a_pool[idx], weightsConv3b_pool[idx], biasesConv3b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3b_pool.push_back(MaxPool<NDArray>(preconv3b_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv4a: S = " << map_S_weights["Conv4a"] << "; Z = " << map_Z_weights["Conv4a"] << "; S_act = " << map_S_activations["Conv4a"] << "; Z_act = " << map_Z_activations["Conv4a"] << endl; vector<Ref<Var>> weightsConv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv4a_pool.push_back(new Var(map_weights["Conv4a"])); } vector<Ref<vector<int>>> biasesConv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv4a_pool.push_back(new vector<int>(map_Q_biases["Conv4a"])); } vector<Ref<Var>> conv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv4a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv4a"], map_Z_activations["Conv4a"], conv3b_pool[idx], weightsConv4a_pool[idx], biasesConv4a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv4b: S = " << map_S_weights["Conv4b"] << "; Z = " << map_Z_weights["Conv4b"] << "; S_act = " << map_S_activations["Conv4b"] << "; Z_act = " << map_Z_activations["Conv4b"] << endl; vector<Ref<Var>> weightsConv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv4b_pool.push_back(new Var(map_weights["Conv4b"])); } vector<Ref<vector<int>>> biasesConv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv4b_pool.push_back(new vector<int>(map_Q_biases["Conv4b"])); } vector<Ref<Var>> preconv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv4b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv4b"], map_Z_activations["Conv4b"], conv4a_pool[idx], weightsConv4b_pool[idx], biasesConv4b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv4b_pool.push_back(MaxPool<NDArray>(preconv4b_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv4b_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC2"] << "; Z = " << map_Z_weights["FC2"] << "; S_act = " << map_S_activations["FC2"] << "; Z_act = " << map_Z_activations["FC2"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC2"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC2"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MADReLU<NDArray>(map_S_activations["FC2"], map_Z_activations["FC2"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } cout << "Building FC_Logits: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC3_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC3_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc3_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc2_pool[idx], weightsFC3_pool[idx], biasesFC3_pool[idx])); } vector<vector<float>> images = getImagesCIFAR10(); vector<unsigned> labels = getLabelsCIFAR10(); float count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784*3); for(size_t kdx = 0; kdx < 784*3; kdx++) { Q_image[kdx] = images[idx+jdx][kdx]; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc3_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc3_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } // fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " / " << labels[idx+jdx] << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << "; Accuracy: " << (count / (idx+jdx+1)) << endl; } } cout << "Accuray: " << (count / TestSize) << endl; return 0; } int testCIFAR10AlexNetExport(const string &lutfile = "../Utils/LUT_HEAM.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/CIFAR10/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1a", "Conv1b", "Conv2a", "Conv2b", "Conv3a", "Conv3b", "Conv4a", "Conv4b", "FC1", "FC2", "FC_Logits"}; vector<size_t> sizesWeights = {3*3*3*96, 3*3*96*96, 3*3*96*256, 3*3*256*256, 3*3*256*384, 3*3*384*384, 3*3*384*256, 3*3*256*256, 4096*4096, 4096*4096, 4096*10}; vector<size_t> sizesBiases = {96, 96, 256, 256, 384, 384, 256, 256, 4096, 4096, 10}; vector<vector<size_t>> shapesWeights = {{3*3*3, 96}, {3*3*96, 96}, {3*3*96, 256}, {3*3*256, 256}, {3*3*256, 384}, {3*3*384, 384}, {3*3*384, 256}, {3*3*256, 256}, {4096, 4096}, {4096, 4096}, {4096, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 3})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } assert((namesLayers.size() == sizesWeights.size()) && (namesLayers.size() == sizesBiases.size()) && (namesLayers.size() == shapesWeights.size())); cout << "Building Conv1a: S = " << map_S_weights["Conv1a"] << "; Z = " << map_Z_weights["Conv1a"] << "; S_act = " << map_S_activations["Conv1a"] << "; Z_act = " << map_Z_activations["Conv1a"] << endl; vector<Ref<Var>> weightsConv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1a_pool.push_back(new Var(map_weights["Conv1a"])); } vector<Ref<vector<int>>> biasesConv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1a_pool.push_back(new vector<int>(map_Q_biases["Conv1a"])); } vector<Ref<Var>> conv1a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1a"], map_Z_activations["Conv1a"], input_pool[idx], weightsConv1a_pool[idx], biasesConv1a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv1b: S = " << map_S_weights["Conv1b"] << "; Z = " << map_Z_weights["Conv1b"] << "; S_act = " << map_S_activations["Conv1b"] << "; Z_act = " << map_Z_activations["Conv1b"] << endl; vector<Ref<Var>> weightsConv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1b_pool.push_back(new Var(map_weights["Conv1b"])); } vector<Ref<vector<int>>> biasesConv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1b_pool.push_back(new vector<int>(map_Q_biases["Conv1b"])); } vector<Ref<Var>> conv1b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1b"], map_Z_activations["Conv1b"], conv1a_pool[idx], weightsConv1b_pool[idx], biasesConv1b_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv2a: S = " << map_S_weights["Conv2a"] << "; Z = " << map_Z_weights["Conv2a"] << "; S_act = " << map_S_activations["Conv2a"] << "; Z_act = " << map_Z_activations["Conv2a"] << endl; vector<Ref<Var>> weightsConv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2a_pool.push_back(new Var(map_weights["Conv2a"])); } vector<Ref<vector<int>>> biasesConv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2a_pool.push_back(new vector<int>(map_Q_biases["Conv2a"])); } vector<Ref<Var>> conv2a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2a"], map_Z_activations["Conv2a"], conv1b_pool[idx], weightsConv2a_pool[idx], biasesConv2a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv2b: S = " << map_S_weights["Conv2b"] << "; Z = " << map_Z_weights["Conv2b"] << "; S_act = " << map_S_activations["Conv2b"] << "; Z_act = " << map_Z_activations["Conv2b"] << endl; vector<Ref<Var>> weightsConv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2b_pool.push_back(new Var(map_weights["Conv2b"])); } vector<Ref<vector<int>>> biasesConv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2b_pool.push_back(new vector<int>(map_Q_biases["Conv2b"])); } vector<Ref<Var>> preconv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2b"], map_Z_activations["Conv2b"], conv2a_pool[idx], weightsConv2b_pool[idx], biasesConv2b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv2b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2b_pool.push_back(MaxPool<NDArray>(preconv2b_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3a: S = " << map_S_weights["Conv3a"] << "; Z = " << map_Z_weights["Conv3a"] << "; S_act = " << map_S_activations["Conv3a"] << "; Z_act = " << map_Z_activations["Conv3a"] << endl; vector<Ref<Var>> weightsConv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3a_pool.push_back(new Var(map_weights["Conv3a"])); } vector<Ref<vector<int>>> biasesConv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3a_pool.push_back(new vector<int>(map_Q_biases["Conv3a"])); } vector<Ref<Var>> conv3a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3a"], map_Z_activations["Conv3a"], conv2b_pool[idx], weightsConv3a_pool[idx], biasesConv3a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv3b: S = " << map_S_weights["Conv3b"] << "; Z = " << map_Z_weights["Conv3b"] << "; S_act = " << map_S_activations["Conv3b"] << "; Z_act = " << map_Z_activations["Conv3b"] << endl; vector<Ref<Var>> weightsConv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3b_pool.push_back(new Var(map_weights["Conv3b"])); } vector<Ref<vector<int>>> biasesConv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3b_pool.push_back(new vector<int>(map_Q_biases["Conv3b"])); } vector<Ref<Var>> preconv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3b"], map_Z_activations["Conv3b"], conv3a_pool[idx], weightsConv3b_pool[idx], biasesConv3b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv3b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3b_pool.push_back(MaxPool<NDArray>(preconv3b_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv4a: S = " << map_S_weights["Conv4a"] << "; Z = " << map_Z_weights["Conv4a"] << "; S_act = " << map_S_activations["Conv4a"] << "; Z_act = " << map_Z_activations["Conv4a"] << endl; vector<Ref<Var>> weightsConv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv4a_pool.push_back(new Var(map_weights["Conv4a"])); } vector<Ref<vector<int>>> biasesConv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv4a_pool.push_back(new vector<int>(map_Q_biases["Conv4a"])); } vector<Ref<Var>> conv4a_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv4a_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv4a"], map_Z_activations["Conv4a"], conv3b_pool[idx], weightsConv4a_pool[idx], biasesConv4a_pool[idx], {3, 3}, {1, 1}, true)); } cout << "Building Conv4b: S = " << map_S_weights["Conv4b"] << "; Z = " << map_Z_weights["Conv4b"] << "; S_act = " << map_S_activations["Conv4b"] << "; Z_act = " << map_Z_activations["Conv4b"] << endl; vector<Ref<Var>> weightsConv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv4b_pool.push_back(new Var(map_weights["Conv4b"])); } vector<Ref<vector<int>>> biasesConv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv4b_pool.push_back(new vector<int>(map_Q_biases["Conv4b"])); } vector<Ref<Var>> preconv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv4b_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv4b"], map_Z_activations["Conv4b"], conv4a_pool[idx], weightsConv4b_pool[idx], biasesConv4b_pool[idx], {3, 3}, {1, 1}, true)); } vector<Ref<Var>> conv4b_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv4b_pool.push_back(MaxPool<NDArray>(preconv4b_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv4b_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC2"] << "; Z = " << map_Z_weights["FC2"] << "; S_act = " << map_S_activations["FC2"] << "; Z_act = " << map_Z_activations["FC2"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC2"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC2"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MADReLU<NDArray>(map_S_activations["FC2"], map_Z_activations["FC2"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } cout << "Building FC_Logits: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC3_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC3_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc3_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc2_pool[idx], weightsFC3_pool[idx], biasesFC3_pool[idx])); } vector<vector<float>> images = getImagesCIFAR10(); vector<unsigned> labels = getLabelsCIFAR10(); float count = 0; size_t TestSize = 1000; vector<vector<unsigned>> layer0(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer1(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer2(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer3(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer4(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer5(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer6(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer7(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer8(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer9(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer10(TestSize, vector<unsigned>()); vector<vector<unsigned>> layer11(TestSize, vector<unsigned>()); for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784*3); for(size_t kdx = 0; kdx < 784*3; kdx++) { Q_image[kdx] = images[idx+jdx][kdx]; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc3_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t index = idx + jdx; auto temp0 = image_pool[jdx].value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp0.size(); kdx++) { layer0[index].push_back(temp0[kdx]); } auto temp1 = conv1a_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp1.size(); kdx++) { layer1[index].push_back(temp1[kdx]); } auto temp2 = conv1b_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp2.size(); kdx++) { layer2[index].push_back(temp2[kdx]); } auto temp3 = conv2a_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp3.size(); kdx++) { layer3[index].push_back(temp3[kdx]); } auto temp4 = conv2b_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp4.size(); kdx++) { layer4[index].push_back(temp4[kdx]); } auto temp5 = conv3a_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp5.size(); kdx++) { layer5[index].push_back(temp5[kdx]); } auto temp6 = conv3b_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp6.size(); kdx++) { layer6[index].push_back(temp6[kdx]); } auto temp7 = conv4a_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp7.size(); kdx++) { layer7[index].push_back(temp7[kdx]); } auto temp8 = conv4b_pool[jdx].value().value().im2col({3, 3}, {1, 1}, true); for(size_t kdx = 0; kdx < temp8.size(); kdx++) { layer8[index].push_back(temp8[kdx]); } auto temp9 = fc1_pool[jdx].value().value(); for(size_t kdx = 0; kdx < temp9.size(); kdx++) { layer9[index].push_back(temp9[kdx]); } auto temp10 = fc2_pool[jdx].value().value(); for(size_t kdx = 0; kdx < temp10.size(); kdx++) { layer10[index].push_back(temp10[kdx]); } auto temp11 = fc3_pool[jdx].value().value(); for(size_t kdx = 0; kdx < temp11.size(); kdx++) { layer11[index].push_back(temp11[kdx]); } size_t label = fc3_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } // fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " / " << labels[idx+jdx] << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << "; Accuracy: " << (count / (idx+jdx+1)) << endl; } } cout << "Accuray: " << (count / TestSize) << endl; ofstream fout0("images_AlexNet.txt"); ofstream fout1("layer1_AlexNet.txt"); ofstream fout2("layer2_AlexNet.txt"); ofstream fout3("layer3_AlexNet.txt"); ofstream fout4("layer4_AlexNet.txt"); ofstream fout5("layer5_AlexNet.txt"); ofstream fout6("layer6_AlexNet.txt"); ofstream fout7("layer7_AlexNet.txt"); ofstream fout8("layer8_AlexNet.txt"); ofstream fout9("layer9_AlexNet.txt"); ofstream fout10("layer10_AlexNet.txt"); ofstream fout11("layer11_AlexNet.txt"); for(const auto &line: layer0) { for(const auto &elem: line) { fout0 << elem << " "; } fout0 << endl; } for(const auto &line: layer1) { for(const auto &elem: line) { fout1 << elem << " "; } fout1 << endl; } for(const auto &line: layer2) { for(const auto &elem: line) { fout2 << elem << " "; } fout2 << endl; } for(const auto &line: layer3) { for(const auto &elem: line) { fout3 << elem << " "; } fout3 << endl; } for(const auto &line: layer4) { for(const auto &elem: line) { fout4 << elem << " "; } fout4 << endl; } for(const auto &line: layer5) { for(const auto &elem: line) { fout5 << elem << " "; } fout5 << endl; } for(const auto &line: layer5) { for(const auto &elem: line) { fout5 << elem << " "; } fout5 << endl; } for(const auto &line: layer6) { for(const auto &elem: line) { fout6 << elem << " "; } fout6 << endl; } for(const auto &line: layer7) { for(const auto &elem: line) { fout7 << elem << " "; } fout7 << endl; } for(const auto &line: layer8) { for(const auto &elem: line) { fout8 << elem << " "; } fout8 << endl; } for(const auto &line: layer9) { for(const auto &elem: line) { fout9 << elem << " "; } fout9 << endl; } for(const auto &line: layer10) { for(const auto &elem: line) { fout10 << elem << " "; } fout10 << endl; } for(const auto &line: layer11) { for(const auto &elem: line) { fout11 << elem << " "; } fout11 << endl; } fout0.close(); fout1.close(); fout2.close(); fout3.close(); fout4.close(); fout5.close(); fout6.close(); fout7.close(); fout8.close(); fout9.close(); fout10.close(); fout11.close(); return 0; } #endif
l1_normMEX.c
#include "mex.h" #include <math.h> #include "emmintrin.h" #include "xmmintrin.h" #ifdef __GNU__ #include <omp.h> #endif #ifndef MAXCORES #define MAXCORES 1 #endif void mexFunction(int nlhs, mxArray *left[], int nrhs, const mxArray *right[]) { /* Declare variables */ mwSize elem, cmplx, cmplx1, cmplx2, cmplx3; long long i, elem2; const mwSize size[]={1,1}; mxClassID precision, precision1; mxArray *X1, *X2, *T, *Y; double *pX1r, *pX1i, *pX2r, *pX2i, *pYr, *pT, *pSd, Td, Sd; double xr, xi, L1, dL1[2]; __m128d vTd, vSd, vL1, vxr, vxi; float *pX1rf, *pX1if, *pX2rf, *pX2if, *pYrf, *pTf, *pSf, Tf, Sf; float xrf, xif, L1f, dL1f[4]; __m128 vTf, vSf, vL1f, vxrf, vxif; /* Get number of elements */ elem = mxGetNumberOfElements(right[0]); /* mexPrintf("elem: %i\n",elem);*/ /* Test for complex and obtain data class */ cmplx = mxIsComplex(right[0]); cmplx1 = mxIsComplex(right[1]); cmplx2 = mxIsComplex(right[2]); cmplx3 = mxIsComplex(right[3]); if (cmplx != cmplx1) mexErrMsgTxt("Inputs 0 and 1 have different complexity"); if (cmplx2) mexErrMsgTxt("Input 2 is complex (must be real)"); if (cmplx3) mexErrMsgTxt("Input 3 is complex (must be real)"); /* Obtain and test data class */ precision = mxGetClassID(right[0]); precision1 = mxGetClassID(right[1]); if (precision != precision1) mexErrMsgTxt("Inputs 0 and 1 have different precision"); /* Get pointers to input arrays and create output array */ Y = mxCreateNumericArray(2, size, precision, mxREAL); if (precision == mxDOUBLE_CLASS) { pX1r = mxGetPr(right[0]); pX2r = mxGetPr(right[1]); if (cmplx) { pX1i = mxGetPi(right[0]); pX2i = mxGetPi(right[1]); } pYr = mxGetPr(Y); } else { pX1rf = mxGetData(right[0]); pX2rf = mxGetData(right[1]); if (cmplx) { pX1if = mxGetImagData(right[0]); pX2if = mxGetImagData(right[1]); } pYrf = mxGetData(Y); } /* Get pointer to input scalar */ if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) pT = mxGetData(right[2]); else pTf = mxGetData(right[2]); /* Get pointer to smoothing factor */ if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) pSd = mxGetData(right[3]); else pSf = mxGetData(right[3]); /* Convert scalars to same data type as input arrays */ if (precision == mxDOUBLE_CLASS) { if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Td = (double)pT[0]; else Td = (double)pTf[0]; if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) Sd = (double)pSd[0]; else Sd = (double)pSf[0]; } else { if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Tf = (float)pT[0]; else Tf = (float)pTf[0]; if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) Sf = (float)pSd[0]; else Sf = (float)pSf[0]; } #ifdef __GNU__ /* Set number of threads */ omp_set_num_threads(MAXCORES); #endif /* Loop through and compute the abs of the combined coefficients then sum */ if (precision == mxDOUBLE_CLASS) { if (cmplx) { /* Compute the number of elements for SIMD loop */ elem2 = (elem/2)*2; /* SIMD variables */ vTd = _mm_load1_pd(&Td); vSd = _mm_load1_pd(&Sd); vL1 = _mm_setzero_pd(); #pragma omp parallel for private(i,vxr,vxi) reduction(+: vL1) for (i=0; i<elem2; i+=2) { vxr = _mm_add_pd(_mm_load_pd(pX1r+i),_mm_mul_pd(vTd,_mm_load_pd(pX2r+i))); vxr = _mm_mul_pd(vxr,vxr); vxi = _mm_add_pd(_mm_load_pd(pX1i+i),_mm_mul_pd(vTd,_mm_load_pd(pX2i+i))); vxi = _mm_mul_pd(vxi,vxi); vL1 = _mm_add_pd(vL1,_mm_sqrt_pd(_mm_add_pd(_mm_add_pd(vxr,vxi),vSd))); } /* Save results */ _mm_store_pd(dL1,vL1); L1 = dL1[0] + dL1[1]; /* Finish the last few elements */ for (i=elem2; i<elem; i++) { xr = pX1r[i] + Td*pX2r[i]; xi = pX1i[i] + Td*pX2i[i]; L1 += sqrt(xr*xr + xi*xi + Sd); } } else { #pragma omp parallel for private(i,xr) reduction(+: L1) for (i=0; i<elem; i++) { xr = pX1r[i] + Td*pX2r[i]; L1 += sqrt(xr*xr + Sd); /*L1 += fabs(pX1r[i] + Td*pX2r[i]);*/ } } pYr[0] = L1; } else { if (cmplx) { /* Compute the number of elements for SIMD loop */ elem2 = (elem/4)*4; /* SIMD variables */ vTf = _mm_load1_ps(&Tf); vSf = _mm_load1_ps(&Sf); vL1f = _mm_setzero_ps(); #pragma omp parallel for private(i,vxrf,vxif) reduction(+: vL1f) for (i=0; i<elem2; i+=4) { vxrf = _mm_add_ps(_mm_load_ps(pX1rf+i),_mm_mul_ps(vTf,_mm_load_ps(pX2rf+i))); vxrf = _mm_mul_ps(vxrf,vxrf); vxif = _mm_add_ps(_mm_load_ps(pX1if+i),_mm_mul_ps(vTf,_mm_load_ps(pX2if+i))); vxif = _mm_mul_ps(vxif,vxif); vL1f = _mm_add_ps(vL1f,_mm_sqrt_ps(_mm_add_ps(_mm_add_ps(vxrf,vxif),vSf))); } /* Save results */ _mm_store_ps(dL1f,vL1f); L1f = dL1f[0] + dL1f[1] + dL1f[2] + dL1f[3]; /* Finish the last few elements */ for (i=elem2; i<elem; i++) { xrf = pX1rf[i] + Tf*pX2rf[i]; xif = pX1if[i] + Tf*pX2if[i]; L1f += sqrt(xrf*xrf + xif*xif + Sf); } pYrf[0] = L1f; } else { #pragma omp parallel for private(i,xrf) reduction(+: L1) for (i=0; i<elem; i++) { xrf = pX1rf[i] + Tf*pX2rf[i]; L1 += sqrt(xrf*xrf + Sf); /*L1 += fabs(pX1rf[i] + Tf*pX2rf[i]);*/ } pYrf[0] = L1; } } /* Return values */ left[0] = Y; }